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 $this->showResults( $term );
180 # If there's an exact or very near match, jump right there.
181 $t = SearchEngine
::getNearMatch( $term );
183 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
184 # Hook requested termination
188 if( !is_null( $t ) ) {
189 $this->getOutput()->redirect( $t->getFullURL() );
192 # No match, generate an edit URL
193 $t = Title
::newFromText( $term );
194 if( !is_null( $t ) ) {
196 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
197 wfDebugLog( 'nogomatch', $t->getText(), false );
199 # If the feature is enabled, go straight to the edit page
201 $this->getOutput()->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
205 $this->showResults( $term );
209 * @param $term String
211 public function showResults( $term ) {
212 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
213 wfProfileIn( __METHOD__
);
215 $search = $this->getSearchEngine();
216 $search->setLimitOffset( $this->limit
, $this->offset
);
217 $search->setNamespaces( $this->namespaces
);
218 $search->showRedirects
= $this->searchRedirects
; // BC
219 $search->setFeatureData( 'list-redirects', $this->searchRedirects
);
220 $search->prefix
= $this->mPrefix
;
221 $term = $search->transformSearchTerm($term);
223 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
225 $this->setupPage( $term );
227 $out = $this->getOutput();
229 if ( $wgDisableTextSearch ) {
230 if ( $wgSearchForwardUrl ) {
231 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
232 $out->redirect( $url );
235 Xml
::openElement( 'fieldset' ) .
236 Xml
::element( 'legend', null, wfMsg( 'search-external' ) ) .
237 Xml
::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
238 wfMsg( 'googlesearch',
239 htmlspecialchars( $term ),
240 htmlspecialchars( 'UTF-8' ),
241 htmlspecialchars( wfMsg( 'searchbutton' ) )
243 Xml
::closeElement( 'fieldset' )
246 wfProfileOut( __METHOD__
);
250 $t = Title
::newFromText( $term );
252 // fetch search results
253 $rewritten = $search->replacePrefixes($term);
255 $titleMatches = $search->searchTitle( $rewritten );
256 if( !( $titleMatches instanceof SearchResultTooMany
) ) {
257 $textMatches = $search->searchText( $rewritten );
260 // did you mean... suggestions
261 if( $textMatches && $textMatches->hasSuggestion() ) {
262 $st = SpecialPage
::getTitleFor( 'Search' );
264 # mirror Go/Search behaviour of original request ..
265 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
267 if( $this->fulltext
!= null ) {
268 $didYouMeanParams['fulltext'] = $this->fulltext
;
271 $stParams = array_merge(
273 $this->powerSearchOptions()
276 $suggestionSnippet = $textMatches->getSuggestionSnippet();
278 if( $suggestionSnippet == '' ) {
279 $suggestionSnippet = null;
282 $suggestLink = Linker
::linkKnown(
289 $this->didYouMeanHtml
= '<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>';
291 // start rendering the page
296 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
298 'action' => $wgScript
303 Xml
::openElement( 'table', array( 'id'=>'mw-search-top-table', 'border'=>0, 'cellpadding'=>0, 'cellspacing'=>0 ) ) .
304 Xml
::openElement( 'tr' ) .
305 Xml
::openElement( 'td' ) . "\n" .
306 $this->shortDialog( $term ) .
307 Xml
::closeElement('td') .
308 Xml
::closeElement('tr') .
309 Xml
::closeElement('table')
312 // Sometimes the search engine knows there are too many hits
313 if( $titleMatches instanceof SearchResultTooMany
) {
314 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
315 wfProfileOut( __METHOD__
);
319 $filePrefix = $wgContLang->getFormattedNsText(NS_FILE
).':';
320 if( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
321 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
322 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
323 $out->addHTML( '</form>' );
324 // Empty query -- straight view of search form
325 wfProfileOut( __METHOD__
);
329 // Get number of results
330 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
331 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
332 // Total initial query matches (possible false positives)
333 $num = $titleMatchesNum +
$textMatchesNum;
335 // Get total actual results (after second filtering, if any)
336 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
337 $titleMatches->getTotalHits() : $titleMatchesNum;
338 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
339 $textMatches->getTotalHits() : $textMatchesNum;
341 // get total number of results if backend can calculate it
343 if($titleMatches && !is_null( $titleMatches->getTotalHits() ) )
344 $totalRes +
= $titleMatches->getTotalHits();
345 if($textMatches && !is_null( $textMatches->getTotalHits() ))
346 $totalRes +
= $textMatches->getTotalHits();
348 // show number of results and current offset
349 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
350 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
353 $out->addHtml( Xml
::closeElement( 'form' ) );
354 $out->addHtml( "<div class='searchresults'>" );
357 if( $num ||
$this->offset
) {
358 // Show the create link ahead
359 $this->showCreateLink( $t );
360 $prevnext = $this->getLanguage()->viewPrevNext( $this->getTitle(), $this->offset
, $this->limit
,
361 $this->powerSearchOptions() +
array( 'search' => $term ),
362 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
364 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
365 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
367 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
370 $out->parserOptions()->setEditSection( false );
371 if( $titleMatches ) {
372 if( $numTitleMatches > 0 ) {
373 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
374 $out->addHTML( $this->showMatches( $titleMatches ) );
376 $titleMatches->free();
379 // output appropriate heading
380 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
381 // if no title matches the heading is redundant
382 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
383 } elseif( $totalRes == 0 ) {
384 # Don't show the 'no text matches' if we received title matches
385 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
387 // show interwiki results if any
388 if( $textMatches->hasInterwikiResults() ) {
389 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
392 if( $numTextMatches > 0 ) {
393 $out->addHTML( $this->showMatches( $textMatches ) );
396 $textMatches->free();
399 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
400 $this->showCreateLink( $t );
402 $out->addHtml( "</div>" );
404 if( $num ||
$this->offset
) {
405 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
407 wfProfileOut( __METHOD__
);
413 protected function showCreateLink( $t ) {
414 // show direct page/create link if applicable
416 // Check DBkey !== '' in case of fragment link only.
417 if( is_null( $t ) ||
$t->getDBkey() === '' ) {
419 // preserve the paragraph for margins etc...
420 $this->getOutput()->addHtml( '<p></p>' );
424 if( $t->isKnown() ) {
425 $messageName = 'searchmenu-exists';
426 } elseif( $t->userCan( 'create' ) ) {
427 $messageName = 'searchmenu-new';
429 $messageName = 'searchmenu-new-nocreate';
431 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ) );
432 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
434 // Extensions using the hook might still return an empty $messageName
436 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
438 // preserve the paragraph for margins etc...
439 $this->getOutput()->addHtml( '<p></p>' );
444 * @param $term string
446 protected function setupPage( $term ) {
447 # Should advanced UI be used?
448 $this->searchAdvanced
= ($this->profile
=== 'advanced');
449 $out = $this->getOutput();
450 if( strval( $term ) !== '' ) {
451 $out->setPageTitle( $this->msg( 'searchresults' ) );
452 $out->setHTMLTitle( $this->msg( 'pagetitle', $this->msg( 'searchresults-title', $term )->plain() ) );
454 // add javascript specific to special:search
455 $out->addModules( 'mediawiki.special.search' );
459 * Extract "power search" namespace settings from the request object,
460 * returning a list of index numbers to search.
462 * @param $request WebRequest
465 protected function powerSearch( &$request ) {
467 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
468 if( $request->getCheck( 'ns' . $ns ) ) {
477 * Reconstruct the 'power search' options for links
481 protected function powerSearchOptions() {
483 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
484 if( $this->profile
!== 'advanced' ) {
485 $opt['profile'] = $this->profile
;
487 foreach( $this->namespaces
as $n ) {
491 return $opt +
$this->extraParams
;
495 * Show whole set of results
497 * @param $matches SearchResultSet
501 protected function showMatches( &$matches ) {
503 wfProfileIn( __METHOD__
);
505 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
508 $infoLine = $matches->getInfo();
509 if( !is_null($infoLine) ) {
510 $out .= "\n<!-- {$infoLine} -->\n";
512 $out .= "<ul class='mw-search-results'>\n";
513 $result = $matches->next();
515 $out .= $this->showHit( $result, $terms );
516 $result = $matches->next();
520 // convert the whole thing to desired language variant
521 $out = $wgContLang->convert( $out );
522 wfProfileOut( __METHOD__
);
527 * Format a single hit result
529 * @param $result SearchResult
530 * @param $terms Array: terms to highlight
534 protected function showHit( $result, $terms ) {
535 wfProfileIn( __METHOD__
);
537 if( $result->isBrokenTitle() ) {
538 wfProfileOut( __METHOD__
);
539 return "<!-- Broken link in search result -->\n";
542 $t = $result->getTitle();
544 $titleSnippet = $result->getTitleSnippet($terms);
546 if( $titleSnippet == '' )
547 $titleSnippet = null;
551 wfRunHooks( 'ShowSearchHitTitle',
552 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
554 $link = Linker
::linkKnown(
559 //If page content is not readable, just return the title.
560 //This is not quite safe, but better than showing excerpts from non-readable pages
561 //Note that hiding the entry entirely would screw up paging.
562 if( !$t->userCan( 'read' ) ) {
563 wfProfileOut( __METHOD__
);
564 return "<li>{$link}</li>\n";
567 // If the page doesn't *exist*... our search index is out of date.
568 // The least confusing at this point is to drop the result.
569 // You may get less results, but... oh well. :P
570 if( $result->isMissingRevision() ) {
571 wfProfileOut( __METHOD__
);
572 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
575 // format redirects / relevant sections
576 $redirectTitle = $result->getRedirectTitle();
577 $redirectText = $result->getRedirectSnippet($terms);
578 $sectionTitle = $result->getSectionTitle();
579 $sectionText = $result->getSectionSnippet($terms);
582 if( !is_null($redirectTitle) ) {
583 if( $redirectText == '' )
584 $redirectText = null;
586 $redirect = "<span class='searchalttitle'>" .
599 if( !is_null($sectionTitle) ) {
600 if( $sectionText == '' )
603 $section = "<span class='searchalttitle'>" .
605 'search-section', Linker
::linkKnown(
613 // format text extract
614 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
616 $lang = $this->getLanguage();
619 if( is_null( $result->getScore() ) ) {
620 // Search engine doesn't report scoring info
623 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
624 $score = wfMsg( 'search-result-score', $lang->formatNum( $percent ) )
628 // format description
629 $byteSize = $result->getByteSize();
630 $wordCount = $result->getWordCount();
631 $timestamp = $result->getTimestamp();
633 'search-result-size',
634 array( 'parsemag', 'escape' ),
635 $lang->formatSize( $byteSize ),
636 $lang->formatNum( $wordCount )
639 if( $t->getNamespace() == NS_CATEGORY
) {
640 $cat = Category
::newFromTitle( $t );
642 'search-result-category-size',
643 array( 'parsemag', 'escape' ),
644 $lang->formatNum( $cat->getPageCount() ),
645 $lang->formatNum( $cat->getSubcatCount() ),
646 $lang->formatNum( $cat->getFileCount() )
650 $date = $lang->timeanddate( $timestamp );
652 // link to related articles if supported
654 if( $result->hasRelated() ) {
655 $st = SpecialPage
::getTitleFor( 'Search' );
656 $stParams = array_merge(
657 $this->powerSearchOptions(),
659 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
660 'fulltext' => wfMsg( 'search' )
664 $related = ' -- ' . Linker
::linkKnown(
666 wfMsg('search-relatedarticle'),
672 // Include a thumbnail for media files...
673 if( $t->getNamespace() == NS_FILE
) {
674 $img = wfFindFile( $t );
676 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
678 $desc = wfMsg( 'parentheses', $img->getShortDesc() );
679 wfProfileOut( __METHOD__
);
680 // Float doesn't seem to interact well with the bullets.
681 // Table messes up vertical alignment of the bullets.
682 // Bullets are therefore disabled (didn't look great anyway).
684 '<table class="searchResultImage">' .
686 '<td width="120" align="center" valign="top">' .
687 $thumb->toHtml( array( 'desc-link' => true ) ) .
689 '<td valign="top">' .
692 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
701 wfProfileOut( __METHOD__
);
702 return "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
703 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
709 * Show results from other wikis
711 * @param $matches SearchResultSet
712 * @param $query String
716 protected function showInterwiki( &$matches, $query ) {
718 wfProfileIn( __METHOD__
);
719 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
721 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
722 wfMsg('search-interwiki-caption')."</div>\n";
723 $out .= "<ul class='mw-search-iwresults'>\n";
725 // work out custom project captions
726 $customCaptions = array();
727 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
728 foreach($customLines as $line) {
729 $parts = explode(":",$line,2);
730 if(count($parts) == 2) // validate line
731 $customCaptions[$parts[0]] = $parts[1];
735 $result = $matches->next();
737 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
738 $prev = $result->getInterwikiPrefix();
739 $result = $matches->next();
741 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
742 $out .= "</ul></div>\n";
744 // convert the whole thing to desired language variant
745 $out = $wgContLang->convert( $out );
746 wfProfileOut( __METHOD__
);
751 * Show single interwiki link
753 * @param $result SearchResult
754 * @param $lastInterwiki String
755 * @param $terms Array
756 * @param $query String
757 * @param $customCaptions Array: iw prefix -> caption
761 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
762 wfProfileIn( __METHOD__
);
764 if( $result->isBrokenTitle() ) {
765 wfProfileOut( __METHOD__
);
766 return "<!-- Broken link in search result -->\n";
769 $t = $result->getTitle();
771 $titleSnippet = $result->getTitleSnippet($terms);
773 if( $titleSnippet == '' )
774 $titleSnippet = null;
776 $link = Linker
::linkKnown(
781 // format redirect if any
782 $redirectTitle = $result->getRedirectTitle();
783 $redirectText = $result->getRedirectSnippet($terms);
785 if( !is_null($redirectTitle) ) {
786 if( $redirectText == '' )
787 $redirectText = null;
789 $redirect = "<span class='searchalttitle'>" .
801 // display project name
802 if(is_null($lastInterwiki) ||
$lastInterwiki != $t->getInterwiki()) {
803 if( array_key_exists($t->getInterwiki(),$customCaptions) ) {
804 // captions from 'search-interwiki-custom'
805 $caption = $customCaptions[$t->getInterwiki()];
807 // default is to show the hostname of the other wiki which might suck
808 // if there are many wikis on one hostname
809 $parsed = wfParseUrl( $t->getFullURL() );
810 $caption = wfMsg('search-interwiki-default', $parsed['host']);
812 // "more results" link (special page stuff could be localized, but we might not know target lang)
813 $searchTitle = Title
::newFromText($t->getInterwiki().":Special:Search");
814 $searchLink = Linker
::linkKnown(
816 wfMsg('search-interwiki-more'),
820 'fulltext' => 'Search'
823 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
824 {$searchLink}</span>{$caption}</div>\n<ul>";
827 $out .= "<li>{$link} {$redirect}</li>\n";
828 wfProfileOut( __METHOD__
);
837 protected function getProfileForm( $profile, $term ) {
840 $opts['redirs'] = $this->searchRedirects
;
841 $opts['profile'] = $this->profile
;
843 if ( $profile === 'advanced' ) {
844 return $this->powerSearchBox( $term, $opts );
847 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
853 * Generates the power search box at [[Special:Search]]
855 * @param $term String: search term
857 * @return String: HTML form
859 protected function powerSearchBox( $term, $opts ) {
860 // Groups namespaces into rows according to subject
862 foreach( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
863 $subject = MWNamespace
::getSubject( $namespace );
864 if( !array_key_exists( $subject, $rows ) ) {
865 $rows[$subject] = "";
867 $name = str_replace( '_', ' ', $name );
869 $name = wfMsg( 'blanknamespace' );
873 'td', array( 'style' => 'white-space: nowrap' )
878 "mw-search-ns{$namespace}",
879 in_array( $namespace, $this->namespaces
)
881 Xml
::closeElement( 'td' );
883 $rows = array_values( $rows );
884 $numRows = count( $rows );
886 // Lays out namespaces in multiple floating two-column tables so they'll
887 // be arranged nicely while still accommodating different screen widths
888 $namespaceTables = '';
889 for( $i = 0; $i < $numRows; $i +
= 4 ) {
890 $namespaceTables .= Xml
::openElement(
892 array( 'cellpadding' => 0, 'cellspacing' => 0, 'border' => 0 )
894 for( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
895 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
897 $namespaceTables .= Xml
::closeElement( 'table' );
900 $showSections = array( 'namespaceTables' => $namespaceTables );
902 // Show redirects check only if backend supports it
903 if( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
904 $showSections['redirects'] =
905 Xml
::checkLabel( wfMsg( 'powersearch-redir' ), 'redirs', 'redirs', $this->searchRedirects
);
908 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
911 unset( $opts['redirs'] );
912 foreach( $opts as $key => $value ) {
913 $hidden .= Html
::hidden( $key, $value );
915 // Return final output
919 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
921 Xml
::element( 'legend', null, wfMsg('powersearch-legend') ) .
922 Xml
::tags( 'h4', null, wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) ) .
925 array( 'id' => 'mw-search-togglebox' ),
926 Xml
::label( wfMsg( 'powersearch-togglelabel' ), 'mw-search-togglelabel' ) .
931 'id' => 'mw-search-toggleall',
932 'value' => wfMsg( 'powersearch-toggleall' )
939 'id' => 'mw-search-togglenone',
940 'value' => wfMsg( 'powersearch-togglenone' )
944 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
945 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
947 Xml
::closeElement( 'fieldset' );
953 protected function getSearchProfiles() {
954 // Builds list of Search Types (profiles)
955 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
959 'message' => 'searchprofile-articles',
960 'tooltip' => 'searchprofile-articles-tooltip',
961 'namespaces' => SearchEngine
::defaultNamespaces(),
962 'namespace-messages' => SearchEngine
::namespacesAsText(
963 SearchEngine
::defaultNamespaces()
967 'message' => 'searchprofile-images',
968 'tooltip' => 'searchprofile-images-tooltip',
969 'namespaces' => array( NS_FILE
),
972 'message' => 'searchprofile-project',
973 'tooltip' => 'searchprofile-project-tooltip',
974 'namespaces' => SearchEngine
::helpNamespaces(),
975 'namespace-messages' => SearchEngine
::namespacesAsText(
976 SearchEngine
::helpNamespaces()
980 'message' => 'searchprofile-everything',
981 'tooltip' => 'searchprofile-everything-tooltip',
982 'namespaces' => $nsAllSet,
985 'message' => 'searchprofile-advanced',
986 'tooltip' => 'searchprofile-advanced-tooltip',
987 'namespaces' => self
::NAMESPACES_CURRENT
,
991 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
993 foreach( $profiles as &$data ) {
994 if ( !is_array( $data['namespaces'] ) ) continue;
995 sort( $data['namespaces'] );
1003 * @param $resultsShown
1007 protected function formHeader( $term, $resultsShown, $totalNum ) {
1008 $out = Xml
::openElement('div', array( 'class' => 'mw-search-formheader' ) );
1011 if( $this->startsWithImage( $term ) ) {
1013 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1016 $profiles = $this->getSearchProfiles();
1017 $lang = $this->getLanguage();
1019 // Outputs XML for Search Types
1020 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1021 $out .= Xml
::openElement( 'ul' );
1022 foreach ( $profiles as $id => $profile ) {
1023 if ( !isset( $profile['parameters'] ) ) {
1024 $profile['parameters'] = array();
1026 $profile['parameters']['profile'] = $id;
1028 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1029 $lang->commaList( $profile['namespace-messages'] ) : null;
1033 'class' => $this->profile
=== $id ?
'current' : 'normal'
1035 $this->makeSearchLink(
1038 wfMsg( $profile['message'] ),
1039 wfMsg( $profile['tooltip'], $tooltipParam ),
1040 $profile['parameters']
1044 $out .= Xml
::closeElement( 'ul' );
1045 $out .= Xml
::closeElement('div') ;
1048 if ( $resultsShown > 0 ) {
1049 if ( $totalNum > 0 ){
1050 $top = wfMsgExt( 'showingresultsheader', array( 'parseinline' ),
1051 $lang->formatNum( $this->offset +
1 ),
1052 $lang->formatNum( $this->offset +
$resultsShown ),
1053 $lang->formatNum( $totalNum ),
1054 wfEscapeWikiText( $term ),
1055 $lang->formatNum( $resultsShown )
1057 } elseif ( $resultsShown >= $this->limit
) {
1058 $top = wfMsgExt( 'showingresults', array( 'parseinline' ),
1059 $lang->formatNum( $this->limit
),
1060 $lang->formatNum( $this->offset +
1 )
1063 $top = wfMsgExt( 'showingresultsnum', array( 'parseinline' ),
1064 $lang->formatNum( $this->limit
),
1065 $lang->formatNum( $this->offset +
1 ),
1066 $lang->formatNum( $resultsShown )
1069 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1070 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1074 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1075 $out .= Xml
::closeElement('div');
1081 * @param $term string
1084 protected function shortDialog( $term ) {
1085 $out = Html
::hidden( 'title', $this->getTitle()->getPrefixedText() );
1086 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1088 $out .= Html
::input( 'search', $term, 'search', array(
1089 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1093 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1094 $out .= Xml
::submitButton( wfMsg( 'searchbutton' ) ) . "\n";
1095 return $out . $this->didYouMeanHtml
;
1099 * Make a search link with some target namespaces
1101 * @param $term String
1102 * @param $namespaces Array ignored
1103 * @param $label String: link's text
1104 * @param $tooltip String: link's tooltip
1105 * @param $params Array: query string parameters
1106 * @return String: HTML fragment
1108 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1110 foreach( $namespaces as $n ) {
1111 $opt['ns' . $n] = 1;
1113 $opt['redirs'] = $this->searchRedirects
;
1115 $stParams = array_merge(
1118 'fulltext' => wfMsg( 'search' )
1123 return Xml
::element(
1126 'href' => $this->getTitle()->getLocalURL( $stParams ),
1127 'title' => $tooltip),
1133 * Check if query starts with image: prefix
1135 * @param $term String: the string to check
1138 protected function startsWithImage( $term ) {
1141 $p = explode( ':', $term );
1142 if( count( $p ) > 1 ) {
1143 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE
;
1149 * Check if query starts with all: prefix
1151 * @param $term String: the string to check
1154 protected function startsWithAll( $term ) {
1156 $allkeyword = wfMsgForContent('searchall');
1158 $p = explode( ':', $term );
1159 if( count( $p ) > 1 ) {
1160 return $p[0] == $allkeyword;
1168 * @return SearchEngine
1170 public function getSearchEngine() {
1171 if ( $this->searchEngine
=== null ) {
1172 $this->searchEngine
= SearchEngine
::create();
1174 return $this->searchEngine
;
1178 * Users of hook SpecialSearchSetupEngine can use this to
1179 * add more params to links to not lose selection when
1180 * user navigates search results.
1186 public function setExtraParam( $key, $value ) {
1187 $this->extraParams
[$key] = $value;