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 ) {
55 global $wgRequest, $wgUser, $wgOut;
58 $this->outputHeader();
59 $wgOut->allowClickjacking();
60 $wgOut->addModuleStyles( 'mediawiki.special' );
62 // Strip underscores from title parameter; most of the time we'll want
63 // text form here. But don't strip underscores from actual text params!
64 $titleParam = str_replace( '_', ' ', $par );
66 // Fetch the search term
67 $search = str_replace( "\n", " ", $wgRequest->getText( 'search', $titleParam ) );
69 $this->load( $wgRequest, $wgUser );
71 if ( $wgRequest->getVal( 'fulltext' )
72 ||
!is_null( $wgRequest->getVal( 'offset' ) )
73 ||
!is_null( $wgRequest->getVal( 'searchx' ) ) )
75 $this->showResults( $search );
77 $this->goResult( $search );
82 * Set up basic search parameters from the request and user settings.
83 * Typically you'll pass $wgRequest and $wgUser.
85 * @param $request WebRequest
88 public function load( &$request, &$user ) {
89 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, 'searchlimit' );
90 $this->mPrefix
= $request->getVal( 'prefix', '' );
93 # Extract manually requested namespaces
94 $nslist = $this->powerSearch( $request );
95 $this->profile
= $profile = $request->getVal( 'profile', null );
96 $profiles = $this->getSearchProfiles();
97 if ( $profile === null) {
98 // BC with old request format
99 $this->profile
= 'advanced';
100 if ( count( $nslist ) ) {
101 foreach( $profiles as $key => $data ) {
102 if ( $nslist === $data['namespaces'] && $key !== 'advanced') {
103 $this->profile
= $key;
106 $this->namespaces
= $nslist;
108 $this->namespaces
= SearchEngine
::userNamespaces( $user );
110 } elseif ( $profile === 'advanced' ) {
111 $this->namespaces
= $nslist;
113 if ( isset( $profiles[$profile]['namespaces'] ) ) {
114 $this->namespaces
= $profiles[$profile]['namespaces'];
116 // Unknown profile requested
117 $this->profile
= 'default';
118 $this->namespaces
= $profiles['default']['namespaces'];
122 // Redirects defaults to true, but we don't know whether it was ticked of or just missing
123 $default = $request->getBool( 'profile' ) ?
0 : 1;
124 $this->searchRedirects
= $request->getBool( 'redirs', $default ) ?
1 : 0;
125 $this->sk
= $this->getSkin();
126 $this->didYouMeanHtml
= ''; # html of did you mean... link
127 $this->fulltext
= $request->getVal('fulltext');
131 * If an exact title match can be found, jump straight ahead to it.
133 * @param $term String
135 public function goResult( $term ) {
137 $this->setupPage( $term );
138 # Try to go to page as entered.
139 $t = Title
::newFromText( $term );
140 # If the string cannot be used to create a title
141 if( is_null( $t ) ) {
142 return $this->showResults( $term );
144 # If there's an exact or very near match, jump right there.
145 $t = SearchEngine
::getNearMatch( $term );
147 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
148 # Hook requested termination
152 if( !is_null( $t ) ) {
153 $wgOut->redirect( $t->getFullURL() );
156 # No match, generate an edit URL
157 $t = Title
::newFromText( $term );
158 if( !is_null( $t ) ) {
160 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
161 wfDebugLog( 'nogomatch', $t->getText(), false );
163 # If the feature is enabled, go straight to the edit page
165 $wgOut->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
169 return $this->showResults( $term );
173 * @param $term String
175 public function showResults( $term ) {
176 global $wgOut, $wgDisableTextSearch, $wgContLang, $wgScript;
177 wfProfileIn( __METHOD__
);
179 $sk = $this->getSkin();
181 $search = $this->getSearchEngine();
182 $search->setLimitOffset( $this->limit
, $this->offset
);
183 $search->setNamespaces( $this->namespaces
);
184 $search->showRedirects
= $this->searchRedirects
; // BC
185 $search->setFeatureData( 'list-redirects', $this->searchRedirects
);
186 $search->prefix
= $this->mPrefix
;
187 $term = $search->transformSearchTerm($term);
189 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
191 $this->setupPage( $term );
193 if( $wgDisableTextSearch ) {
194 global $wgSearchForwardUrl;
195 if( $wgSearchForwardUrl ) {
196 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
197 $wgOut->redirect( $url );
198 wfProfileOut( __METHOD__
);
202 Xml
::openElement( 'fieldset' ) .
203 Xml
::element( 'legend', null, wfMsg( 'search-external' ) ) .
204 Xml
::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
205 wfMsg( 'googlesearch',
206 htmlspecialchars( $term ),
207 htmlspecialchars( 'UTF-8' ),
208 htmlspecialchars( wfMsg( 'searchbutton' ) )
210 Xml
::closeElement( 'fieldset' )
212 wfProfileOut( __METHOD__
);
216 $t = Title
::newFromText( $term );
218 // fetch search results
219 $rewritten = $search->replacePrefixes($term);
221 $titleMatches = $search->searchTitle( $rewritten );
222 if( !($titleMatches instanceof SearchResultTooMany
))
223 $textMatches = $search->searchText( $rewritten );
225 // did you mean... suggestions
226 if( $textMatches && $textMatches->hasSuggestion() ) {
227 $st = SpecialPage
::getTitleFor( 'Search' );
229 # mirror Go/Search behaviour of original request ..
230 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
232 if($this->fulltext
!= null)
233 $didYouMeanParams['fulltext'] = $this->fulltext
;
235 $stParams = array_merge(
237 $this->powerSearchOptions()
240 $suggestionSnippet = $textMatches->getSuggestionSnippet();
242 if( $suggestionSnippet == '' )
243 $suggestionSnippet = null;
245 $suggestLink = $sk->linkKnown(
252 $this->didYouMeanHtml
= '<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>';
254 // start rendering the page
259 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
261 'action' => $wgScript
266 Xml
::openElement( 'table', array( 'id'=>'mw-search-top-table', 'border'=>0, 'cellpadding'=>0, 'cellspacing'=>0 ) ) .
267 Xml
::openElement( 'tr' ) .
268 Xml
::openElement( 'td' ) . "\n" .
269 $this->shortDialog( $term ) .
270 Xml
::closeElement('td') .
271 Xml
::closeElement('tr') .
272 Xml
::closeElement('table')
275 // Sometimes the search engine knows there are too many hits
276 if( $titleMatches instanceof SearchResultTooMany
) {
277 $wgOut->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
278 wfProfileOut( __METHOD__
);
282 $filePrefix = $wgContLang->getFormattedNsText(NS_FILE
).':';
283 if( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
284 $wgOut->addHTML( $this->formHeader( $term, 0, 0 ) );
285 $wgOut->addHtml( $this->getProfileForm( $this->profile
, $term ) );
286 $wgOut->addHTML( '</form>' );
287 // Empty query -- straight view of search form
288 wfProfileOut( __METHOD__
);
292 // Get number of results
293 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
294 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
295 // Total initial query matches (possible false positives)
296 $num = $titleMatchesNum +
$textMatchesNum;
298 // Get total actual results (after second filtering, if any)
299 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
300 $titleMatches->getTotalHits() : $titleMatchesNum;
301 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
302 $textMatches->getTotalHits() : $textMatchesNum;
304 // get total number of results if backend can calculate it
306 if($titleMatches && !is_null( $titleMatches->getTotalHits() ) )
307 $totalRes +
= $titleMatches->getTotalHits();
308 if($textMatches && !is_null( $textMatches->getTotalHits() ))
309 $totalRes +
= $textMatches->getTotalHits();
311 // show number of results and current offset
312 $wgOut->addHTML( $this->formHeader( $term, $num, $totalRes ) );
313 $wgOut->addHtml( $this->getProfileForm( $this->profile
, $term ) );
316 $wgOut->addHtml( Xml
::closeElement( 'form' ) );
317 $wgOut->addHtml( "<div class='searchresults'>" );
320 if( $num ||
$this->offset
) {
321 // Show the create link ahead
322 $this->showCreateLink( $t );
323 $prevnext = wfViewPrevNext( $this->offset
, $this->limit
,
324 SpecialPage
::getTitleFor( 'Search' ),
325 wfArrayToCGI( $this->powerSearchOptions(), array( 'search' => $term ) ),
326 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
328 //$wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
329 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
331 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
334 $wgOut->parserOptions()->setEditSection( false );
335 if( $titleMatches ) {
336 if( $numTitleMatches > 0 ) {
337 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
338 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
340 $titleMatches->free();
343 // output appropriate heading
344 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
345 // if no title matches the heading is redundant
346 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
347 } elseif( $totalRes == 0 ) {
348 # Don't show the 'no text matches' if we received title matches
349 # $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
351 // show interwiki results if any
352 if( $textMatches->hasInterwikiResults() ) {
353 $wgOut->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
356 if( $numTextMatches > 0 ) {
357 $wgOut->addHTML( $this->showMatches( $textMatches ) );
360 $textMatches->free();
363 $wgOut->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
364 $this->showCreateLink( $t );
366 $wgOut->addHtml( "</div>" );
368 if( $num ||
$this->offset
) {
369 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
371 wfProfileOut( __METHOD__
);
374 protected function showCreateLink( $t ) {
377 // show direct page/create link if applicable
378 // Check DBkey !== '' in case of fragment link only.
380 if( !is_null($t) && $t->getDBkey() !== '' ) {
381 if( $t->isKnown() ) {
382 $messageName = 'searchmenu-exists';
383 } elseif( $t->userCan( 'create' ) ) {
384 $messageName = 'searchmenu-new';
386 $messageName = 'searchmenu-new-nocreate';
390 $wgOut->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ) ) );
392 // preserve the paragraph for margins etc...
393 $wgOut->addHtml( '<p></p>' );
400 protected function setupPage( $term ) {
403 # Should advanced UI be used?
404 $this->searchAdvanced
= ($this->profile
=== 'advanced');
405 if( strval( $term ) !== '' ) {
406 $wgOut->setPageTitle( wfMsg( 'searchresults') );
407 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term ) ) );
409 // add javascript specific to special:search
410 $wgOut->addModules( 'mediawiki.legacy.search' );
411 $wgOut->addModules( 'mediawiki.special.search' );
415 * Extract "power search" namespace settings from the request object,
416 * returning a list of index numbers to search.
418 * @param $request WebRequest
421 protected function powerSearch( &$request ) {
423 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
424 if( $request->getCheck( 'ns' . $ns ) ) {
433 * Reconstruct the 'power search' options for links
437 protected function powerSearchOptions() {
439 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
440 if( $this->profile
!== 'advanced' ) {
441 $opt['profile'] = $this->profile
;
443 foreach( $this->namespaces
as $n ) {
447 return $opt +
$this->extraParams
;
451 * Show whole set of results
453 * @param $matches SearchResultSet
455 protected function showMatches( &$matches ) {
457 wfProfileIn( __METHOD__
);
459 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
462 $infoLine = $matches->getInfo();
463 if( !is_null($infoLine) ) {
464 $out .= "\n<!-- {$infoLine} -->\n";
466 $out .= "<ul class='mw-search-results'>\n";
467 while( $result = $matches->next() ) {
468 $out .= $this->showHit( $result, $terms );
472 // convert the whole thing to desired language variant
473 $out = $wgContLang->convert( $out );
474 wfProfileOut( __METHOD__
);
479 * Format a single hit result
481 * @param $result SearchResult
482 * @param $terms Array: terms to highlight
484 protected function showHit( $result, $terms ) {
486 wfProfileIn( __METHOD__
);
488 if( $result->isBrokenTitle() ) {
489 wfProfileOut( __METHOD__
);
490 return "<!-- Broken link in search result -->\n";
493 $sk = $this->getSkin();
494 $t = $result->getTitle();
496 $titleSnippet = $result->getTitleSnippet($terms);
498 if( $titleSnippet == '' )
499 $titleSnippet = null;
503 wfRunHooks( 'ShowSearchHitTitle',
504 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
506 $link = $this->sk
->linkKnown(
511 //If page content is not readable, just return the title.
512 //This is not quite safe, but better than showing excerpts from non-readable pages
513 //Note that hiding the entry entirely would screw up paging.
514 if( !$t->userCanRead() ) {
515 wfProfileOut( __METHOD__
);
516 return "<li>{$link}</li>\n";
519 // If the page doesn't *exist*... our search index is out of date.
520 // The least confusing at this point is to drop the result.
521 // You may get less results, but... oh well. :P
522 if( $result->isMissingRevision() ) {
523 wfProfileOut( __METHOD__
);
524 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
527 // format redirects / relevant sections
528 $redirectTitle = $result->getRedirectTitle();
529 $redirectText = $result->getRedirectSnippet($terms);
530 $sectionTitle = $result->getSectionTitle();
531 $sectionText = $result->getSectionSnippet($terms);
534 if( !is_null($redirectTitle) ) {
535 if( $redirectText == '' )
536 $redirectText = null;
538 $redirect = "<span class='searchalttitle'>" .
541 $this->sk
->linkKnown(
551 if( !is_null($sectionTitle) ) {
552 if( $sectionText == '' )
555 $section = "<span class='searchalttitle'>" .
557 'search-section', $this->sk
->linkKnown(
565 // format text extract
566 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
569 if( is_null( $result->getScore() ) ) {
570 // Search engine doesn't report scoring info
573 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
574 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
578 // format description
579 $byteSize = $result->getByteSize();
580 $wordCount = $result->getWordCount();
581 $timestamp = $result->getTimestamp();
583 'search-result-size',
584 array( 'parsemag', 'escape' ),
585 $wgLang->formatSize( $byteSize ),
586 $wgLang->formatNum( $wordCount )
589 if( $t->getNamespace() == NS_CATEGORY
) {
590 $cat = Category
::newFromTitle( $t );
592 'search-result-category-size',
593 array( 'parsemag', 'escape' ),
594 $wgLang->formatNum( $cat->getPageCount() ),
595 $wgLang->formatNum( $cat->getSubcatCount() ),
596 $wgLang->formatNum( $cat->getFileCount() )
600 $date = $wgLang->timeanddate( $timestamp );
602 // link to related articles if supported
604 if( $result->hasRelated() ) {
605 $st = SpecialPage
::getTitleFor( 'Search' );
606 $stParams = array_merge(
607 $this->powerSearchOptions(),
609 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
610 'fulltext' => wfMsg( 'search' )
614 $related = ' -- ' . $sk->linkKnown(
616 wfMsg('search-relatedarticle'),
622 // Include a thumbnail for media files...
623 if( $t->getNamespace() == NS_FILE
) {
624 $img = wfFindFile( $t );
626 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
628 $desc = wfMsg( 'parentheses', $img->getShortDesc() );
629 wfProfileOut( __METHOD__
);
630 // Float doesn't seem to interact well with the bullets.
631 // Table messes up vertical alignment of the bullets.
632 // Bullets are therefore disabled (didn't look great anyway).
634 '<table class="searchResultImage">' .
636 '<td width="120" align="center" valign="top">' .
637 $thumb->toHtml( array( 'desc-link' => true ) ) .
639 '<td valign="top">' .
642 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
651 wfProfileOut( __METHOD__
);
652 return "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
653 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
659 * Show results from other wikis
661 * @param $matches SearchResultSet
662 * @param $query String
664 protected function showInterwiki( &$matches, $query ) {
666 wfProfileIn( __METHOD__
);
667 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
669 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
670 wfMsg('search-interwiki-caption')."</div>\n";
671 $out .= "<ul class='mw-search-iwresults'>\n";
673 // work out custom project captions
674 $customCaptions = array();
675 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
676 foreach($customLines as $line) {
677 $parts = explode(":",$line,2);
678 if(count($parts) == 2) // validate line
679 $customCaptions[$parts[0]] = $parts[1];
683 while( $result = $matches->next() ) {
684 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
685 $prev = $result->getInterwikiPrefix();
687 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
688 $out .= "</ul></div>\n";
690 // convert the whole thing to desired language variant
691 $out = $wgContLang->convert( $out );
692 wfProfileOut( __METHOD__
);
697 * Show single interwiki link
699 * @param $result SearchResult
700 * @param $lastInterwiki String
701 * @param $terms Array
702 * @param $query String
703 * @param $customCaptions Array: iw prefix -> caption
705 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
706 wfProfileIn( __METHOD__
);
708 if( $result->isBrokenTitle() ) {
709 wfProfileOut( __METHOD__
);
710 return "<!-- Broken link in search result -->\n";
713 $t = $result->getTitle();
715 $titleSnippet = $result->getTitleSnippet($terms);
717 if( $titleSnippet == '' )
718 $titleSnippet = null;
720 $link = $this->sk
->linkKnown(
725 // format redirect if any
726 $redirectTitle = $result->getRedirectTitle();
727 $redirectText = $result->getRedirectSnippet($terms);
729 if( !is_null($redirectTitle) ) {
730 if( $redirectText == '' )
731 $redirectText = null;
733 $redirect = "<span class='searchalttitle'>" .
736 $this->sk
->linkKnown(
745 // display project name
746 if(is_null($lastInterwiki) ||
$lastInterwiki != $t->getInterwiki()) {
747 if( key_exists($t->getInterwiki(),$customCaptions) )
748 // captions from 'search-interwiki-custom'
749 $caption = $customCaptions[$t->getInterwiki()];
751 // default is to show the hostname of the other wiki which might suck
752 // if there are many wikis on one hostname
753 $parsed = parse_url($t->getFullURL());
754 $caption = wfMsg('search-interwiki-default', $parsed['host']);
756 // "more results" link (special page stuff could be localized, but we might not know target lang)
757 $searchTitle = Title
::newFromText($t->getInterwiki().":Special:Search");
758 $searchLink = $this->sk
->linkKnown(
760 wfMsg('search-interwiki-more'),
764 'fulltext' => 'Search'
767 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
768 {$searchLink}</span>{$caption}</div>\n<ul>";
771 $out .= "<li>{$link} {$redirect}</li>\n";
772 wfProfileOut( __METHOD__
);
776 protected function getProfileForm( $profile, $term ) {
779 $opts['redirs'] = $this->searchRedirects
;
780 $opts['profile'] = $this->profile
;
782 if ( $profile === 'advanced' ) {
783 return $this->powerSearchBox( $term, $opts );
786 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
792 * Generates the power search box at [[Special:Search]]
794 * @param $term String: search term
795 * @return String: HTML form
797 protected function powerSearchBox( $term, $opts ) {
798 // Groups namespaces into rows according to subject
800 foreach( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
801 $subject = MWNamespace
::getSubject( $namespace );
802 if( !array_key_exists( $subject, $rows ) ) {
803 $rows[$subject] = "";
805 $name = str_replace( '_', ' ', $name );
807 $name = wfMsg( 'blanknamespace' );
811 'td', array( 'style' => 'white-space: nowrap' )
816 "mw-search-ns{$namespace}",
817 in_array( $namespace, $this->namespaces
)
819 Xml
::closeElement( 'td' );
821 $rows = array_values( $rows );
822 $numRows = count( $rows );
824 // Lays out namespaces in multiple floating two-column tables so they'll
825 // be arranged nicely while still accommodating different screen widths
826 $namespaceTables = '';
827 for( $i = 0; $i < $numRows; $i +
= 4 ) {
828 $namespaceTables .= Xml
::openElement(
830 array( 'cellpadding' => 0, 'cellspacing' => 0, 'border' => 0 )
832 for( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
833 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
835 $namespaceTables .= Xml
::closeElement( 'table' );
837 // Show redirects check only if backend supports it
839 if( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
841 Xml
::checkLabel( wfMsg( 'powersearch-redir' ), 'redirs', 'redirs', $this->searchRedirects
);
845 unset( $opts['redirs'] );
846 foreach( $opts as $key => $value ) {
847 $hidden .= Html
::hidden( $key, $value );
849 // Return final output
853 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
855 Xml
::element( 'legend', null, wfMsg('powersearch-legend') ) .
856 Xml
::tags( 'h4', null, wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) ) .
859 array( 'id' => 'mw-search-togglebox' ),
860 Xml
::label( wfMsg( 'powersearch-togglelabel' ), 'mw-search-togglelabel' ) .
865 'id' => 'mw-search-toggleall',
866 'onclick' => 'mwToggleSearchCheckboxes("all");',
867 'value' => wfMsg( 'powersearch-toggleall' )
874 'id' => 'mw-search-togglenone',
875 'onclick' => 'mwToggleSearchCheckboxes("none");',
876 'value' => wfMsg( 'powersearch-togglenone' )
880 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
882 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
883 $redirects . $hidden .
884 Xml
::closeElement( 'fieldset' );
887 protected function getSearchProfiles() {
888 // Builds list of Search Types (profiles)
889 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
893 'message' => 'searchprofile-articles',
894 'tooltip' => 'searchprofile-articles-tooltip',
895 'namespaces' => SearchEngine
::defaultNamespaces(),
896 'namespace-messages' => SearchEngine
::namespacesAsText(
897 SearchEngine
::defaultNamespaces()
901 'message' => 'searchprofile-images',
902 'tooltip' => 'searchprofile-images-tooltip',
903 'namespaces' => array( NS_FILE
),
906 'message' => 'searchprofile-project',
907 'tooltip' => 'searchprofile-project-tooltip',
908 'namespaces' => SearchEngine
::helpNamespaces(),
909 'namespace-messages' => SearchEngine
::namespacesAsText(
910 SearchEngine
::helpNamespaces()
914 'message' => 'searchprofile-everything',
915 'tooltip' => 'searchprofile-everything-tooltip',
916 'namespaces' => $nsAllSet,
919 'message' => 'searchprofile-advanced',
920 'tooltip' => 'searchprofile-advanced-tooltip',
921 'namespaces' => self
::NAMESPACES_CURRENT
,
925 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
927 foreach( $profiles as &$data ) {
928 if ( !is_array( $data['namespaces'] ) ) continue;
929 sort( $data['namespaces'] );
935 protected function formHeader( $term, $resultsShown, $totalNum ) {
938 $out = Xml
::openElement('div', array( 'class' => 'mw-search-formheader' ) );
941 if( $this->startsWithImage( $term ) ) {
943 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
946 $profiles = $this->getSearchProfiles();
948 // Outputs XML for Search Types
949 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
950 $out .= Xml
::openElement( 'ul' );
951 foreach ( $profiles as $id => $profile ) {
952 if ( !isset( $profile['parameters'] ) ) {
953 $profile['parameters'] = array();
955 $profile['parameters']['profile'] = $id;
957 $tooltipParam = isset( $profile['namespace-messages'] ) ?
958 $wgLang->commaList( $profile['namespace-messages'] ) : null;
962 'class' => $this->profile
=== $id ?
'current' : 'normal'
964 $this->makeSearchLink(
967 wfMsg( $profile['message'] ),
968 wfMsg( $profile['tooltip'], $tooltipParam ),
969 $profile['parameters']
973 $out .= Xml
::closeElement( 'ul' );
974 $out .= Xml
::closeElement('div') ;
977 if ( $resultsShown > 0 ) {
978 if ( $totalNum > 0 ){
979 $top = wfMsgExt( 'showingresultsheader', array( 'parseinline' ),
980 $wgLang->formatNum( $this->offset +
1 ),
981 $wgLang->formatNum( $this->offset +
$resultsShown ),
982 $wgLang->formatNum( $totalNum ),
983 wfEscapeWikiText( $term ),
984 $wgLang->formatNum( $resultsShown )
986 } elseif ( $resultsShown >= $this->limit
) {
987 $top = wfShowingResults( $this->offset
, $this->limit
);
989 $top = wfShowingResultsNum( $this->offset
, $this->limit
, $resultsShown );
991 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
992 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
996 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
997 $out .= Xml
::closeElement('div');
1002 protected function shortDialog( $term ) {
1003 $out = Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1005 $out .= Html
::input( 'search', $term, 'search', array(
1006 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1010 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1011 $out .= Xml
::submitButton( wfMsg( 'searchbutton' ) ) . "\n";
1012 return $out . $this->didYouMeanHtml
;
1016 * Make a search link with some target namespaces
1018 * @param $term String
1019 * @param $namespaces Array ignored
1020 * @param $label String: link's text
1021 * @param $tooltip String: link's tooltip
1022 * @param $params Array: query string parameters
1023 * @return String: HTML fragment
1025 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1027 foreach( $namespaces as $n ) {
1028 $opt['ns' . $n] = 1;
1030 $opt['redirs'] = $this->searchRedirects
;
1032 $stParams = array_merge(
1035 'fulltext' => wfMsg( 'search' )
1040 return Xml
::element(
1043 'href' => $this->getTitle()->getLocalURL( $stParams ),
1044 'title' => $tooltip,
1045 'onmousedown' => 'mwSearchHeaderClick(this);',
1046 'onkeydown' => 'mwSearchHeaderClick(this);'),
1052 * Check if query starts with image: prefix
1054 * @param $term String: the string to check
1057 protected function startsWithImage( $term ) {
1060 $p = explode( ':', $term );
1061 if( count( $p ) > 1 ) {
1062 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE
;
1068 * Check if query starts with all: prefix
1070 * @param $term String: the string to check
1073 protected function startsWithAll( $term ) {
1075 $allkeyword = wfMsgForContent('searchall');
1077 $p = explode( ':', $term );
1078 if( count( $p ) > 1 ) {
1079 return $p[0] == $allkeyword;
1087 public function getSearchEngine() {
1088 if ( $this->searchEngine
=== null ) {
1089 $this->searchEngine
= SearchEngine
::create();
1091 return $this->searchEngine
;
1095 * Users of hook SpecialSearchSetupEngine can use this to
1096 * add more params to links to not lose selection when
1097 * user navigates search results.
1100 public function setExtraParam( $key, $value ) {
1101 $this->extraParams
[$key] = $value;