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
{
31 /// Current search profile
35 protected $searchEngine;
38 protected $extraParams = array();
40 /// No idea, apparently used by some other classes
43 const NAMESPACES_CURRENT
= 'sense';
45 public function __construct() {
46 parent
::__construct( 'Search' );
52 * @param $par String or null
54 public function execute( $par ) {
56 $this->outputHeader();
57 $out = $this->getOutput();
58 $out->allowClickjacking();
59 $out->addModuleStyles( 'mediawiki.special' );
61 // Strip underscores from title parameter; most of the time we'll want
62 // text form here. But don't strip underscores from actual text params!
63 $titleParam = str_replace( '_', ' ', $par );
65 $request = $this->getRequest();
67 // Fetch the search term
68 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
72 if ( $request->getVal( 'fulltext' )
73 ||
!is_null( $request->getVal( 'offset' ) )
74 ||
!is_null( $request->getVal( 'searchx' ) ) )
76 $this->showResults( $search );
78 $this->goResult( $search );
83 * Set up basic search parameters from the request and user settings.
85 public function load() {
86 $request = $this->getRequest();
87 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, 'searchlimit' );
88 $this->mPrefix
= $request->getVal( 'prefix', '' );
90 $user = $this->getUser();
91 # Extract manually requested namespaces
92 $nslist = $this->powerSearch( $request );
93 $this->profile
= $profile = $request->getVal( 'profile', null );
94 $profiles = $this->getSearchProfiles();
95 if ( $profile === null) {
96 // BC with old request format
97 $this->profile
= 'advanced';
98 if ( count( $nslist ) ) {
99 foreach( $profiles as $key => $data ) {
100 if ( $nslist === $data['namespaces'] && $key !== 'advanced') {
101 $this->profile
= $key;
104 $this->namespaces
= $nslist;
106 $this->namespaces
= SearchEngine
::userNamespaces( $user );
108 } elseif ( $profile === 'advanced' ) {
109 $this->namespaces
= $nslist;
111 if ( isset( $profiles[$profile]['namespaces'] ) ) {
112 $this->namespaces
= $profiles[$profile]['namespaces'];
114 // Unknown profile requested
115 $this->profile
= 'default';
116 $this->namespaces
= $profiles['default']['namespaces'];
120 // Redirects defaults to true, but we don't know whether it was ticked of or just missing
121 $default = $request->getBool( 'profile' ) ?
0 : 1;
122 $this->searchRedirects
= $request->getBool( 'redirs', $default ) ?
1 : 0;
123 $this->didYouMeanHtml
= ''; # html of did you mean... link
124 $this->fulltext
= $request->getVal('fulltext');
128 * If an exact title match can be found, jump straight ahead to it.
130 * @param $term String
132 public function goResult( $term ) {
133 $this->setupPage( $term );
134 # Try to go to page as entered.
135 $t = Title
::newFromText( $term );
136 # If the string cannot be used to create a title
137 if( is_null( $t ) ) {
138 return $this->showResults( $term );
140 # If there's an exact or very near match, jump right there.
141 $t = SearchEngine
::getNearMatch( $term );
143 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
144 # Hook requested termination
148 if( !is_null( $t ) ) {
149 $this->getOutput()->redirect( $t->getFullURL() );
152 # No match, generate an edit URL
153 $t = Title
::newFromText( $term );
154 if( !is_null( $t ) ) {
156 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
157 wfDebugLog( 'nogomatch', $t->getText(), false );
159 # If the feature is enabled, go straight to the edit page
161 $this->getOutput()->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
165 return $this->showResults( $term );
169 * @param $term String
171 public function showResults( $term ) {
172 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
173 wfProfileIn( __METHOD__
);
175 $search = $this->getSearchEngine();
176 $search->setLimitOffset( $this->limit
, $this->offset
);
177 $search->setNamespaces( $this->namespaces
);
178 $search->showRedirects
= $this->searchRedirects
; // BC
179 $search->setFeatureData( 'list-redirects', $this->searchRedirects
);
180 $search->prefix
= $this->mPrefix
;
181 $term = $search->transformSearchTerm($term);
183 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
185 $this->setupPage( $term );
187 $out = $this->getOutput();
189 if ( $wgDisableTextSearch ) {
190 if ( $wgSearchForwardUrl ) {
191 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
192 $out->redirect( $url );
195 Xml
::openElement( 'fieldset' ) .
196 Xml
::element( 'legend', null, wfMsg( 'search-external' ) ) .
197 Xml
::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
198 wfMsg( 'googlesearch',
199 htmlspecialchars( $term ),
200 htmlspecialchars( 'UTF-8' ),
201 htmlspecialchars( wfMsg( 'searchbutton' ) )
203 Xml
::closeElement( 'fieldset' )
206 wfProfileOut( __METHOD__
);
210 $t = Title
::newFromText( $term );
212 // fetch search results
213 $rewritten = $search->replacePrefixes($term);
215 $titleMatches = $search->searchTitle( $rewritten );
216 if( !($titleMatches instanceof SearchResultTooMany
))
217 $textMatches = $search->searchText( $rewritten );
219 // did you mean... suggestions
220 if( $textMatches && $textMatches->hasSuggestion() ) {
221 $st = SpecialPage
::getTitleFor( 'Search' );
223 # mirror Go/Search behaviour of original request ..
224 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
226 if($this->fulltext
!= null)
227 $didYouMeanParams['fulltext'] = $this->fulltext
;
229 $stParams = array_merge(
231 $this->powerSearchOptions()
234 $suggestionSnippet = $textMatches->getSuggestionSnippet();
236 if( $suggestionSnippet == '' )
237 $suggestionSnippet = null;
239 $suggestLink = Linker
::linkKnown(
246 $this->didYouMeanHtml
= '<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>';
248 // start rendering the page
253 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
255 'action' => $wgScript
260 Xml
::openElement( 'table', array( 'id'=>'mw-search-top-table', 'border'=>0, 'cellpadding'=>0, 'cellspacing'=>0 ) ) .
261 Xml
::openElement( 'tr' ) .
262 Xml
::openElement( 'td' ) . "\n" .
263 $this->shortDialog( $term ) .
264 Xml
::closeElement('td') .
265 Xml
::closeElement('tr') .
266 Xml
::closeElement('table')
269 // Sometimes the search engine knows there are too many hits
270 if( $titleMatches instanceof SearchResultTooMany
) {
271 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
272 wfProfileOut( __METHOD__
);
276 $filePrefix = $wgContLang->getFormattedNsText(NS_FILE
).':';
277 if( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
278 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
279 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
280 $out->addHTML( '</form>' );
281 // Empty query -- straight view of search form
282 wfProfileOut( __METHOD__
);
286 // Get number of results
287 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
288 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
289 // Total initial query matches (possible false positives)
290 $num = $titleMatchesNum +
$textMatchesNum;
292 // Get total actual results (after second filtering, if any)
293 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
294 $titleMatches->getTotalHits() : $titleMatchesNum;
295 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
296 $textMatches->getTotalHits() : $textMatchesNum;
298 // get total number of results if backend can calculate it
300 if($titleMatches && !is_null( $titleMatches->getTotalHits() ) )
301 $totalRes +
= $titleMatches->getTotalHits();
302 if($textMatches && !is_null( $textMatches->getTotalHits() ))
303 $totalRes +
= $textMatches->getTotalHits();
305 // show number of results and current offset
306 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
307 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
310 $out->addHtml( Xml
::closeElement( 'form' ) );
311 $out->addHtml( "<div class='searchresults'>" );
314 if( $num ||
$this->offset
) {
315 // Show the create link ahead
316 $this->showCreateLink( $t );
317 $prevnext = wfViewPrevNext( $this->offset
, $this->limit
,
318 SpecialPage
::getTitleFor( 'Search' ),
319 wfArrayToCGI( $this->powerSearchOptions(), array( 'search' => $term ) ),
320 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
322 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
323 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
325 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
328 $out->parserOptions()->setEditSection( false );
329 if( $titleMatches ) {
330 if( $numTitleMatches > 0 ) {
331 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
332 $out->addHTML( $this->showMatches( $titleMatches ) );
334 $titleMatches->free();
337 // output appropriate heading
338 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
339 // if no title matches the heading is redundant
340 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
341 } elseif( $totalRes == 0 ) {
342 # Don't show the 'no text matches' if we received title matches
343 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
345 // show interwiki results if any
346 if( $textMatches->hasInterwikiResults() ) {
347 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
350 if( $numTextMatches > 0 ) {
351 $out->addHTML( $this->showMatches( $textMatches ) );
354 $textMatches->free();
357 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
358 $this->showCreateLink( $t );
360 $out->addHtml( "</div>" );
362 if( $num ||
$this->offset
) {
363 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
365 wfProfileOut( __METHOD__
);
368 protected function showCreateLink( $t ) {
369 // show direct page/create link if applicable
370 // Check DBkey !== '' in case of fragment link only.
372 if( !is_null($t) && $t->getDBkey() !== '' ) {
373 if( $t->isKnown() ) {
374 $messageName = 'searchmenu-exists';
375 } elseif( $t->userCan( 'create' ) ) {
376 $messageName = 'searchmenu-new';
378 $messageName = 'searchmenu-new-nocreate';
382 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ) ) );
384 // preserve the paragraph for margins etc...
385 $this->getOutput()->addHtml( '<p></p>' );
392 protected function setupPage( $term ) {
393 # Should advanced UI be used?
394 $this->searchAdvanced
= ($this->profile
=== 'advanced');
395 $out = $this->getOutput();
396 if( strval( $term ) !== '' ) {
397 $out->setPageTitle( wfMsg( 'searchresults') );
398 $out->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term ) ) );
400 // add javascript specific to special:search
401 $out->addModules( 'mediawiki.special.search' );
405 * Extract "power search" namespace settings from the request object,
406 * returning a list of index numbers to search.
408 * @param $request WebRequest
411 protected function powerSearch( &$request ) {
413 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
414 if( $request->getCheck( 'ns' . $ns ) ) {
423 * Reconstruct the 'power search' options for links
427 protected function powerSearchOptions() {
429 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
430 if( $this->profile
!== 'advanced' ) {
431 $opt['profile'] = $this->profile
;
433 foreach( $this->namespaces
as $n ) {
437 return $opt +
$this->extraParams
;
441 * Show whole set of results
443 * @param $matches SearchResultSet
445 protected function showMatches( &$matches ) {
447 wfProfileIn( __METHOD__
);
449 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
452 $infoLine = $matches->getInfo();
453 if( !is_null($infoLine) ) {
454 $out .= "\n<!-- {$infoLine} -->\n";
456 $out .= "<ul class='mw-search-results'>\n";
457 while( $result = $matches->next() ) {
458 $out .= $this->showHit( $result, $terms );
462 // convert the whole thing to desired language variant
463 $out = $wgContLang->convert( $out );
464 wfProfileOut( __METHOD__
);
469 * Format a single hit result
471 * @param $result SearchResult
472 * @param $terms Array: terms to highlight
474 protected function showHit( $result, $terms ) {
475 wfProfileIn( __METHOD__
);
477 if( $result->isBrokenTitle() ) {
478 wfProfileOut( __METHOD__
);
479 return "<!-- Broken link in search result -->\n";
482 $t = $result->getTitle();
484 $titleSnippet = $result->getTitleSnippet($terms);
486 if( $titleSnippet == '' )
487 $titleSnippet = null;
491 wfRunHooks( 'ShowSearchHitTitle',
492 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
494 $link = Linker
::linkKnown(
499 //If page content is not readable, just return the title.
500 //This is not quite safe, but better than showing excerpts from non-readable pages
501 //Note that hiding the entry entirely would screw up paging.
502 if( !$t->userCanRead() ) {
503 wfProfileOut( __METHOD__
);
504 return "<li>{$link}</li>\n";
507 // If the page doesn't *exist*... our search index is out of date.
508 // The least confusing at this point is to drop the result.
509 // You may get less results, but... oh well. :P
510 if( $result->isMissingRevision() ) {
511 wfProfileOut( __METHOD__
);
512 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
515 // format redirects / relevant sections
516 $redirectTitle = $result->getRedirectTitle();
517 $redirectText = $result->getRedirectSnippet($terms);
518 $sectionTitle = $result->getSectionTitle();
519 $sectionText = $result->getSectionSnippet($terms);
522 if( !is_null($redirectTitle) ) {
523 if( $redirectText == '' )
524 $redirectText = null;
526 $redirect = "<span class='searchalttitle'>" .
539 if( !is_null($sectionTitle) ) {
540 if( $sectionText == '' )
543 $section = "<span class='searchalttitle'>" .
545 'search-section', Linker
::linkKnown(
553 // format text extract
554 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
556 $lang = $this->getLang();
559 if( is_null( $result->getScore() ) ) {
560 // Search engine doesn't report scoring info
563 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
564 $score = wfMsg( 'search-result-score', $lang->formatNum( $percent ) )
568 // format description
569 $byteSize = $result->getByteSize();
570 $wordCount = $result->getWordCount();
571 $timestamp = $result->getTimestamp();
573 'search-result-size',
574 array( 'parsemag', 'escape' ),
575 $lang->formatSize( $byteSize ),
576 $lang->formatNum( $wordCount )
579 if( $t->getNamespace() == NS_CATEGORY
) {
580 $cat = Category
::newFromTitle( $t );
582 'search-result-category-size',
583 array( 'parsemag', 'escape' ),
584 $lang->formatNum( $cat->getPageCount() ),
585 $lang->formatNum( $cat->getSubcatCount() ),
586 $lang->formatNum( $cat->getFileCount() )
590 $date = $lang->timeanddate( $timestamp );
592 // link to related articles if supported
594 if( $result->hasRelated() ) {
595 $st = SpecialPage
::getTitleFor( 'Search' );
596 $stParams = array_merge(
597 $this->powerSearchOptions(),
599 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
600 'fulltext' => wfMsg( 'search' )
604 $related = ' -- ' . Linker
::linkKnown(
606 wfMsg('search-relatedarticle'),
612 // Include a thumbnail for media files...
613 if( $t->getNamespace() == NS_FILE
) {
614 $img = wfFindFile( $t );
616 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
618 $desc = wfMsg( 'parentheses', $img->getShortDesc() );
619 wfProfileOut( __METHOD__
);
620 // Float doesn't seem to interact well with the bullets.
621 // Table messes up vertical alignment of the bullets.
622 // Bullets are therefore disabled (didn't look great anyway).
624 '<table class="searchResultImage">' .
626 '<td width="120" align="center" valign="top">' .
627 $thumb->toHtml( array( 'desc-link' => true ) ) .
629 '<td valign="top">' .
632 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
641 wfProfileOut( __METHOD__
);
642 return "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
643 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
649 * Show results from other wikis
651 * @param $matches SearchResultSet
652 * @param $query String
654 protected function showInterwiki( &$matches, $query ) {
656 wfProfileIn( __METHOD__
);
657 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
659 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
660 wfMsg('search-interwiki-caption')."</div>\n";
661 $out .= "<ul class='mw-search-iwresults'>\n";
663 // work out custom project captions
664 $customCaptions = array();
665 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
666 foreach($customLines as $line) {
667 $parts = explode(":",$line,2);
668 if(count($parts) == 2) // validate line
669 $customCaptions[$parts[0]] = $parts[1];
673 while( $result = $matches->next() ) {
674 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
675 $prev = $result->getInterwikiPrefix();
677 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
678 $out .= "</ul></div>\n";
680 // convert the whole thing to desired language variant
681 $out = $wgContLang->convert( $out );
682 wfProfileOut( __METHOD__
);
687 * Show single interwiki link
689 * @param $result SearchResult
690 * @param $lastInterwiki String
691 * @param $terms Array
692 * @param $query String
693 * @param $customCaptions Array: iw prefix -> caption
695 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
696 wfProfileIn( __METHOD__
);
698 if( $result->isBrokenTitle() ) {
699 wfProfileOut( __METHOD__
);
700 return "<!-- Broken link in search result -->\n";
703 $t = $result->getTitle();
705 $titleSnippet = $result->getTitleSnippet($terms);
707 if( $titleSnippet == '' )
708 $titleSnippet = null;
710 $link = Linker
::linkKnown(
715 // format redirect if any
716 $redirectTitle = $result->getRedirectTitle();
717 $redirectText = $result->getRedirectSnippet($terms);
719 if( !is_null($redirectTitle) ) {
720 if( $redirectText == '' )
721 $redirectText = null;
723 $redirect = "<span class='searchalttitle'>" .
735 // display project name
736 if(is_null($lastInterwiki) ||
$lastInterwiki != $t->getInterwiki()) {
737 if( key_exists($t->getInterwiki(),$customCaptions) )
738 // captions from 'search-interwiki-custom'
739 $caption = $customCaptions[$t->getInterwiki()];
741 // default is to show the hostname of the other wiki which might suck
742 // if there are many wikis on one hostname
743 $parsed = parse_url($t->getFullURL());
744 $caption = wfMsg('search-interwiki-default', $parsed['host']);
746 // "more results" link (special page stuff could be localized, but we might not know target lang)
747 $searchTitle = Title
::newFromText($t->getInterwiki().":Special:Search");
748 $searchLink = Linker
::linkKnown(
750 wfMsg('search-interwiki-more'),
754 'fulltext' => 'Search'
757 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
758 {$searchLink}</span>{$caption}</div>\n<ul>";
761 $out .= "<li>{$link} {$redirect}</li>\n";
762 wfProfileOut( __METHOD__
);
766 protected function getProfileForm( $profile, $term ) {
769 $opts['redirs'] = $this->searchRedirects
;
770 $opts['profile'] = $this->profile
;
772 if ( $profile === 'advanced' ) {
773 return $this->powerSearchBox( $term, $opts );
776 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
782 * Generates the power search box at [[Special:Search]]
784 * @param $term String: search term
785 * @return String: HTML form
787 protected function powerSearchBox( $term, $opts ) {
788 // Groups namespaces into rows according to subject
790 foreach( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
791 $subject = MWNamespace
::getSubject( $namespace );
792 if( !array_key_exists( $subject, $rows ) ) {
793 $rows[$subject] = "";
795 $name = str_replace( '_', ' ', $name );
797 $name = wfMsg( 'blanknamespace' );
801 'td', array( 'style' => 'white-space: nowrap' )
806 "mw-search-ns{$namespace}",
807 in_array( $namespace, $this->namespaces
)
809 Xml
::closeElement( 'td' );
811 $rows = array_values( $rows );
812 $numRows = count( $rows );
814 // Lays out namespaces in multiple floating two-column tables so they'll
815 // be arranged nicely while still accommodating different screen widths
816 $namespaceTables = '';
817 for( $i = 0; $i < $numRows; $i +
= 4 ) {
818 $namespaceTables .= Xml
::openElement(
820 array( 'cellpadding' => 0, 'cellspacing' => 0, 'border' => 0 )
822 for( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
823 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
825 $namespaceTables .= Xml
::closeElement( 'table' );
827 // Show redirects check only if backend supports it
829 if( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
831 Xml
::checkLabel( wfMsg( 'powersearch-redir' ), 'redirs', 'redirs', $this->searchRedirects
);
835 unset( $opts['redirs'] );
836 foreach( $opts as $key => $value ) {
837 $hidden .= Html
::hidden( $key, $value );
839 // Return final output
843 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
845 Xml
::element( 'legend', null, wfMsg('powersearch-legend') ) .
846 Xml
::tags( 'h4', null, wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) ) .
849 array( 'id' => 'mw-search-togglebox' ),
850 Xml
::label( wfMsg( 'powersearch-togglelabel' ), 'mw-search-togglelabel' ) .
855 'id' => 'mw-search-toggleall',
856 'value' => wfMsg( 'powersearch-toggleall' )
863 'id' => 'mw-search-togglenone',
864 'value' => wfMsg( 'powersearch-togglenone' )
868 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
870 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
871 $redirects . $hidden .
872 Xml
::closeElement( 'fieldset' );
875 protected function getSearchProfiles() {
876 // Builds list of Search Types (profiles)
877 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
881 'message' => 'searchprofile-articles',
882 'tooltip' => 'searchprofile-articles-tooltip',
883 'namespaces' => SearchEngine
::defaultNamespaces(),
884 'namespace-messages' => SearchEngine
::namespacesAsText(
885 SearchEngine
::defaultNamespaces()
889 'message' => 'searchprofile-images',
890 'tooltip' => 'searchprofile-images-tooltip',
891 'namespaces' => array( NS_FILE
),
894 'message' => 'searchprofile-project',
895 'tooltip' => 'searchprofile-project-tooltip',
896 'namespaces' => SearchEngine
::helpNamespaces(),
897 'namespace-messages' => SearchEngine
::namespacesAsText(
898 SearchEngine
::helpNamespaces()
902 'message' => 'searchprofile-everything',
903 'tooltip' => 'searchprofile-everything-tooltip',
904 'namespaces' => $nsAllSet,
907 'message' => 'searchprofile-advanced',
908 'tooltip' => 'searchprofile-advanced-tooltip',
909 'namespaces' => self
::NAMESPACES_CURRENT
,
913 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
915 foreach( $profiles as &$data ) {
916 if ( !is_array( $data['namespaces'] ) ) continue;
917 sort( $data['namespaces'] );
923 protected function formHeader( $term, $resultsShown, $totalNum ) {
924 $out = Xml
::openElement('div', array( 'class' => 'mw-search-formheader' ) );
927 if( $this->startsWithImage( $term ) ) {
929 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
932 $profiles = $this->getSearchProfiles();
933 $lang = $this->getLang();
935 // Outputs XML for Search Types
936 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
937 $out .= Xml
::openElement( 'ul' );
938 foreach ( $profiles as $id => $profile ) {
939 if ( !isset( $profile['parameters'] ) ) {
940 $profile['parameters'] = array();
942 $profile['parameters']['profile'] = $id;
944 $tooltipParam = isset( $profile['namespace-messages'] ) ?
945 $lang->commaList( $profile['namespace-messages'] ) : null;
949 'class' => $this->profile
=== $id ?
'current' : 'normal'
951 $this->makeSearchLink(
954 wfMsg( $profile['message'] ),
955 wfMsg( $profile['tooltip'], $tooltipParam ),
956 $profile['parameters']
960 $out .= Xml
::closeElement( 'ul' );
961 $out .= Xml
::closeElement('div') ;
964 if ( $resultsShown > 0 ) {
965 if ( $totalNum > 0 ){
966 $top = wfMsgExt( 'showingresultsheader', array( 'parseinline' ),
967 $lang->formatNum( $this->offset +
1 ),
968 $lang->formatNum( $this->offset +
$resultsShown ),
969 $lang->formatNum( $totalNum ),
970 wfEscapeWikiText( $term ),
971 $lang->formatNum( $resultsShown )
973 } elseif ( $resultsShown >= $this->limit
) {
974 $top = wfShowingResults( $this->offset
, $this->limit
);
976 $top = wfMsgExt( 'showingresultsnum', array( 'parseinline' ),
977 $lang->formatNum( $this->limit
),
978 $lang->formatNum( $this->offset +
1 ),
979 $lang->formatNum( $resultsShown )
982 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
983 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
987 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
988 $out .= Xml
::closeElement('div');
993 protected function shortDialog( $term ) {
994 $out = Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
996 $out .= Html
::input( 'search', $term, 'search', array(
997 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1001 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1002 $out .= Xml
::submitButton( wfMsg( 'searchbutton' ) ) . "\n";
1003 return $out . $this->didYouMeanHtml
;
1007 * Make a search link with some target namespaces
1009 * @param $term String
1010 * @param $namespaces Array ignored
1011 * @param $label String: link's text
1012 * @param $tooltip String: link's tooltip
1013 * @param $params Array: query string parameters
1014 * @return String: HTML fragment
1016 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1018 foreach( $namespaces as $n ) {
1019 $opt['ns' . $n] = 1;
1021 $opt['redirs'] = $this->searchRedirects
;
1023 $stParams = array_merge(
1026 'fulltext' => wfMsg( 'search' )
1031 return Xml
::element(
1034 'href' => $this->getTitle()->getLocalURL( $stParams ),
1035 'title' => $tooltip),
1041 * Check if query starts with image: prefix
1043 * @param $term String: the string to check
1046 protected function startsWithImage( $term ) {
1049 $p = explode( ':', $term );
1050 if( count( $p ) > 1 ) {
1051 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE
;
1057 * Check if query starts with all: prefix
1059 * @param $term String: the string to check
1062 protected function startsWithAll( $term ) {
1064 $allkeyword = wfMsgForContent('searchall');
1066 $p = explode( ':', $term );
1067 if( count( $p ) > 1 ) {
1068 return $p[0] == $allkeyword;
1076 public function getSearchEngine() {
1077 if ( $this->searchEngine
=== null ) {
1078 $this->searchEngine
= SearchEngine
::create();
1080 return $this->searchEngine
;
1084 * Users of hook SpecialSearchSetupEngine can use this to
1085 * add more params to links to not lose selection when
1086 * user navigates search results.
1089 public function setExtraParam( $key, $value ) {
1090 $this->extraParams
[$key] = $value;