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, $this->msg( 'search-external' )->text() ) .
237 Xml
::element( 'p', array( 'class' => 'mw-searchdisabled' ), $this->msg( 'searchdisabled' )->text() ) .
238 $this->msg( 'googlesearch' )->rawParams(
239 htmlspecialchars( $term ),
241 $this->msg( 'searchbutton' )->escaped()
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">' . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</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', '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', $this->getUser() ) ) {
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' )->rawParams(
453 $this->msg( 'searchresults-title' )->rawParams( $term )->text()
456 // add javascript specific to special:search
457 $out->addModules( 'mediawiki.special.search' );
461 * Extract "power search" namespace settings from the request object,
462 * returning a list of index numbers to search.
464 * @param $request WebRequest
467 protected function powerSearch( &$request ) {
469 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
470 if( $request->getCheck( 'ns' . $ns ) ) {
479 * Reconstruct the 'power search' options for links
483 protected function powerSearchOptions() {
485 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
486 if( $this->profile
!== 'advanced' ) {
487 $opt['profile'] = $this->profile
;
489 foreach( $this->namespaces
as $n ) {
493 return $opt +
$this->extraParams
;
497 * Show whole set of results
499 * @param $matches SearchResultSet
503 protected function showMatches( &$matches ) {
505 wfProfileIn( __METHOD__
);
507 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
510 $infoLine = $matches->getInfo();
511 if( !is_null($infoLine) ) {
512 $out .= "\n<!-- {$infoLine} -->\n";
514 $out .= "<ul class='mw-search-results'>\n";
515 $result = $matches->next();
517 $out .= $this->showHit( $result, $terms );
518 $result = $matches->next();
522 // convert the whole thing to desired language variant
523 $out = $wgContLang->convert( $out );
524 wfProfileOut( __METHOD__
);
529 * Format a single hit result
531 * @param $result SearchResult
532 * @param $terms Array: terms to highlight
536 protected function showHit( $result, $terms ) {
537 wfProfileIn( __METHOD__
);
539 if( $result->isBrokenTitle() ) {
540 wfProfileOut( __METHOD__
);
541 return "<!-- Broken link in search result -->\n";
544 $t = $result->getTitle();
546 $titleSnippet = $result->getTitleSnippet($terms);
548 if( $titleSnippet == '' )
549 $titleSnippet = null;
553 wfRunHooks( 'ShowSearchHitTitle',
554 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
556 $link = Linker
::linkKnown(
561 //If page content is not readable, just return the title.
562 //This is not quite safe, but better than showing excerpts from non-readable pages
563 //Note that hiding the entry entirely would screw up paging.
564 if( !$t->userCan( 'read', $this->getUser() ) ) {
565 wfProfileOut( __METHOD__
);
566 return "<li>{$link}</li>\n";
569 // If the page doesn't *exist*... our search index is out of date.
570 // The least confusing at this point is to drop the result.
571 // You may get less results, but... oh well. :P
572 if( $result->isMissingRevision() ) {
573 wfProfileOut( __METHOD__
);
574 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
577 // format redirects / relevant sections
578 $redirectTitle = $result->getRedirectTitle();
579 $redirectText = $result->getRedirectSnippet($terms);
580 $sectionTitle = $result->getSectionTitle();
581 $sectionText = $result->getSectionSnippet($terms);
584 if( !is_null($redirectTitle) ) {
585 if( $redirectText == '' )
586 $redirectText = null;
588 $redirect = "<span class='searchalttitle'>" .
589 $this->msg( 'search-redirect' )->rawParams(
590 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
596 if( !is_null($sectionTitle) ) {
597 if( $sectionText == '' )
600 $section = "<span class='searchalttitle'>" .
601 $this->msg( 'search-section' )->rawParams(
602 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
606 // format text extract
607 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
609 $lang = $this->getLanguage();
612 if( is_null( $result->getScore() ) ) {
613 // Search engine doesn't report scoring info
616 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
617 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
621 // format description
622 $byteSize = $result->getByteSize();
623 $wordCount = $result->getWordCount();
624 $timestamp = $result->getTimestamp();
625 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
626 ->numParams( $wordCount )->escaped();
628 if( $t->getNamespace() == NS_CATEGORY
) {
629 $cat = Category
::newFromTitle( $t );
630 $size = $this->msg( 'search-result-category-size' )
631 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
635 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
637 // link to related articles if supported
639 if( $result->hasRelated() ) {
640 $st = SpecialPage
::getTitleFor( 'Search' );
641 $stParams = array_merge(
642 $this->powerSearchOptions(),
644 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
645 ':' . $t->getPrefixedText(),
646 'fulltext' => $this->msg( 'search' )->text()
650 $related = ' -- ' . Linker
::linkKnown(
652 $this->msg( 'search-relatedarticle' )->text(),
658 // Include a thumbnail for media files...
659 if( $t->getNamespace() == NS_FILE
) {
660 $img = wfFindFile( $t );
662 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
664 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
665 wfProfileOut( __METHOD__
);
666 // Float doesn't seem to interact well with the bullets.
667 // Table messes up vertical alignment of the bullets.
668 // Bullets are therefore disabled (didn't look great anyway).
670 '<table class="searchResultImage">' .
672 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
673 $thumb->toHtml( array( 'desc-link' => true ) ) .
675 '<td style="vertical-align: top;">' .
678 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
687 wfProfileOut( __METHOD__
);
688 return "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
689 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
695 * Show results from other wikis
697 * @param $matches SearchResultSet
698 * @param $query String
702 protected function showInterwiki( &$matches, $query ) {
704 wfProfileIn( __METHOD__
);
705 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
707 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
708 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
709 $out .= "<ul class='mw-search-iwresults'>\n";
711 // work out custom project captions
712 $customCaptions = array();
713 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() ); // format per line <iwprefix>:<caption>
714 foreach($customLines as $line) {
715 $parts = explode(":",$line,2);
716 if(count($parts) == 2) // validate line
717 $customCaptions[$parts[0]] = $parts[1];
721 $result = $matches->next();
723 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
724 $prev = $result->getInterwikiPrefix();
725 $result = $matches->next();
727 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
728 $out .= "</ul></div>\n";
730 // convert the whole thing to desired language variant
731 $out = $wgContLang->convert( $out );
732 wfProfileOut( __METHOD__
);
737 * Show single interwiki link
739 * @param $result SearchResult
740 * @param $lastInterwiki String
741 * @param $terms Array
742 * @param $query String
743 * @param $customCaptions Array: iw prefix -> caption
747 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
748 wfProfileIn( __METHOD__
);
750 if( $result->isBrokenTitle() ) {
751 wfProfileOut( __METHOD__
);
752 return "<!-- Broken link in search result -->\n";
755 $t = $result->getTitle();
757 $titleSnippet = $result->getTitleSnippet($terms);
759 if( $titleSnippet == '' )
760 $titleSnippet = null;
762 $link = Linker
::linkKnown(
767 // format redirect if any
768 $redirectTitle = $result->getRedirectTitle();
769 $redirectText = $result->getRedirectSnippet($terms);
771 if( !is_null($redirectTitle) ) {
772 if( $redirectText == '' )
773 $redirectText = null;
775 $redirect = "<span class='searchalttitle'>" .
776 $this->msg( 'search-redirect' )->rawParams(
777 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
782 // display project name
783 if(is_null($lastInterwiki) ||
$lastInterwiki != $t->getInterwiki()) {
784 if( array_key_exists($t->getInterwiki(),$customCaptions) ) {
785 // captions from 'search-interwiki-custom'
786 $caption = $customCaptions[$t->getInterwiki()];
788 // default is to show the hostname of the other wiki which might suck
789 // if there are many wikis on one hostname
790 $parsed = wfParseUrl( $t->getFullURL() );
791 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
793 // "more results" link (special page stuff could be localized, but we might not know target lang)
794 $searchTitle = Title
::newFromText($t->getInterwiki().":Special:Search");
795 $searchLink = Linker
::linkKnown(
797 $this->msg( 'search-interwiki-more' )->text(),
801 'fulltext' => 'Search'
804 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
805 {$searchLink}</span>{$caption}</div>\n<ul>";
808 $out .= "<li>{$link} {$redirect}</li>\n";
809 wfProfileOut( __METHOD__
);
818 protected function getProfileForm( $profile, $term ) {
821 $opts['redirs'] = $this->searchRedirects
;
822 $opts['profile'] = $this->profile
;
824 if ( $profile === 'advanced' ) {
825 return $this->powerSearchBox( $term, $opts );
828 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
834 * Generates the power search box at [[Special:Search]]
836 * @param $term String: search term
838 * @return String: HTML form
840 protected function powerSearchBox( $term, $opts ) {
841 // Groups namespaces into rows according to subject
843 foreach( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
844 $subject = MWNamespace
::getSubject( $namespace );
845 if( !array_key_exists( $subject, $rows ) ) {
846 $rows[$subject] = "";
848 $name = str_replace( '_', ' ', $name );
850 $name = $this->msg( 'blanknamespace' )->text();
854 'td', array( 'style' => 'white-space: nowrap' )
859 "mw-search-ns{$namespace}",
860 in_array( $namespace, $this->namespaces
)
862 Xml
::closeElement( 'td' );
864 $rows = array_values( $rows );
865 $numRows = count( $rows );
867 // Lays out namespaces in multiple floating two-column tables so they'll
868 // be arranged nicely while still accommodating different screen widths
869 $namespaceTables = '';
870 for( $i = 0; $i < $numRows; $i +
= 4 ) {
871 $namespaceTables .= Xml
::openElement(
873 array( 'cellpadding' => 0, 'cellspacing' => 0 )
875 for( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
876 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
878 $namespaceTables .= Xml
::closeElement( 'table' );
881 $showSections = array( 'namespaceTables' => $namespaceTables );
883 // Show redirects check only if backend supports it
884 if( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
885 $showSections['redirects'] =
886 Xml
::checkLabel( $this->msg( 'powersearch-redir' )->text(), 'redirs', 'redirs', $this->searchRedirects
);
889 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
892 unset( $opts['redirs'] );
893 foreach( $opts as $key => $value ) {
894 $hidden .= Html
::hidden( $key, $value );
896 // Return final output
900 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
902 Xml
::element( 'legend', null, $this->msg('powersearch-legend' )->text() ) .
903 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
904 Html
::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
905 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
906 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
908 Xml
::closeElement( 'fieldset' );
914 protected function getSearchProfiles() {
915 // Builds list of Search Types (profiles)
916 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
920 'message' => 'searchprofile-articles',
921 'tooltip' => 'searchprofile-articles-tooltip',
922 'namespaces' => SearchEngine
::defaultNamespaces(),
923 'namespace-messages' => SearchEngine
::namespacesAsText(
924 SearchEngine
::defaultNamespaces()
928 'message' => 'searchprofile-images',
929 'tooltip' => 'searchprofile-images-tooltip',
930 'namespaces' => array( NS_FILE
),
933 'message' => 'searchprofile-project',
934 'tooltip' => 'searchprofile-project-tooltip',
935 'namespaces' => SearchEngine
::helpNamespaces(),
936 'namespace-messages' => SearchEngine
::namespacesAsText(
937 SearchEngine
::helpNamespaces()
941 'message' => 'searchprofile-everything',
942 'tooltip' => 'searchprofile-everything-tooltip',
943 'namespaces' => $nsAllSet,
946 'message' => 'searchprofile-advanced',
947 'tooltip' => 'searchprofile-advanced-tooltip',
948 'namespaces' => self
::NAMESPACES_CURRENT
,
952 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
954 foreach( $profiles as &$data ) {
955 if ( !is_array( $data['namespaces'] ) ) continue;
956 sort( $data['namespaces'] );
964 * @param $resultsShown
968 protected function formHeader( $term, $resultsShown, $totalNum ) {
969 $out = Xml
::openElement('div', array( 'class' => 'mw-search-formheader' ) );
972 if( $this->startsWithImage( $term ) ) {
974 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
977 $profiles = $this->getSearchProfiles();
978 $lang = $this->getLanguage();
980 // Outputs XML for Search Types
981 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
982 $out .= Xml
::openElement( 'ul' );
983 foreach ( $profiles as $id => $profile ) {
984 if ( !isset( $profile['parameters'] ) ) {
985 $profile['parameters'] = array();
987 $profile['parameters']['profile'] = $id;
989 $tooltipParam = isset( $profile['namespace-messages'] ) ?
990 $lang->commaList( $profile['namespace-messages'] ) : null;
994 'class' => $this->profile
=== $id ?
'current' : 'normal'
996 $this->makeSearchLink(
999 $this->msg( $profile['message'] )->text(),
1000 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1001 $profile['parameters']
1005 $out .= Xml
::closeElement( 'ul' );
1006 $out .= Xml
::closeElement('div') ;
1009 if ( $resultsShown > 0 ) {
1010 if ( $totalNum > 0 ){
1011 $top = $this->msg( 'showingresultsheader' )
1012 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1013 ->params( wfEscapeWikiText( $term ) )
1014 ->numParams( $resultsShown )
1016 } elseif ( $resultsShown >= $this->limit
) {
1017 $top = $this->msg( 'showingresults' )
1018 ->numParams( $this->limit
, $this->offset +
1 )
1021 $top = $this->msg( 'showingresultsnum' )
1022 ->numParams( $this->limit
, $this->offset +
1, $resultsShown )
1025 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1026 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1030 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1031 $out .= Xml
::closeElement('div');
1037 * @param $term string
1040 protected function shortDialog( $term ) {
1041 $out = Html
::hidden( 'title', $this->getTitle()->getPrefixedText() );
1042 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1044 $out .= Html
::input( 'search', $term, 'search', array(
1045 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1049 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1050 $out .= Xml
::submitButton( $this->msg( 'searchbutton' )->text() ) . "\n";
1051 return $out . $this->didYouMeanHtml
;
1055 * Make a search link with some target namespaces
1057 * @param $term String
1058 * @param $namespaces Array ignored
1059 * @param $label String: link's text
1060 * @param $tooltip String: link's tooltip
1061 * @param $params Array: query string parameters
1062 * @return String: HTML fragment
1064 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1066 foreach( $namespaces as $n ) {
1067 $opt['ns' . $n] = 1;
1069 $opt['redirs'] = $this->searchRedirects
;
1071 $stParams = array_merge(
1074 'fulltext' => $this->msg( 'search' )->text()
1079 return Xml
::element(
1082 'href' => $this->getTitle()->getLocalURL( $stParams ),
1083 'title' => $tooltip),
1089 * Check if query starts with image: prefix
1091 * @param $term String: the string to check
1094 protected function startsWithImage( $term ) {
1097 $p = explode( ':', $term );
1098 if( count( $p ) > 1 ) {
1099 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE
;
1105 * Check if query starts with all: prefix
1107 * @param $term String: the string to check
1110 protected function startsWithAll( $term ) {
1112 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1114 $p = explode( ':', $term );
1115 if( count( $p ) > 1 ) {
1116 return $p[0] == $allkeyword;
1124 * @return SearchEngine
1126 public function getSearchEngine() {
1127 if ( $this->searchEngine
=== null ) {
1128 $this->searchEngine
= SearchEngine
::create();
1130 return $this->searchEngine
;
1134 * Users of hook SpecialSearchSetupEngine can use this to
1135 * add more params to links to not lose selection when
1136 * user navigates search results.
1142 public function setExtraParam( $key, $value ) {
1143 $this->extraParams
[$key] = $value;