Rm old options from commandLine.inc days
[mediawiki.git] / includes / specials / SpecialSearch.php
blob351972feba98e569e711d1b5c67bfae088c2efef
1 <?php
2 /**
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
22 * @file
23 * @ingroup SpecialPage
26 /**
27 * implements Special:Search - Run text & title search and display the output
28 * @ingroup SpecialPage
30 class SpecialSearch extends SpecialPage {
31 /**
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.
37 * @var null|string
39 protected $profile;
41 /// Search engine
42 protected $searchEngine;
44 /// For links
45 protected $extraParams = array();
47 /// No idea, apparently used by some other classes
48 protected $mPrefix;
50 /**
51 * @var int
53 protected $limit, $offset;
55 /**
56 * @var array
58 protected $namespaces;
60 /**
61 * @var bool
63 protected $searchRedirects;
65 /**
66 * @var string
68 protected $didYouMeanHtml, $fulltext;
70 const NAMESPACES_CURRENT = 'sense';
72 public function __construct() {
73 parent::__construct( 'Search' );
76 /**
77 * Entry point
79 * @param $par String or null
81 public function execute( $par ) {
82 $this->setHeaders();
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 ) );
97 $this->load();
99 if ( $request->getVal( 'fulltext' )
100 || !is_null( $request->getVal( 'offset' ) )
101 || !is_null( $request->getVal( 'searchx' ) ) )
103 $this->showResults( $search );
104 } else {
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;
132 } else {
133 $this->namespaces = SearchEngine::userNamespaces( $user );
135 } elseif ( $profile === 'advanced' ) {
136 $this->namespaces = $nslist;
137 } else {
138 if ( isset( $profiles[$profile]['namespaces'] ) ) {
139 $this->namespaces = $profiles[$profile]['namespaces'];
140 } else {
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
172 return;
175 if( !is_null( $t ) ) {
176 $this->getOutput()->redirect( $t->getFullURL() );
177 return;
179 # No match, generate an edit URL
180 $t = Title::newFromText( $term );
181 if( !is_null( $t ) ) {
182 global $wgGoToEdit;
183 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
184 wfDebugLog( 'nogomatch', $t->getText(), false );
186 # If the feature is enabled, go straight to the edit page
187 if( $wgGoToEdit ) {
188 $this->getOutput()->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
189 return;
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 );
220 } else {
221 $out->addHTML(
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__ );
234 return;
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(
259 $didYouMeanParams,
260 $this->powerSearchOptions()
263 $suggestionSnippet = $textMatches->getSuggestionSnippet();
265 if( $suggestionSnippet == '' ) {
266 $suggestionSnippet = null;
269 $suggestLink = Linker::linkKnown(
270 $st,
271 $suggestionSnippet,
272 array(),
273 $stParams
276 $this->didYouMeanHtml = '<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>';
278 // start rendering the page
279 $out->addHtml(
280 Xml::openElement(
281 'form',
282 array(
283 'id' => ( $this->profile === 'advanced' ? 'powersearch' : 'search' ),
284 'method' => 'get',
285 'action' => $wgScript
289 $out->addHtml(
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__ );
303 return;
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__ );
313 return;
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
329 $totalRes = 0;
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'>" );
343 // prev/next links
344 if( $num || $this->offset ) {
345 // Show the create link ahead
346 $this->showCreateLink( $t );
347 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
348 SpecialPage::getTitleFor( 'Search' ),
349 wfArrayToCGI( $this->powerSearchOptions(), array( 'search' => $term ) ),
350 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
352 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
353 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
354 } else {
355 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
358 $out->parserOptions()->setEditSection( false );
359 if( $titleMatches ) {
360 if( $numTitleMatches > 0 ) {
361 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
362 $out->addHTML( $this->showMatches( $titleMatches ) );
364 $titleMatches->free();
366 if( $textMatches ) {
367 // output appropriate heading
368 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
369 // if no title matches the heading is redundant
370 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
371 } elseif( $totalRes == 0 ) {
372 # Don't show the 'no text matches' if we received title matches
373 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
375 // show interwiki results if any
376 if( $textMatches->hasInterwikiResults() ) {
377 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
379 // show results
380 if( $numTextMatches > 0 ) {
381 $out->addHTML( $this->showMatches( $textMatches ) );
384 $textMatches->free();
386 if( $num === 0 ) {
387 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
388 $this->showCreateLink( $t );
390 $out->addHtml( "</div>" );
392 if( $num || $this->offset ) {
393 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
395 wfProfileOut( __METHOD__ );
399 * @param $t Title
401 protected function showCreateLink( $t ) {
402 // show direct page/create link if applicable
403 // Check DBkey !== '' in case of fragment link only.
404 $messageName = null;
405 if( !is_null($t) && $t->getDBkey() !== '' ) {
406 if( $t->isKnown() ) {
407 $messageName = 'searchmenu-exists';
408 } elseif( $t->userCan( 'create' ) ) {
409 $messageName = 'searchmenu-new';
410 } else {
411 $messageName = 'searchmenu-new-nocreate';
414 if( $messageName ) {
415 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ) ) );
416 } else {
417 // preserve the paragraph for margins etc...
418 $this->getOutput()->addHtml( '<p></p>' );
423 * @param $term string
425 protected function setupPage( $term ) {
426 # Should advanced UI be used?
427 $this->searchAdvanced = ($this->profile === 'advanced');
428 $out = $this->getOutput();
429 if( strval( $term ) !== '' ) {
430 $out->setPageTitle( wfMsg( 'searchresults') );
431 $out->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term ) ) );
433 // add javascript specific to special:search
434 $out->addModules( 'mediawiki.special.search' );
438 * Extract "power search" namespace settings from the request object,
439 * returning a list of index numbers to search.
441 * @param $request WebRequest
442 * @return Array
444 protected function powerSearch( &$request ) {
445 $arr = array();
446 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
447 if( $request->getCheck( 'ns' . $ns ) ) {
448 $arr[] = $ns;
452 return $arr;
456 * Reconstruct the 'power search' options for links
458 * @return Array
460 protected function powerSearchOptions() {
461 $opt = array();
462 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
463 if( $this->profile !== 'advanced' ) {
464 $opt['profile'] = $this->profile;
465 } else {
466 foreach( $this->namespaces as $n ) {
467 $opt['ns' . $n] = 1;
470 return $opt + $this->extraParams;
474 * Show whole set of results
476 * @param $matches SearchResultSet
478 * @return string
480 protected function showMatches( &$matches ) {
481 global $wgContLang;
482 wfProfileIn( __METHOD__ );
484 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
486 $out = "";
487 $infoLine = $matches->getInfo();
488 if( !is_null($infoLine) ) {
489 $out .= "\n<!-- {$infoLine} -->\n";
491 $out .= "<ul class='mw-search-results'>\n";
492 while( $result = $matches->next() ) {
493 $out .= $this->showHit( $result, $terms );
495 $out .= "</ul>\n";
497 // convert the whole thing to desired language variant
498 $out = $wgContLang->convert( $out );
499 wfProfileOut( __METHOD__ );
500 return $out;
504 * Format a single hit result
506 * @param $result SearchResult
507 * @param $terms Array: terms to highlight
509 * @return string
511 protected function showHit( $result, $terms ) {
512 wfProfileIn( __METHOD__ );
514 if( $result->isBrokenTitle() ) {
515 wfProfileOut( __METHOD__ );
516 return "<!-- Broken link in search result -->\n";
519 $t = $result->getTitle();
521 $titleSnippet = $result->getTitleSnippet($terms);
523 if( $titleSnippet == '' )
524 $titleSnippet = null;
526 $link_t = clone $t;
528 wfRunHooks( 'ShowSearchHitTitle',
529 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
531 $link = Linker::linkKnown(
532 $link_t,
533 $titleSnippet
536 //If page content is not readable, just return the title.
537 //This is not quite safe, but better than showing excerpts from non-readable pages
538 //Note that hiding the entry entirely would screw up paging.
539 if( !$t->userCanRead() ) {
540 wfProfileOut( __METHOD__ );
541 return "<li>{$link}</li>\n";
544 // If the page doesn't *exist*... our search index is out of date.
545 // The least confusing at this point is to drop the result.
546 // You may get less results, but... oh well. :P
547 if( $result->isMissingRevision() ) {
548 wfProfileOut( __METHOD__ );
549 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
552 // format redirects / relevant sections
553 $redirectTitle = $result->getRedirectTitle();
554 $redirectText = $result->getRedirectSnippet($terms);
555 $sectionTitle = $result->getSectionTitle();
556 $sectionText = $result->getSectionSnippet($terms);
557 $redirect = '';
559 if( !is_null($redirectTitle) ) {
560 if( $redirectText == '' )
561 $redirectText = null;
563 $redirect = "<span class='searchalttitle'>" .
564 wfMsg(
565 'search-redirect',
566 Linker::linkKnown(
567 $redirectTitle,
568 $redirectText
571 "</span>";
574 $section = '';
576 if( !is_null($sectionTitle) ) {
577 if( $sectionText == '' )
578 $sectionText = null;
580 $section = "<span class='searchalttitle'>" .
581 wfMsg(
582 'search-section', Linker::linkKnown(
583 $sectionTitle,
584 $sectionText
587 "</span>";
590 // format text extract
591 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
593 $lang = $this->getLang();
595 // format score
596 if( is_null( $result->getScore() ) ) {
597 // Search engine doesn't report scoring info
598 $score = '';
599 } else {
600 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
601 $score = wfMsg( 'search-result-score', $lang->formatNum( $percent ) )
602 . ' - ';
605 // format description
606 $byteSize = $result->getByteSize();
607 $wordCount = $result->getWordCount();
608 $timestamp = $result->getTimestamp();
609 $size = wfMsgExt(
610 'search-result-size',
611 array( 'parsemag', 'escape' ),
612 $lang->formatSize( $byteSize ),
613 $lang->formatNum( $wordCount )
616 if( $t->getNamespace() == NS_CATEGORY ) {
617 $cat = Category::newFromTitle( $t );
618 $size = wfMsgExt(
619 'search-result-category-size',
620 array( 'parsemag', 'escape' ),
621 $lang->formatNum( $cat->getPageCount() ),
622 $lang->formatNum( $cat->getSubcatCount() ),
623 $lang->formatNum( $cat->getFileCount() )
627 $date = $lang->timeanddate( $timestamp );
629 // link to related articles if supported
630 $related = '';
631 if( $result->hasRelated() ) {
632 $st = SpecialPage::getTitleFor( 'Search' );
633 $stParams = array_merge(
634 $this->powerSearchOptions(),
635 array(
636 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
637 'fulltext' => wfMsg( 'search' )
641 $related = ' -- ' . Linker::linkKnown(
642 $st,
643 wfMsg('search-relatedarticle'),
644 array(),
645 $stParams
649 // Include a thumbnail for media files...
650 if( $t->getNamespace() == NS_FILE ) {
651 $img = wfFindFile( $t );
652 if( $img ) {
653 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
654 if( $thumb ) {
655 $desc = wfMsg( 'parentheses', $img->getShortDesc() );
656 wfProfileOut( __METHOD__ );
657 // Float doesn't seem to interact well with the bullets.
658 // Table messes up vertical alignment of the bullets.
659 // Bullets are therefore disabled (didn't look great anyway).
660 return "<li>" .
661 '<table class="searchResultImage">' .
662 '<tr>' .
663 '<td width="120" align="center" valign="top">' .
664 $thumb->toHtml( array( 'desc-link' => true ) ) .
665 '</td>' .
666 '<td valign="top">' .
667 $link .
668 $extract .
669 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
670 '</td>' .
671 '</tr>' .
672 '</table>' .
673 "</li>\n";
678 wfProfileOut( __METHOD__ );
679 return "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
680 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
681 "</li>\n";
686 * Show results from other wikis
688 * @param $matches SearchResultSet
689 * @param $query String
691 * @return string
693 protected function showInterwiki( &$matches, $query ) {
694 global $wgContLang;
695 wfProfileIn( __METHOD__ );
696 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
698 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
699 wfMsg('search-interwiki-caption')."</div>\n";
700 $out .= "<ul class='mw-search-iwresults'>\n";
702 // work out custom project captions
703 $customCaptions = array();
704 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
705 foreach($customLines as $line) {
706 $parts = explode(":",$line,2);
707 if(count($parts) == 2) // validate line
708 $customCaptions[$parts[0]] = $parts[1];
711 $prev = null;
712 while( $result = $matches->next() ) {
713 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
714 $prev = $result->getInterwikiPrefix();
716 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
717 $out .= "</ul></div>\n";
719 // convert the whole thing to desired language variant
720 $out = $wgContLang->convert( $out );
721 wfProfileOut( __METHOD__ );
722 return $out;
726 * Show single interwiki link
728 * @param $result SearchResult
729 * @param $lastInterwiki String
730 * @param $terms Array
731 * @param $query String
732 * @param $customCaptions Array: iw prefix -> caption
734 * @return string
736 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
737 wfProfileIn( __METHOD__ );
739 if( $result->isBrokenTitle() ) {
740 wfProfileOut( __METHOD__ );
741 return "<!-- Broken link in search result -->\n";
744 $t = $result->getTitle();
746 $titleSnippet = $result->getTitleSnippet($terms);
748 if( $titleSnippet == '' )
749 $titleSnippet = null;
751 $link = Linker::linkKnown(
753 $titleSnippet
756 // format redirect if any
757 $redirectTitle = $result->getRedirectTitle();
758 $redirectText = $result->getRedirectSnippet($terms);
759 $redirect = '';
760 if( !is_null($redirectTitle) ) {
761 if( $redirectText == '' )
762 $redirectText = null;
764 $redirect = "<span class='searchalttitle'>" .
765 wfMsg(
766 'search-redirect',
767 Linker::linkKnown(
768 $redirectTitle,
769 $redirectText
772 "</span>";
775 $out = "";
776 // display project name
777 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()) {
778 if( array_key_exists($t->getInterwiki(),$customCaptions) ) {
779 // captions from 'search-interwiki-custom'
780 $caption = $customCaptions[$t->getInterwiki()];
781 } else {
782 // default is to show the hostname of the other wiki which might suck
783 // if there are many wikis on one hostname
784 $parsed = wfParseUrl( $t->getFullURL() );
785 $caption = wfMsg('search-interwiki-default', $parsed['host']);
787 // "more results" link (special page stuff could be localized, but we might not know target lang)
788 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
789 $searchLink = Linker::linkKnown(
790 $searchTitle,
791 wfMsg('search-interwiki-more'),
792 array(),
793 array(
794 'search' => $query,
795 'fulltext' => 'Search'
798 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
799 {$searchLink}</span>{$caption}</div>\n<ul>";
802 $out .= "<li>{$link} {$redirect}</li>\n";
803 wfProfileOut( __METHOD__ );
804 return $out;
808 * @param $profile
809 * @param $term
810 * @return String
812 protected function getProfileForm( $profile, $term ) {
813 // Hidden stuff
814 $opts = array();
815 $opts['redirs'] = $this->searchRedirects;
816 $opts['profile'] = $this->profile;
818 if ( $profile === 'advanced' ) {
819 return $this->powerSearchBox( $term, $opts );
820 } else {
821 $form = '';
822 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
823 return $form;
828 * Generates the power search box at [[Special:Search]]
830 * @param $term String: search term
831 * @param $opts array
832 * @return String: HTML form
834 protected function powerSearchBox( $term, $opts ) {
835 // Groups namespaces into rows according to subject
836 $rows = array();
837 foreach( SearchEngine::searchableNamespaces() as $namespace => $name ) {
838 $subject = MWNamespace::getSubject( $namespace );
839 if( !array_key_exists( $subject, $rows ) ) {
840 $rows[$subject] = "";
842 $name = str_replace( '_', ' ', $name );
843 if( $name == '' ) {
844 $name = wfMsg( 'blanknamespace' );
846 $rows[$subject] .=
847 Xml::openElement(
848 'td', array( 'style' => 'white-space: nowrap' )
850 Xml::checkLabel(
851 $name,
852 "ns{$namespace}",
853 "mw-search-ns{$namespace}",
854 in_array( $namespace, $this->namespaces )
856 Xml::closeElement( 'td' );
858 $rows = array_values( $rows );
859 $numRows = count( $rows );
861 // Lays out namespaces in multiple floating two-column tables so they'll
862 // be arranged nicely while still accommodating different screen widths
863 $namespaceTables = '';
864 for( $i = 0; $i < $numRows; $i += 4 ) {
865 $namespaceTables .= Xml::openElement(
866 'table',
867 array( 'cellpadding' => 0, 'cellspacing' => 0, 'border' => 0 )
869 for( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
870 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
872 $namespaceTables .= Xml::closeElement( 'table' );
874 // Show redirects check only if backend supports it
875 $redirects = '';
876 if( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
877 $redirects =
878 Xml::checkLabel( wfMsg( 'powersearch-redir' ), 'redirs', 'redirs', $this->searchRedirects );
881 $hidden = '';
882 unset( $opts['redirs'] );
883 foreach( $opts as $key => $value ) {
884 $hidden .= Html::hidden( $key, $value );
886 // Return final output
887 return
888 Xml::openElement(
889 'fieldset',
890 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
892 Xml::element( 'legend', null, wfMsg('powersearch-legend') ) .
893 Xml::tags( 'h4', null, wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) ) .
894 Xml::tags(
895 'div',
896 array( 'id' => 'mw-search-togglebox' ),
897 Xml::label( wfMsg( 'powersearch-togglelabel' ), 'mw-search-togglelabel' ) .
898 Xml::element(
899 'input',
900 array(
901 'type'=>'button',
902 'id' => 'mw-search-toggleall',
903 'value' => wfMsg( 'powersearch-toggleall' )
906 Xml::element(
907 'input',
908 array(
909 'type'=>'button',
910 'id' => 'mw-search-togglenone',
911 'value' => wfMsg( 'powersearch-togglenone' )
915 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
916 $namespaceTables .
917 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
918 $redirects . $hidden .
919 Xml::closeElement( 'fieldset' );
923 * @return array
925 protected function getSearchProfiles() {
926 // Builds list of Search Types (profiles)
927 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
929 $profiles = array(
930 'default' => array(
931 'message' => 'searchprofile-articles',
932 'tooltip' => 'searchprofile-articles-tooltip',
933 'namespaces' => SearchEngine::defaultNamespaces(),
934 'namespace-messages' => SearchEngine::namespacesAsText(
935 SearchEngine::defaultNamespaces()
938 'images' => array(
939 'message' => 'searchprofile-images',
940 'tooltip' => 'searchprofile-images-tooltip',
941 'namespaces' => array( NS_FILE ),
943 'help' => array(
944 'message' => 'searchprofile-project',
945 'tooltip' => 'searchprofile-project-tooltip',
946 'namespaces' => SearchEngine::helpNamespaces(),
947 'namespace-messages' => SearchEngine::namespacesAsText(
948 SearchEngine::helpNamespaces()
951 'all' => array(
952 'message' => 'searchprofile-everything',
953 'tooltip' => 'searchprofile-everything-tooltip',
954 'namespaces' => $nsAllSet,
956 'advanced' => array(
957 'message' => 'searchprofile-advanced',
958 'tooltip' => 'searchprofile-advanced-tooltip',
959 'namespaces' => self::NAMESPACES_CURRENT,
963 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
965 foreach( $profiles as &$data ) {
966 if ( !is_array( $data['namespaces'] ) ) continue;
967 sort( $data['namespaces'] );
970 return $profiles;
974 * @param $term
975 * @param $resultsShown
976 * @param $totalNum
977 * @return string
979 protected function formHeader( $term, $resultsShown, $totalNum ) {
980 $out = Xml::openElement('div', array( 'class' => 'mw-search-formheader' ) );
982 $bareterm = $term;
983 if( $this->startsWithImage( $term ) ) {
984 // Deletes prefixes
985 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
988 $profiles = $this->getSearchProfiles();
989 $lang = $this->getLang();
991 // Outputs XML for Search Types
992 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
993 $out .= Xml::openElement( 'ul' );
994 foreach ( $profiles as $id => $profile ) {
995 if ( !isset( $profile['parameters'] ) ) {
996 $profile['parameters'] = array();
998 $profile['parameters']['profile'] = $id;
1000 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1001 $lang->commaList( $profile['namespace-messages'] ) : null;
1002 $out .= Xml::tags(
1003 'li',
1004 array(
1005 'class' => $this->profile === $id ? 'current' : 'normal'
1007 $this->makeSearchLink(
1008 $bareterm,
1009 array(),
1010 wfMsg( $profile['message'] ),
1011 wfMsg( $profile['tooltip'], $tooltipParam ),
1012 $profile['parameters']
1016 $out .= Xml::closeElement( 'ul' );
1017 $out .= Xml::closeElement('div') ;
1019 // Results-info
1020 if ( $resultsShown > 0 ) {
1021 if ( $totalNum > 0 ){
1022 $top = wfMsgExt( 'showingresultsheader', array( 'parseinline' ),
1023 $lang->formatNum( $this->offset + 1 ),
1024 $lang->formatNum( $this->offset + $resultsShown ),
1025 $lang->formatNum( $totalNum ),
1026 wfEscapeWikiText( $term ),
1027 $lang->formatNum( $resultsShown )
1029 } elseif ( $resultsShown >= $this->limit ) {
1030 $top = wfShowingResults( $this->offset, $this->limit );
1031 } else {
1032 $top = wfMsgExt( 'showingresultsnum', array( 'parseinline' ),
1033 $lang->formatNum( $this->limit ),
1034 $lang->formatNum( $this->offset + 1 ),
1035 $lang->formatNum( $resultsShown )
1038 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
1039 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
1043 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1044 $out .= Xml::closeElement('div');
1046 return $out;
1050 * @param $term string
1051 * @return string
1053 protected function shortDialog( $term ) {
1054 $out = Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
1055 // Term box
1056 $out .= Html::input( 'search', $term, 'search', array(
1057 'id' => $this->profile === 'advanced' ? 'powerSearchText' : 'searchText',
1058 'size' => '50',
1059 'autofocus'
1060 ) ) . "\n";
1061 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1062 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) ) . "\n";
1063 return $out . $this->didYouMeanHtml;
1067 * Make a search link with some target namespaces
1069 * @param $term String
1070 * @param $namespaces Array ignored
1071 * @param $label String: link's text
1072 * @param $tooltip String: link's tooltip
1073 * @param $params Array: query string parameters
1074 * @return String: HTML fragment
1076 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1077 $opt = $params;
1078 foreach( $namespaces as $n ) {
1079 $opt['ns' . $n] = 1;
1081 $opt['redirs'] = $this->searchRedirects;
1083 $stParams = array_merge(
1084 array(
1085 'search' => $term,
1086 'fulltext' => wfMsg( 'search' )
1088 $opt
1091 return Xml::element(
1092 'a',
1093 array(
1094 'href' => $this->getTitle()->getLocalURL( $stParams ),
1095 'title' => $tooltip),
1096 $label
1101 * Check if query starts with image: prefix
1103 * @param $term String: the string to check
1104 * @return Boolean
1106 protected function startsWithImage( $term ) {
1107 global $wgContLang;
1109 $p = explode( ':', $term );
1110 if( count( $p ) > 1 ) {
1111 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
1113 return false;
1117 * Check if query starts with all: prefix
1119 * @param $term String: the string to check
1120 * @return Boolean
1122 protected function startsWithAll( $term ) {
1124 $allkeyword = wfMsgForContent('searchall');
1126 $p = explode( ':', $term );
1127 if( count( $p ) > 1 ) {
1128 return $p[0] == $allkeyword;
1130 return false;
1134 * @since 1.18
1136 * @return SearchEngine
1138 public function getSearchEngine() {
1139 if ( $this->searchEngine === null ) {
1140 $this->searchEngine = SearchEngine::create();
1142 return $this->searchEngine;
1146 * Users of hook SpecialSearchSetupEngine can use this to
1147 * add more params to links to not lose selection when
1148 * user navigates search results.
1149 * @since 1.18
1151 * @param $key
1152 * @param $value
1154 public function setExtraParam( $key, $value ) {
1155 $this->extraParams[$key] = $value;