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.
42 protected $searchEngine;
45 protected $extraParams = array();
47 /// No idea, apparently used by some other classes
53 protected $limit, $offset;
58 protected $namespaces;
63 protected $searchRedirects;
68 protected $didYouMeanHtml, $fulltext;
70 const NAMESPACES_CURRENT
= 'sense';
72 public function __construct() {
73 parent
::__construct( 'Search' );
79 * @param $par String or null
81 public function execute( $par ) {
83 $this->outputHeader();
84 $out = $this->getOutput();
85 $out->allowClickjacking();
86 $out->addModuleStyles( 'mediawiki.special' );
88 // Strip underscores from title parameter; most of the time we'll want
89 // text form here. But don't strip underscores from actual text params!
90 $titleParam = str_replace( '_', ' ', $par );
92 $request = $this->getRequest();
94 // Fetch the search term
95 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
99 if ( $request->getVal( 'fulltext' )
100 ||
!is_null( $request->getVal( 'offset' ) )
101 ||
!is_null( $request->getVal( 'searchx' ) ) )
103 $this->showResults( $search );
105 $this->goResult( $search );
110 * Set up basic search parameters from the request and user settings.
112 public function load() {
113 $request = $this->getRequest();
114 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, 'searchlimit' );
115 $this->mPrefix
= $request->getVal( 'prefix', '' );
117 $user = $this->getUser();
118 # Extract manually requested namespaces
119 $nslist = $this->powerSearch( $request );
120 $this->profile
= $profile = $request->getVal( 'profile', null );
121 $profiles = $this->getSearchProfiles();
122 if ( $profile === null) {
123 // BC with old request format
124 $this->profile
= 'advanced';
125 if ( count( $nslist ) ) {
126 foreach( $profiles as $key => $data ) {
127 if ( $nslist === $data['namespaces'] && $key !== 'advanced') {
128 $this->profile
= $key;
131 $this->namespaces
= $nslist;
133 $this->namespaces
= SearchEngine
::userNamespaces( $user );
135 } elseif ( $profile === 'advanced' ) {
136 $this->namespaces
= $nslist;
138 if ( isset( $profiles[$profile]['namespaces'] ) ) {
139 $this->namespaces
= $profiles[$profile]['namespaces'];
141 // Unknown profile requested
142 $this->profile
= 'default';
143 $this->namespaces
= $profiles['default']['namespaces'];
147 // Redirects defaults to true, but we don't know whether it was ticked of or just missing
148 $default = $request->getBool( 'profile' ) ?
0 : 1;
149 $this->searchRedirects
= $request->getBool( 'redirs', $default ) ?
1 : 0;
150 $this->didYouMeanHtml
= ''; # html of did you mean... link
151 $this->fulltext
= $request->getVal('fulltext');
155 * If an exact title match can be found, jump straight ahead to it.
157 * @param $term String
159 public function goResult( $term ) {
160 $this->setupPage( $term );
161 # Try to go to page as entered.
162 $t = Title
::newFromText( $term );
163 # If the string cannot be used to create a title
164 if( is_null( $t ) ) {
165 return $this->showResults( $term );
167 # If there's an exact or very near match, jump right there.
168 $t = SearchEngine
::getNearMatch( $term );
170 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
171 # Hook requested termination
175 if( !is_null( $t ) ) {
176 $this->getOutput()->redirect( $t->getFullURL() );
179 # No match, generate an edit URL
180 $t = Title
::newFromText( $term );
181 if( !is_null( $t ) ) {
183 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
184 wfDebugLog( 'nogomatch', $t->getText(), false );
186 # If the feature is enabled, go straight to the edit page
188 $this->getOutput()->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
192 return $this->showResults( $term );
196 * @param $term String
198 public function showResults( $term ) {
199 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
200 wfProfileIn( __METHOD__
);
202 $search = $this->getSearchEngine();
203 $search->setLimitOffset( $this->limit
, $this->offset
);
204 $search->setNamespaces( $this->namespaces
);
205 $search->showRedirects
= $this->searchRedirects
; // BC
206 $search->setFeatureData( 'list-redirects', $this->searchRedirects
);
207 $search->prefix
= $this->mPrefix
;
208 $term = $search->transformSearchTerm($term);
210 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
212 $this->setupPage( $term );
214 $out = $this->getOutput();
216 if ( $wgDisableTextSearch ) {
217 if ( $wgSearchForwardUrl ) {
218 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
219 $out->redirect( $url );
222 Xml
::openElement( 'fieldset' ) .
223 Xml
::element( 'legend', null, wfMsg( 'search-external' ) ) .
224 Xml
::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
225 wfMsg( 'googlesearch',
226 htmlspecialchars( $term ),
227 htmlspecialchars( 'UTF-8' ),
228 htmlspecialchars( wfMsg( 'searchbutton' ) )
230 Xml
::closeElement( 'fieldset' )
233 wfProfileOut( __METHOD__
);
237 $t = Title
::newFromText( $term );
239 // fetch search results
240 $rewritten = $search->replacePrefixes($term);
242 $titleMatches = $search->searchTitle( $rewritten );
243 if( !( $titleMatches instanceof SearchResultTooMany
) ) {
244 $textMatches = $search->searchText( $rewritten );
247 // did you mean... suggestions
248 if( $textMatches && $textMatches->hasSuggestion() ) {
249 $st = SpecialPage
::getTitleFor( 'Search' );
251 # mirror Go/Search behaviour of original request ..
252 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
254 if( $this->fulltext
!= null ) {
255 $didYouMeanParams['fulltext'] = $this->fulltext
;
258 $stParams = array_merge(
260 $this->powerSearchOptions()
263 $suggestionSnippet = $textMatches->getSuggestionSnippet();
265 if( $suggestionSnippet == '' ) {
266 $suggestionSnippet = null;
269 $suggestLink = Linker
::linkKnown(
276 $this->didYouMeanHtml
= '<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>';
278 // start rendering the page
283 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
285 'action' => $wgScript
290 Xml
::openElement( 'table', array( 'id'=>'mw-search-top-table', 'border'=>0, 'cellpadding'=>0, 'cellspacing'=>0 ) ) .
291 Xml
::openElement( 'tr' ) .
292 Xml
::openElement( 'td' ) . "\n" .
293 $this->shortDialog( $term ) .
294 Xml
::closeElement('td') .
295 Xml
::closeElement('tr') .
296 Xml
::closeElement('table')
299 // Sometimes the search engine knows there are too many hits
300 if( $titleMatches instanceof SearchResultTooMany
) {
301 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
302 wfProfileOut( __METHOD__
);
306 $filePrefix = $wgContLang->getFormattedNsText(NS_FILE
).':';
307 if( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
308 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
309 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
310 $out->addHTML( '</form>' );
311 // Empty query -- straight view of search form
312 wfProfileOut( __METHOD__
);
316 // Get number of results
317 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
318 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
319 // Total initial query matches (possible false positives)
320 $num = $titleMatchesNum +
$textMatchesNum;
322 // Get total actual results (after second filtering, if any)
323 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
324 $titleMatches->getTotalHits() : $titleMatchesNum;
325 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
326 $textMatches->getTotalHits() : $textMatchesNum;
328 // get total number of results if backend can calculate it
330 if($titleMatches && !is_null( $titleMatches->getTotalHits() ) )
331 $totalRes +
= $titleMatches->getTotalHits();
332 if($textMatches && !is_null( $textMatches->getTotalHits() ))
333 $totalRes +
= $textMatches->getTotalHits();
335 // show number of results and current offset
336 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
337 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
340 $out->addHtml( Xml
::closeElement( 'form' ) );
341 $out->addHtml( "<div class='searchresults'>" );
344 if( $num ||
$this->offset
) {
345 // Show the create link ahead
346 $this->showCreateLink( $t );
347 $prevnext = $this->getLang()->viewPrevNext( $this->getTitle(), $this->offset
, $this->limit
,
348 $this->powerSearchOptions() +
array( 'search' => $term ),
349 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
351 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
352 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
354 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
357 $out->parserOptions()->setEditSection( false );
358 if( $titleMatches ) {
359 if( $numTitleMatches > 0 ) {
360 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
361 $out->addHTML( $this->showMatches( $titleMatches ) );
363 $titleMatches->free();
366 // output appropriate heading
367 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
368 // if no title matches the heading is redundant
369 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
370 } elseif( $totalRes == 0 ) {
371 # Don't show the 'no text matches' if we received title matches
372 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
374 // show interwiki results if any
375 if( $textMatches->hasInterwikiResults() ) {
376 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
379 if( $numTextMatches > 0 ) {
380 $out->addHTML( $this->showMatches( $textMatches ) );
383 $textMatches->free();
386 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
387 $this->showCreateLink( $t );
389 $out->addHtml( "</div>" );
391 if( $num ||
$this->offset
) {
392 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
394 wfProfileOut( __METHOD__
);
400 protected function showCreateLink( $t ) {
401 // show direct page/create link if applicable
403 // Check DBkey !== '' in case of fragment link only.
404 if( is_null( $t ) ||
$t->getDBkey() === '' ) {
406 // preserve the paragraph for margins etc...
407 $this->getOutput()->addHtml( '<p></p>' );
411 if( $t->isKnown() ) {
412 $messageName = 'searchmenu-exists';
413 } elseif( $t->userCan( 'create' ) ) {
414 $messageName = 'searchmenu-new';
416 $messageName = 'searchmenu-new-nocreate';
418 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ) );
419 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
421 // Extensions using the hook might still return an empty $messageName
423 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
425 // preserve the paragraph for margins etc...
426 $this->getOutput()->addHtml( '<p></p>' );
431 * @param $term string
433 protected function setupPage( $term ) {
434 # Should advanced UI be used?
435 $this->searchAdvanced
= ($this->profile
=== 'advanced');
436 $out = $this->getOutput();
437 if( strval( $term ) !== '' ) {
438 $out->setPageTitle( $this->msg( 'searchresults' ) );
439 $out->setHTMLTitle( $this->msg( 'pagetitle', $this->msg( 'searchresults-title', $term )->plain() ) );
441 // add javascript specific to special:search
442 $out->addModules( 'mediawiki.special.search' );
446 * Extract "power search" namespace settings from the request object,
447 * returning a list of index numbers to search.
449 * @param $request WebRequest
452 protected function powerSearch( &$request ) {
454 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
455 if( $request->getCheck( 'ns' . $ns ) ) {
464 * Reconstruct the 'power search' options for links
468 protected function powerSearchOptions() {
470 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
471 if( $this->profile
!== 'advanced' ) {
472 $opt['profile'] = $this->profile
;
474 foreach( $this->namespaces
as $n ) {
478 return $opt +
$this->extraParams
;
482 * Show whole set of results
484 * @param $matches SearchResultSet
488 protected function showMatches( &$matches ) {
490 wfProfileIn( __METHOD__
);
492 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
495 $infoLine = $matches->getInfo();
496 if( !is_null($infoLine) ) {
497 $out .= "\n<!-- {$infoLine} -->\n";
499 $out .= "<ul class='mw-search-results'>\n";
500 $result = $matches->next();
502 $out .= $this->showHit( $result, $terms );
503 $result = $matches->next();
507 // convert the whole thing to desired language variant
508 $out = $wgContLang->convert( $out );
509 wfProfileOut( __METHOD__
);
514 * Format a single hit result
516 * @param $result SearchResult
517 * @param $terms Array: terms to highlight
521 protected function showHit( $result, $terms ) {
522 wfProfileIn( __METHOD__
);
524 if( $result->isBrokenTitle() ) {
525 wfProfileOut( __METHOD__
);
526 return "<!-- Broken link in search result -->\n";
529 $t = $result->getTitle();
531 $titleSnippet = $result->getTitleSnippet($terms);
533 if( $titleSnippet == '' )
534 $titleSnippet = null;
538 wfRunHooks( 'ShowSearchHitTitle',
539 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
541 $link = Linker
::linkKnown(
546 //If page content is not readable, just return the title.
547 //This is not quite safe, but better than showing excerpts from non-readable pages
548 //Note that hiding the entry entirely would screw up paging.
549 if( !$t->userCanRead() ) {
550 wfProfileOut( __METHOD__
);
551 return "<li>{$link}</li>\n";
554 // If the page doesn't *exist*... our search index is out of date.
555 // The least confusing at this point is to drop the result.
556 // You may get less results, but... oh well. :P
557 if( $result->isMissingRevision() ) {
558 wfProfileOut( __METHOD__
);
559 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
562 // format redirects / relevant sections
563 $redirectTitle = $result->getRedirectTitle();
564 $redirectText = $result->getRedirectSnippet($terms);
565 $sectionTitle = $result->getSectionTitle();
566 $sectionText = $result->getSectionSnippet($terms);
569 if( !is_null($redirectTitle) ) {
570 if( $redirectText == '' )
571 $redirectText = null;
573 $redirect = "<span class='searchalttitle'>" .
586 if( !is_null($sectionTitle) ) {
587 if( $sectionText == '' )
590 $section = "<span class='searchalttitle'>" .
592 'search-section', Linker
::linkKnown(
600 // format text extract
601 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
603 $lang = $this->getLang();
606 if( is_null( $result->getScore() ) ) {
607 // Search engine doesn't report scoring info
610 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
611 $score = wfMsg( 'search-result-score', $lang->formatNum( $percent ) )
615 // format description
616 $byteSize = $result->getByteSize();
617 $wordCount = $result->getWordCount();
618 $timestamp = $result->getTimestamp();
620 'search-result-size',
621 array( 'parsemag', 'escape' ),
622 $lang->formatSize( $byteSize ),
623 $lang->formatNum( $wordCount )
626 if( $t->getNamespace() == NS_CATEGORY
) {
627 $cat = Category
::newFromTitle( $t );
629 'search-result-category-size',
630 array( 'parsemag', 'escape' ),
631 $lang->formatNum( $cat->getPageCount() ),
632 $lang->formatNum( $cat->getSubcatCount() ),
633 $lang->formatNum( $cat->getFileCount() )
637 $date = $lang->timeanddate( $timestamp );
639 // link to related articles if supported
641 if( $result->hasRelated() ) {
642 $st = SpecialPage
::getTitleFor( 'Search' );
643 $stParams = array_merge(
644 $this->powerSearchOptions(),
646 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
647 'fulltext' => wfMsg( 'search' )
651 $related = ' -- ' . Linker
::linkKnown(
653 wfMsg('search-relatedarticle'),
659 // Include a thumbnail for media files...
660 if( $t->getNamespace() == NS_FILE
) {
661 $img = wfFindFile( $t );
663 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
665 $desc = wfMsg( 'parentheses', $img->getShortDesc() );
666 wfProfileOut( __METHOD__
);
667 // Float doesn't seem to interact well with the bullets.
668 // Table messes up vertical alignment of the bullets.
669 // Bullets are therefore disabled (didn't look great anyway).
671 '<table class="searchResultImage">' .
673 '<td width="120" align="center" valign="top">' .
674 $thumb->toHtml( array( 'desc-link' => true ) ) .
676 '<td valign="top">' .
679 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
688 wfProfileOut( __METHOD__
);
689 return "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
690 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
696 * Show results from other wikis
698 * @param $matches SearchResultSet
699 * @param $query String
703 protected function showInterwiki( &$matches, $query ) {
705 wfProfileIn( __METHOD__
);
706 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
708 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
709 wfMsg('search-interwiki-caption')."</div>\n";
710 $out .= "<ul class='mw-search-iwresults'>\n";
712 // work out custom project captions
713 $customCaptions = array();
714 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
715 foreach($customLines as $line) {
716 $parts = explode(":",$line,2);
717 if(count($parts) == 2) // validate line
718 $customCaptions[$parts[0]] = $parts[1];
722 $result = $matches->next();
724 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
725 $prev = $result->getInterwikiPrefix();
726 $result = $matches->next();
728 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
729 $out .= "</ul></div>\n";
731 // convert the whole thing to desired language variant
732 $out = $wgContLang->convert( $out );
733 wfProfileOut( __METHOD__
);
738 * Show single interwiki link
740 * @param $result SearchResult
741 * @param $lastInterwiki String
742 * @param $terms Array
743 * @param $query String
744 * @param $customCaptions Array: iw prefix -> caption
748 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
749 wfProfileIn( __METHOD__
);
751 if( $result->isBrokenTitle() ) {
752 wfProfileOut( __METHOD__
);
753 return "<!-- Broken link in search result -->\n";
756 $t = $result->getTitle();
758 $titleSnippet = $result->getTitleSnippet($terms);
760 if( $titleSnippet == '' )
761 $titleSnippet = null;
763 $link = Linker
::linkKnown(
768 // format redirect if any
769 $redirectTitle = $result->getRedirectTitle();
770 $redirectText = $result->getRedirectSnippet($terms);
772 if( !is_null($redirectTitle) ) {
773 if( $redirectText == '' )
774 $redirectText = null;
776 $redirect = "<span class='searchalttitle'>" .
788 // display project name
789 if(is_null($lastInterwiki) ||
$lastInterwiki != $t->getInterwiki()) {
790 if( array_key_exists($t->getInterwiki(),$customCaptions) ) {
791 // captions from 'search-interwiki-custom'
792 $caption = $customCaptions[$t->getInterwiki()];
794 // default is to show the hostname of the other wiki which might suck
795 // if there are many wikis on one hostname
796 $parsed = wfParseUrl( $t->getFullURL() );
797 $caption = wfMsg('search-interwiki-default', $parsed['host']);
799 // "more results" link (special page stuff could be localized, but we might not know target lang)
800 $searchTitle = Title
::newFromText($t->getInterwiki().":Special:Search");
801 $searchLink = Linker
::linkKnown(
803 wfMsg('search-interwiki-more'),
807 'fulltext' => 'Search'
810 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
811 {$searchLink}</span>{$caption}</div>\n<ul>";
814 $out .= "<li>{$link} {$redirect}</li>\n";
815 wfProfileOut( __METHOD__
);
824 protected function getProfileForm( $profile, $term ) {
827 $opts['redirs'] = $this->searchRedirects
;
828 $opts['profile'] = $this->profile
;
830 if ( $profile === 'advanced' ) {
831 return $this->powerSearchBox( $term, $opts );
834 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
840 * Generates the power search box at [[Special:Search]]
842 * @param $term String: search term
844 * @return String: HTML form
846 protected function powerSearchBox( $term, $opts ) {
847 // Groups namespaces into rows according to subject
849 foreach( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
850 $subject = MWNamespace
::getSubject( $namespace );
851 if( !array_key_exists( $subject, $rows ) ) {
852 $rows[$subject] = "";
854 $name = str_replace( '_', ' ', $name );
856 $name = wfMsg( 'blanknamespace' );
860 'td', array( 'style' => 'white-space: nowrap' )
865 "mw-search-ns{$namespace}",
866 in_array( $namespace, $this->namespaces
)
868 Xml
::closeElement( 'td' );
870 $rows = array_values( $rows );
871 $numRows = count( $rows );
873 // Lays out namespaces in multiple floating two-column tables so they'll
874 // be arranged nicely while still accommodating different screen widths
875 $namespaceTables = '';
876 for( $i = 0; $i < $numRows; $i +
= 4 ) {
877 $namespaceTables .= Xml
::openElement(
879 array( 'cellpadding' => 0, 'cellspacing' => 0, 'border' => 0 )
881 for( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
882 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
884 $namespaceTables .= Xml
::closeElement( 'table' );
887 $showSections = array( 'namespaceTables' => $namespaceTables );
889 // Show redirects check only if backend supports it
890 if( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
891 $showSections['redirects'] =
892 Xml
::checkLabel( wfMsg( 'powersearch-redir' ), 'redirs', 'redirs', $this->searchRedirects
);
895 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
898 unset( $opts['redirs'] );
899 foreach( $opts as $key => $value ) {
900 $hidden .= Html
::hidden( $key, $value );
902 // Return final output
906 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
908 Xml
::element( 'legend', null, wfMsg('powersearch-legend') ) .
909 Xml
::tags( 'h4', null, wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) ) .
912 array( 'id' => 'mw-search-togglebox' ),
913 Xml
::label( wfMsg( 'powersearch-togglelabel' ), 'mw-search-togglelabel' ) .
918 'id' => 'mw-search-toggleall',
919 'value' => wfMsg( 'powersearch-toggleall' )
926 'id' => 'mw-search-togglenone',
927 'value' => wfMsg( 'powersearch-togglenone' )
931 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
932 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
934 Xml
::closeElement( 'fieldset' );
940 protected function getSearchProfiles() {
941 // Builds list of Search Types (profiles)
942 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
946 'message' => 'searchprofile-articles',
947 'tooltip' => 'searchprofile-articles-tooltip',
948 'namespaces' => SearchEngine
::defaultNamespaces(),
949 'namespace-messages' => SearchEngine
::namespacesAsText(
950 SearchEngine
::defaultNamespaces()
954 'message' => 'searchprofile-images',
955 'tooltip' => 'searchprofile-images-tooltip',
956 'namespaces' => array( NS_FILE
),
959 'message' => 'searchprofile-project',
960 'tooltip' => 'searchprofile-project-tooltip',
961 'namespaces' => SearchEngine
::helpNamespaces(),
962 'namespace-messages' => SearchEngine
::namespacesAsText(
963 SearchEngine
::helpNamespaces()
967 'message' => 'searchprofile-everything',
968 'tooltip' => 'searchprofile-everything-tooltip',
969 'namespaces' => $nsAllSet,
972 'message' => 'searchprofile-advanced',
973 'tooltip' => 'searchprofile-advanced-tooltip',
974 'namespaces' => self
::NAMESPACES_CURRENT
,
978 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
980 foreach( $profiles as &$data ) {
981 if ( !is_array( $data['namespaces'] ) ) continue;
982 sort( $data['namespaces'] );
990 * @param $resultsShown
994 protected function formHeader( $term, $resultsShown, $totalNum ) {
995 $out = Xml
::openElement('div', array( 'class' => 'mw-search-formheader' ) );
998 if( $this->startsWithImage( $term ) ) {
1000 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1003 $profiles = $this->getSearchProfiles();
1004 $lang = $this->getLang();
1006 // Outputs XML for Search Types
1007 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1008 $out .= Xml
::openElement( 'ul' );
1009 foreach ( $profiles as $id => $profile ) {
1010 if ( !isset( $profile['parameters'] ) ) {
1011 $profile['parameters'] = array();
1013 $profile['parameters']['profile'] = $id;
1015 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1016 $lang->commaList( $profile['namespace-messages'] ) : null;
1020 'class' => $this->profile
=== $id ?
'current' : 'normal'
1022 $this->makeSearchLink(
1025 wfMsg( $profile['message'] ),
1026 wfMsg( $profile['tooltip'], $tooltipParam ),
1027 $profile['parameters']
1031 $out .= Xml
::closeElement( 'ul' );
1032 $out .= Xml
::closeElement('div') ;
1035 if ( $resultsShown > 0 ) {
1036 if ( $totalNum > 0 ){
1037 $top = wfMsgExt( 'showingresultsheader', array( 'parseinline' ),
1038 $lang->formatNum( $this->offset +
1 ),
1039 $lang->formatNum( $this->offset +
$resultsShown ),
1040 $lang->formatNum( $totalNum ),
1041 wfEscapeWikiText( $term ),
1042 $lang->formatNum( $resultsShown )
1044 } elseif ( $resultsShown >= $this->limit
) {
1045 $top = wfMsgExt( 'showingresults', array( 'parseinline' ),
1046 $lang->formatNum( $this->limit
),
1047 $lang->formatNum( $this->offset +
1 )
1050 $top = wfMsgExt( 'showingresultsnum', array( 'parseinline' ),
1051 $lang->formatNum( $this->limit
),
1052 $lang->formatNum( $this->offset +
1 ),
1053 $lang->formatNum( $resultsShown )
1056 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1057 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1061 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1062 $out .= Xml
::closeElement('div');
1068 * @param $term string
1071 protected function shortDialog( $term ) {
1072 $out = Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1074 $out .= Html
::input( 'search', $term, 'search', array(
1075 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1079 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1080 $out .= Xml
::submitButton( wfMsg( 'searchbutton' ) ) . "\n";
1081 return $out . $this->didYouMeanHtml
;
1085 * Make a search link with some target namespaces
1087 * @param $term String
1088 * @param $namespaces Array ignored
1089 * @param $label String: link's text
1090 * @param $tooltip String: link's tooltip
1091 * @param $params Array: query string parameters
1092 * @return String: HTML fragment
1094 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1096 foreach( $namespaces as $n ) {
1097 $opt['ns' . $n] = 1;
1099 $opt['redirs'] = $this->searchRedirects
;
1101 $stParams = array_merge(
1104 'fulltext' => wfMsg( 'search' )
1109 return Xml
::element(
1112 'href' => $this->getTitle()->getLocalURL( $stParams ),
1113 'title' => $tooltip),
1119 * Check if query starts with image: prefix
1121 * @param $term String: the string to check
1124 protected function startsWithImage( $term ) {
1127 $p = explode( ':', $term );
1128 if( count( $p ) > 1 ) {
1129 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE
;
1135 * Check if query starts with all: prefix
1137 * @param $term String: the string to check
1140 protected function startsWithAll( $term ) {
1142 $allkeyword = wfMsgForContent('searchall');
1144 $p = explode( ':', $term );
1145 if( count( $p ) > 1 ) {
1146 return $p[0] == $allkeyword;
1154 * @return SearchEngine
1156 public function getSearchEngine() {
1157 if ( $this->searchEngine
=== null ) {
1158 $this->searchEngine
= SearchEngine
::create();
1160 return $this->searchEngine
;
1164 * Users of hook SpecialSearchSetupEngine can use this to
1165 * add more params to links to not lose selection when
1166 * user navigates search results.
1172 public function setExtraParam( $key, $value ) {
1173 $this->extraParams
[$key] = $value;