Changed how the search UI is rendered.
[mediawiki.git] / includes / specials / SpecialSearch.php
blobc781b4ec4a4d86c98a2f079dbb92581699adf85c
1 <?php
2 # Copyright (C) 2004 Brion Vibber <brion@pobox.com>
3 # http://www.mediawiki.org/
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
20 /**
21 * Run text & title search and display the output
22 * @file
23 * @ingroup SpecialPage
26 /**
27 * Entry point
29 * @param $par String: (default '')
31 function wfSpecialSearch( $par = '' ) {
32 global $wgRequest, $wgUser, $wgUseOldSearchUI;
33 // Strip underscores from title parameter; most of the time we'll want
34 // text form here. But don't strip underscores from actual text params!
35 $titleParam = str_replace( '_', ' ', $par );
36 // Fetch the search term
37 $search = str_replace( "\n", " ", $wgRequest->getText( 'search', $titleParam ) );
38 $class = $wgUseOldSearchUI ? 'SpecialSearchOld' : 'SpecialSearch';
39 $searchPage = new $class( $wgRequest, $wgUser );
40 if( $wgRequest->getVal( 'fulltext' )
41 || !is_null( $wgRequest->getVal( 'offset' ))
42 || !is_null( $wgRequest->getVal( 'searchx' )) )
44 $searchPage->showResults( $search );
45 } else {
46 $searchPage->goResult( $search );
50 /**
51 * implements Special:Search - Run text & title search and display the output
52 * @ingroup SpecialPage
54 class SpecialSearch {
56 /**
57 * Set up basic search parameters from the request and user settings.
58 * Typically you'll pass $wgRequest and $wgUser.
60 * @param WebRequest $request
61 * @param User $user
62 * @public
64 function __construct( &$request, &$user ) {
65 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
66 $this->mPrefix = $request->getVal('prefix', '');
67 # Extract requested namespaces
68 $this->namespaces = $this->powerSearch( $request );
69 if( empty( $this->namespaces ) ) {
70 $this->namespaces = SearchEngine::userNamespaces( $user );
72 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
73 $this->searchAdvanced = $request->getVal( 'advanced' );
74 $this->active = 'advanced';
75 $this->sk = $user->getSkin();
76 $this->didYouMeanHtml = ''; # html of did you mean... link
77 $this->fulltext = $request->getVal('fulltext');
80 /**
81 * If an exact title match can be found, jump straight ahead to it.
82 * @param string $term
84 public function goResult( $term ) {
85 global $wgOut;
86 $this->setupPage( $term );
87 # Try to go to page as entered.
88 $t = Title::newFromText( $term );
89 # If the string cannot be used to create a title
90 if( is_null( $t ) ) {
91 return $this->showResults( $term );
93 # If there's an exact or very near match, jump right there.
94 $t = SearchEngine::getNearMatch( $term );
95 if( !is_null( $t ) ) {
96 $wgOut->redirect( $t->getFullURL() );
97 return;
99 # No match, generate an edit URL
100 $t = Title::newFromText( $term );
101 if( !is_null( $t ) ) {
102 global $wgGoToEdit;
103 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
104 # If the feature is enabled, go straight to the edit page
105 if( $wgGoToEdit ) {
106 $wgOut->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
107 return;
110 return $this->showResults( $term );
114 * @param string $term
116 public function showResults( $term ) {
117 global $wgOut, $wgUser, $wgDisableTextSearch, $wgContLang, $wgScript;
118 wfProfileIn( __METHOD__ );
120 $sk = $wgUser->getSkin();
122 $this->searchEngine = SearchEngine::create();
123 $search =& $this->searchEngine;
124 $search->setLimitOffset( $this->limit, $this->offset );
125 $search->setNamespaces( $this->namespaces );
126 $search->showRedirects = $this->searchRedirects;
127 $search->prefix = $this->mPrefix;
128 $term = $search->transformSearchTerm($term);
130 $this->setupPage( $term );
132 if( $wgDisableTextSearch ) {
133 global $wgSearchForwardUrl;
134 if( $wgSearchForwardUrl ) {
135 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
136 $wgOut->redirect( $url );
137 wfProfileOut( __METHOD__ );
138 return;
140 global $wgInputEncoding;
141 $wgOut->addHTML(
142 Xml::openElement( 'fieldset' ) .
143 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
144 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
145 wfMsg( 'googlesearch',
146 htmlspecialchars( $term ),
147 htmlspecialchars( $wgInputEncoding ),
148 htmlspecialchars( wfMsg( 'searchbutton' ) )
150 Xml::closeElement( 'fieldset' )
152 wfProfileOut( __METHOD__ );
153 return;
156 $t = Title::newFromText( $term );
158 // fetch search results
159 $rewritten = $search->replacePrefixes($term);
161 $titleMatches = $search->searchTitle( $rewritten );
162 if( !($titleMatches instanceof SearchResultTooMany))
163 $textMatches = $search->searchText( $rewritten );
165 // did you mean... suggestions
166 if( $textMatches && $textMatches->hasSuggestion() ) {
167 $st = SpecialPage::getTitleFor( 'Search' );
169 # mirror Go/Search behaviour of original request ..
170 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
172 if($this->fulltext != NULL)
173 $didYouMeanParams['fulltext'] = $this->fulltext;
175 $stParams = array_merge(
176 $didYouMeanParams,
177 $this->powerSearchOptions()
180 $suggestionSnippet = $textMatches->getSuggestionSnippet();
182 if( $suggestionSnippet == '' )
183 $suggestionSnippet = null;
185 $suggestLink = $sk->linkKnown(
186 $st,
187 $suggestionSnippet,
188 array(),
189 $stParams
192 $this->didYouMeanHtml = '<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>';
194 // start rendering the page
195 $wgOut->addHtml(
196 Xml::openElement(
197 'form',
198 array(
199 'id' => ( $this->searchAdvanced ? 'powersearch' : 'search' ),
200 'method' => 'get',
201 'action' => $wgScript
205 $wgOut->addHtml(
206 Xml::openElement( 'table', array( 'border'=>0, 'cellpadding'=>0, 'cellspacing'=>0 ) ) .
207 Xml::openElement( 'tr' ) .
208 Xml::openElement( 'td' ) . "\n" .
209 $this->shortDialog( $term ) .
210 Xml::closeElement('td') .
211 Xml::closeElement('tr') .
212 Xml::closeElement('table')
215 // Sometimes the search engine knows there are too many hits
216 if( $titleMatches instanceof SearchResultTooMany ) {
217 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
218 wfProfileOut( __METHOD__ );
219 return;
222 $filePrefix = $wgContLang->getFormattedNsText(NS_FILE).':';
223 if( '' === trim( $term ) || $filePrefix === trim( $term ) ) {
224 $wgOut->addHTML( $this->searchFocus() );
225 $wgOut->addHTML( $this->formHeader($term, 0, 0));
226 if( $this->searchAdvanced ) {
227 $wgOut->addHTML( $this->powerSearchBox( $term ) );
229 // Empty query -- straight view of search form
230 wfProfileOut( __METHOD__ );
231 return;
234 // Get number of results
235 $titleMatchesNum = $titleMatches ? $titleMatches->numRows() : 0;
236 $textMatchesNum = $textMatches ? $textMatches->numRows() : 0;
237 // Total initial query matches (possible false positives)
238 $num = $titleMatchesNum + $textMatchesNum;
240 // Get total actual results (after second filtering, if any)
241 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
242 $titleMatches->getTotalHits() : $titleMatchesNum;
243 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
244 $textMatches->getTotalHits() : $textMatchesNum;
246 // get total number of results if backend can calculate it
247 $totalRes = 0;
248 if($titleMatches && !is_null( $titleMatches->getTotalHits() ) )
249 $totalRes += $titleMatches->getTotalHits();
250 if($textMatches && !is_null( $textMatches->getTotalHits() ))
251 $totalRes += $textMatches->getTotalHits();
253 // show number of results and current offset
254 $wgOut->addHTML( $this->formHeader($term, $num, $totalRes));
255 if( $this->searchAdvanced ) {
256 $wgOut->addHTML( $this->powerSearchBox( $term ) );
259 $wgOut->addHtml( Xml::closeElement( 'form' ) );
260 $wgOut->addHtml( "<div class='searchresults'>" );
262 // show direct page/create link
263 if( !is_null($t) && ($this->active=='default' || $this->active=='all') ) {
264 if( !$t->exists() ) {
265 $wgOut->addWikiMsg( 'searchmenu-new', wfEscapeWikiText( $t->getPrefixedText() ) );
266 } else {
267 $wgOut->addWikiMsg( 'searchmenu-exists', wfEscapeWikiText( $t->getPrefixedText() ) );
271 // prev/next links
272 if( $num || $this->offset ) {
273 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
274 SpecialPage::getTitleFor( 'Search' ),
275 wfArrayToCGI( $this->powerSearchOptions(), array( 'search' => $term ) ),
276 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
278 //$wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
279 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
280 } else {
281 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
284 if( $titleMatches ) {
285 if( $numTitleMatches > 0 ) {
286 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
287 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
289 $titleMatches->free();
291 if( $textMatches ) {
292 // output appropriate heading
293 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
294 // if no title matches the heading is redundant
295 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
296 } elseif( $totalRes == 0 ) {
297 # Don't show the 'no text matches' if we received title matches
298 # $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
300 // show interwiki results if any
301 if( $textMatches->hasInterwikiResults() ) {
302 $wgOut->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
304 // show results
305 if( $numTextMatches > 0 ) {
306 $wgOut->addHTML( $this->showMatches( $textMatches ) );
309 $textMatches->free();
311 if( $num === 0 ) {
312 $wgOut->addWikiMsg( 'search-nonefound' );
314 $wgOut->addHtml( "</div>" );
315 if( $num === 0 ) {
316 $wgOut->addHTML( $this->searchFocus() );
319 if( $num || $this->offset ) {
320 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
322 wfProfileOut( __METHOD__ );
328 protected function setupPage( $term ) {
329 global $wgOut;
330 // Figure out the active search profile header
331 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
332 if( $this->searchAdvanced )
333 $this->active = 'advanced';
334 else if( $this->namespaces === array(NS_FILE) || $this->startsWithImage( $term ) )
335 $this->active = 'images';
336 elseif( $this->namespaces === $nsAllSet || $this->startsWithAll( $term ) )
337 $this->active = 'all';
338 elseif( $this->namespaces === SearchEngine::defaultNamespaces() )
339 $this->active = 'default';
340 elseif( $this->namespaces === SearchEngine::helpNamespaces() )
341 $this->active = 'help';
342 else
343 $this->active = 'advanced';
344 # Should advanced UI be used?
345 $this->searchAdvanced = ($this->active === 'advanced');
346 if( !empty( $term ) ) {
347 $wgOut->setPageTitle( wfMsg( 'searchresults') );
348 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term ) ) );
350 $wgOut->setArticleRelated( false );
351 $wgOut->setRobotPolicy( 'noindex,nofollow' );
352 // add javascript specific to special:search
353 $wgOut->addScriptFile( 'search.js' );
357 * Extract "power search" namespace settings from the request object,
358 * returning a list of index numbers to search.
360 * @param WebRequest $request
361 * @return array
363 protected function powerSearch( &$request ) {
364 $arr = array();
365 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
366 if( $request->getCheck( 'ns' . $ns ) ) {
367 $arr[] = $ns;
370 return $arr;
374 * Reconstruct the 'power search' options for links
375 * @return array
377 protected function powerSearchOptions() {
378 $opt = array();
379 foreach( $this->namespaces as $n ) {
380 $opt['ns' . $n] = 1;
382 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
383 if( $this->searchAdvanced ) {
384 $opt['advanced'] = $this->searchAdvanced;
386 return $opt;
390 * Show whole set of results
392 * @param SearchResultSet $matches
394 protected function showMatches( &$matches ) {
395 global $wgContLang;
396 wfProfileIn( __METHOD__ );
398 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
400 $out = "";
401 $infoLine = $matches->getInfo();
402 if( !is_null($infoLine) ) {
403 $out .= "\n<!-- {$infoLine} -->\n";
405 $off = $this->offset + 1;
406 $out .= "<ul class='mw-search-results'>\n";
407 while( $result = $matches->next() ) {
408 $out .= $this->showHit( $result, $terms );
410 $out .= "</ul>\n";
412 // convert the whole thing to desired language variant
413 $out = $wgContLang->convert( $out );
414 wfProfileOut( __METHOD__ );
415 return $out;
419 * Format a single hit result
420 * @param SearchResult $result
421 * @param array $terms terms to highlight
423 protected function showHit( $result, $terms ) {
424 global $wgContLang, $wgLang, $wgUser;
425 wfProfileIn( __METHOD__ );
427 if( $result->isBrokenTitle() ) {
428 wfProfileOut( __METHOD__ );
429 return "<!-- Broken link in search result -->\n";
432 $sk = $wgUser->getSkin();
433 $t = $result->getTitle();
435 $titleSnippet = $result->getTitleSnippet($terms);
437 if( $titleSnippet == '' )
438 $titleSnippet = null;
440 $link = $this->sk->linkKnown(
442 $titleSnippet
445 //If page content is not readable, just return the title.
446 //This is not quite safe, but better than showing excerpts from non-readable pages
447 //Note that hiding the entry entirely would screw up paging.
448 if( !$t->userCanRead() ) {
449 wfProfileOut( __METHOD__ );
450 return "<li>{$link}</li>\n";
453 // If the page doesn't *exist*... our search index is out of date.
454 // The least confusing at this point is to drop the result.
455 // You may get less results, but... oh well. :P
456 if( $result->isMissingRevision() ) {
457 wfProfileOut( __METHOD__ );
458 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
461 // format redirects / relevant sections
462 $redirectTitle = $result->getRedirectTitle();
463 $redirectText = $result->getRedirectSnippet($terms);
464 $sectionTitle = $result->getSectionTitle();
465 $sectionText = $result->getSectionSnippet($terms);
466 $redirect = '';
468 if( !is_null($redirectTitle) ) {
469 if( $redirectText == '' )
470 $redirectText = null;
472 $redirect = "<span class='searchalttitle'>" .
473 wfMsg(
474 'search-redirect',
475 $this->sk->linkKnown(
476 $redirectTitle,
477 $redirectText
480 "</span>";
483 $section = '';
486 if( !is_null($sectionTitle) ) {
487 if( $sectionText == '' )
488 $sectionText = null;
490 $section = "<span class='searchalttitle'>" .
491 wfMsg(
492 'search-section', $this->sk->linkKnown(
493 $sectionTitle,
494 $sectionText
497 "</span>";
500 // format text extract
501 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
503 // format score
504 if( is_null( $result->getScore() ) ) {
505 // Search engine doesn't report scoring info
506 $score = '';
507 } else {
508 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
509 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
510 . ' - ';
513 // format description
514 $byteSize = $result->getByteSize();
515 $wordCount = $result->getWordCount();
516 $timestamp = $result->getTimestamp();
517 $size = wfMsgExt(
518 'search-result-size',
519 array( 'parsemag', 'escape' ),
520 $this->sk->formatSize( $byteSize ),
521 $wordCount
523 $date = $wgLang->timeanddate( $timestamp );
525 // link to related articles if supported
526 $related = '';
527 if( $result->hasRelated() ) {
528 $st = SpecialPage::getTitleFor( 'Search' );
529 $stParams = array_merge(
530 $this->powerSearchOptions(),
531 array(
532 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
533 'fulltext' => wfMsg( 'search' )
537 $related = ' -- ' . $sk->linkKnown(
538 $st,
539 wfMsg('search-relatedarticle'),
540 array(),
541 $stParams
545 // Include a thumbnail for media files...
546 if( $t->getNamespace() == NS_FILE ) {
547 $img = wfFindFile( $t );
548 if( $img ) {
549 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
550 if( $thumb ) {
551 $desc = $img->getShortDesc();
552 wfProfileOut( __METHOD__ );
553 // Float doesn't seem to interact well with the bullets.
554 // Table messes up vertical alignment of the bullets.
555 // Bullets are therefore disabled (didn't look great anyway).
556 return "<li>" .
557 '<table class="searchResultImage">' .
558 '<tr>' .
559 '<td width="120" align="center" valign="top">' .
560 $thumb->toHtml( array( 'desc-link' => true ) ) .
561 '</td>' .
562 '<td valign="top">' .
563 $link .
564 $extract .
565 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
566 '</td>' .
567 '</tr>' .
568 '</table>' .
569 "</li>\n";
574 wfProfileOut( __METHOD__ );
575 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
576 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
577 "</li>\n";
582 * Show results from other wikis
584 * @param SearchResultSet $matches
586 protected function showInterwiki( &$matches, $query ) {
587 global $wgContLang;
588 wfProfileIn( __METHOD__ );
589 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
591 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
592 wfMsg('search-interwiki-caption')."</div>\n";
593 $off = $this->offset + 1;
594 $out .= "<ul class='mw-search-iwresults'>\n";
596 // work out custom project captions
597 $customCaptions = array();
598 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
599 foreach($customLines as $line) {
600 $parts = explode(":",$line,2);
601 if(count($parts) == 2) // validate line
602 $customCaptions[$parts[0]] = $parts[1];
605 $prev = null;
606 while( $result = $matches->next() ) {
607 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
608 $prev = $result->getInterwikiPrefix();
610 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
611 $out .= "</ul></div>\n";
613 // convert the whole thing to desired language variant
614 $out = $wgContLang->convert( $out );
615 wfProfileOut( __METHOD__ );
616 return $out;
620 * Show single interwiki link
622 * @param SearchResult $result
623 * @param string $lastInterwiki
624 * @param array $terms
625 * @param string $query
626 * @param array $customCaptions iw prefix -> caption
628 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
629 wfProfileIn( __METHOD__ );
630 global $wgContLang, $wgLang;
632 if( $result->isBrokenTitle() ) {
633 wfProfileOut( __METHOD__ );
634 return "<!-- Broken link in search result -->\n";
637 $t = $result->getTitle();
639 $titleSnippet = $result->getTitleSnippet($terms);
641 if( $titleSnippet == '' )
642 $titleSnippet = null;
644 $link = $this->sk->linkKnown(
646 $titleSnippet
649 // format redirect if any
650 $redirectTitle = $result->getRedirectTitle();
651 $redirectText = $result->getRedirectSnippet($terms);
652 $redirect = '';
653 if( !is_null($redirectTitle) ) {
654 if( $redirectText == '' )
655 $redirectText = null;
657 $redirect = "<span class='searchalttitle'>" .
658 wfMsg(
659 'search-redirect',
660 $this->sk->linkKnown(
661 $redirectTitle,
662 $redirectText
665 "</span>";
668 $out = "";
669 // display project name
670 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()) {
671 if( key_exists($t->getInterwiki(),$customCaptions) )
672 // captions from 'search-interwiki-custom'
673 $caption = $customCaptions[$t->getInterwiki()];
674 else{
675 // default is to show the hostname of the other wiki which might suck
676 // if there are many wikis on one hostname
677 $parsed = parse_url($t->getFullURL());
678 $caption = wfMsg('search-interwiki-default', $parsed['host']);
680 // "more results" link (special page stuff could be localized, but we might not know target lang)
681 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
682 $searchLink = $this->sk->linkKnown(
683 $searchTitle,
684 wfMsg('search-interwiki-more'),
685 array(),
686 array(
687 'search' => $query,
688 'fulltext' => 'Search'
691 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
692 {$searchLink}</span>{$caption}</div>\n<ul>";
695 $out .= "<li>{$link} {$redirect}</li>\n";
696 wfProfileOut( __METHOD__ );
697 return $out;
702 * Generates the power search box at bottom of [[Special:Search]]
703 * @param $term string: search term
704 * @return $out string: HTML form
706 protected function powerSearchBox( $term ) {
707 global $wgScript, $wgContLang;
709 // Groups namespaces into rows according to subject
710 $rows = array();
711 foreach( SearchEngine::searchableNamespaces() as $namespace => $name ) {
712 $subject = MWNamespace::getSubject( $namespace );
713 if( !array_key_exists( $subject, $rows ) ) {
714 $rows[$subject] = "";
716 $name = str_replace( '_', ' ', $name );
717 if( $name == '' ) {
718 $name = wfMsg( 'blanknamespace' );
720 $rows[$subject] .=
721 Xml::openElement(
722 'td', array( 'style' => 'white-space: nowrap' )
724 Xml::checkLabel(
725 $name,
726 "ns{$namespace}",
727 "mw-search-ns{$namespace}",
728 in_array( $namespace, $this->namespaces )
730 Xml::closeElement( 'td' );
732 $rows = array_values( $rows );
733 $numRows = count( $rows );
735 // Lays out namespaces in multiple floating two-column tables so they'll
736 // be arranged nicely while still accommodating different screen widths
737 $namespaceTables = '';
738 for( $i = 0; $i < $numRows; $i += 4 ) {
739 $namespaceTables .= Xml::openElement(
740 'table',
741 array( 'cellpadding' => 0, 'cellspacing' => 0, 'border' => 0 )
743 for( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
744 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
746 $namespaceTables .= Xml::closeElement( 'table' );
748 // Show redirects check only if backend supports it
749 $redirects = '';
750 if( $this->searchEngine->acceptListRedirects() ) {
751 $redirects =
752 Xml::check(
753 'redirs', $this->searchRedirects, array( 'value' => '1', 'id' => 'redirs' )
755 ' ' .
756 Xml::label( wfMsg( 'powersearch-redir' ), 'redirs' );
758 // Return final output
759 return
760 Xml::openElement(
761 'fieldset',
762 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
764 Xml::element( 'legend', null, wfMsg('powersearch-legend') ) .
765 Xml::element( 'h4', null, wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) ) .
766 Xml::tags(
767 'div',
768 array( 'id' => 'mw-search-togglebox' ),
769 Xml::label( wfMsg( 'powersearch-togglelabel' ), 'mw-search-togglelabel' ) .
770 Xml::element(
771 'input',
772 array(
773 'type'=>'button',
774 'id' => 'mw-search-toggleall',
775 'onclick' => 'mwToggleSearchCheckboxes("all");',
776 'value' => wfMsg( 'powersearch-toggleall' )
779 Xml::element(
780 'input',
781 array(
782 'type'=>'button',
783 'id' => 'mw-search-togglenone',
784 'onclick' => 'mwToggleSearchCheckboxes("none");',
785 'value' => wfMsg( 'powersearch-togglenone'
790 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
791 $namespaceTables .
792 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
793 $redirects .
794 Xml::hidden( 'title', SpecialPage::getTitleFor( 'Search' )->getPrefixedText() ) .
795 Xml::hidden( 'advanced', $this->searchAdvanced ) .
796 Xml::hidden( 'fulltext', 'Advanced search' ) .
797 Xml::closeElement( 'fieldset' );
800 protected function searchFocus() {
801 global $wgJsMimeType;
802 return "<script type=\"$wgJsMimeType\">" .
803 "hookEvent(\"load\", function() {" .
804 "document.getElementById('searchText').focus();" .
805 "});" .
806 "</script>";
809 protected function formHeader( $term, $resultsShown, $totalNum ) {
810 global $wgContLang, $wgCanonicalNamespaceNames, $wgLang;
812 $out = Xml::openElement('div', array( 'class' => 'mw-search-formheader' ) );
814 $bareterm = $term;
815 if( $this->startsWithImage( $term ) ) {
816 // Deletes prefixes
817 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
819 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
821 // Builds list of Search Types (profiles)
822 $profiles = array(
823 'default' => array(
824 'message' => 'searchprofile-articles',
825 'tooltip' => 'searchprofile-articles-tooltip',
826 'namespaces' => SearchEngine::defaultNamespaces(),
827 'namespace-messages' => SearchEngine::namespacesAsText(
828 SearchEngine::defaultNamespaces()
831 'images' => array(
832 'message' => 'searchprofile-images',
833 'tooltip' => 'searchprofile-images-tooltip',
834 'namespaces' => array( NS_FILE ),
836 'help' => array(
837 'message' => 'searchprofile-project',
838 'tooltip' => 'searchprofile-project-tooltip',
839 'namespaces' => SearchEngine::helpNamespaces(),
840 'namespace-messages' => SearchEngine::namespacesAsText(
841 SearchEngine::helpNamespaces()
844 'all' => array(
845 'message' => 'searchprofile-everything',
846 'tooltip' => 'searchprofile-everything-tooltip',
847 'namespaces' => $nsAllSet,
849 'advanced' => array(
850 'message' => 'searchprofile-advanced',
851 'tooltip' => 'searchprofile-advanced-tooltip',
852 'namespaces' => $this->namespaces,
853 'parameters' => array( 'advanced' => 1 ),
856 // Outputs XML for Search Types
857 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
858 $out .= Xml::openElement( 'ul' );
859 foreach ( $profiles as $id => $profile ) {
860 $tooltipParam = isset( $profile['namespace-messages'] ) ?
861 $wgLang->commaList( $profile['namespace-messages'] ) : null;
862 $out .= Xml::tags(
863 'li',
864 array(
865 'class' => $this->active == $id ? 'current' : 'normal'
867 $this->makeSearchLink(
868 $bareterm,
869 $profile['namespaces'],
870 wfMsg( $profile['message'] ),
871 wfMsg( $profile['tooltip'], $tooltipParam ),
872 isset( $profile['parameters'] ) ? $profile['parameters'] : array()
876 $out .= Xml::closeElement( 'ul' );
877 $out .= Xml::closeElement('div') ;
879 // Results-info
880 if ( $resultsShown > 0 ) {
881 if ( $totalNum > 0 ){
882 $top = wfMsgExt('showingresultsheader', array( 'parseinline' ),
883 $this->offset+1, $this->offset+$resultsShown, $totalNum, $term, $resultsShown );
884 } elseif ( $resultsShown >= $this->limit ) {
885 $top = wfShowingResults( $this->offset, $this->limit );
886 } else {
887 $top = wfShowingResultsNum( $this->offset, $this->limit, $resultsShown );
889 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
890 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
894 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
895 $out .= Xml::closeElement('div');
897 // Adds hidden namespace fields
898 if ( !$this->searchAdvanced ) {
899 foreach( $this->namespaces as $ns ) {
900 $out .= Xml::hidden( "ns{$ns}", '1' );
904 return $out;
907 protected function shortDialog( $term ) {
908 $searchTitle = SpecialPage::getTitleFor( 'Search' );
909 $searchable = SearchEngine::searchableNamespaces();
910 $out .= Xml::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n";
911 // Keep redirect setting
912 $out .= Xml::hidden( "redirs", (int)$this->searchRedirects );
913 // Term box
914 $out .= Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'searchText' ) ) . "\n";
915 $out .= Xml::hidden( 'fulltext', 'Search' );
916 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) );
917 return $out . $this->didYouMeanHtml;
920 /** Make a search link with some target namespaces */
921 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params=array() ) {
922 $opt = $params;
923 foreach( $namespaces as $n ) {
924 $opt['ns' . $n] = 1;
926 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
928 $st = SpecialPage::getTitleFor( 'Search' );
929 $stParams = array_merge(
930 array(
931 'search' => $term,
932 'fulltext' => wfMsg( 'search' )
934 $opt
937 return Xml::element(
938 'a',
939 array(
940 'href' => $st->getLocalURL( $stParams ),
941 'title' => $tooltip,
942 'onmousedown' => 'mwSearchHeaderClick(this);',
943 'onkeydown' => 'mwSearchHeaderClick(this);'),
944 $label
948 /** Check if query starts with image: prefix */
949 protected function startsWithImage( $term ) {
950 global $wgContLang;
952 $p = explode( ':', $term );
953 if( count( $p ) > 1 ) {
954 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
956 return false;
959 /** Check if query starts with all: prefix */
960 protected function startsWithAll( $term ) {
962 $allkeyword = wfMsgForContent('searchall');
964 $p = explode( ':', $term );
965 if( count( $p ) > 1 ) {
966 return $p[0] == $allkeyword;
968 return false;
973 * implements Special:Search - Run text & title search and display the output
974 * @ingroup SpecialPage
976 class SpecialSearchOld {
979 * Set up basic search parameters from the request and user settings.
980 * Typically you'll pass $wgRequest and $wgUser.
982 * @param WebRequest $request
983 * @param User $user
984 * @public
986 function __construct( &$request, &$user ) {
987 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
988 $this->mPrefix = $request->getVal('prefix', '');
989 $this->namespaces = $this->powerSearch( $request );
990 if( empty( $this->namespaces ) ) {
991 $this->namespaces = SearchEngine::userNamespaces( $user );
994 $this->searchRedirects = $request->getcheck( 'redirs' ) ? true : false;
995 $this->fulltext = $request->getVal('fulltext');
999 * If an exact title match can be found, jump straight ahead to it.
1000 * @param string $term
1001 * @public
1003 function goResult( $term ) {
1004 global $wgOut;
1005 global $wgGoToEdit;
1007 $this->setupPage( $term );
1009 # Try to go to page as entered.
1010 $t = Title::newFromText( $term );
1012 # If the string cannot be used to create a title
1013 if( is_null( $t ) ){
1014 return $this->showResults( $term );
1017 # If there's an exact or very near match, jump right there.
1018 $t = SearchEngine::getNearMatch( $term );
1019 if( !is_null( $t ) ) {
1020 $wgOut->redirect( $t->getFullURL() );
1021 return;
1024 # No match, generate an edit URL
1025 $t = Title::newFromText( $term );
1026 if( ! is_null( $t ) ) {
1027 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
1028 # If the feature is enabled, go straight to the edit page
1029 if ( $wgGoToEdit ) {
1030 $wgOut->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
1031 return;
1035 $extra = $wgOut->parse( '=='.wfMsgNoTrans( 'notitlematches' )."==\n" );
1036 if( $t->quickUserCan( 'create' ) && $t->quickUserCan( 'edit' ) ) {
1037 $extra .= wfMsgExt( 'noexactmatch', 'parse', wfEscapeWikiText( $term ) );
1038 } else {
1039 $extra .= wfMsgExt( 'noexactmatch-nocreate', 'parse', wfEscapeWikiText( $term ) );
1042 $this->showResults( $term, $extra );
1046 * @param string $term
1047 * @param string $extra Extra HTML to add after "did you mean"
1049 public function showResults( $term, $extra = '' ) {
1050 wfProfileIn( __METHOD__ );
1051 global $wgOut, $wgUser;
1052 $sk = $wgUser->getSkin();
1054 $search = SearchEngine::create();
1055 $search->setLimitOffset( $this->limit, $this->offset );
1056 $search->setNamespaces( $this->namespaces );
1057 $search->showRedirects = $this->searchRedirects;
1058 $search->prefix = $this->mPrefix;
1059 $term = $search->transformSearchTerm($term);
1061 $this->setupPage( $term );
1063 $rewritten = $search->replacePrefixes($term);
1064 $titleMatches = $search->searchTitle( $rewritten );
1065 $textMatches = $search->searchText( $rewritten );
1067 // did you mean... suggestions
1068 if($textMatches && $textMatches->hasSuggestion()){
1069 $st = SpecialPage::getTitleFor( 'Search' );
1071 # mirror Go/Search behaviour of original request
1072 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
1073 if($this->fulltext != NULL)
1074 $didYouMeanParams['fulltext'] = $this->fulltext;
1075 $stParams = array_merge(
1076 $didYouMeanParams,
1077 $this->powerSearchOptions()
1080 $suggestionSnippet = $textMatches->getSuggestionSnippet();
1082 if( $suggestionSnippet )
1083 $suggestionSnippet = null;
1085 $suggestLink = $sk->linkKnown(
1086 $st,
1087 $suggestionSnippet,
1088 array(),
1089 $stParams
1092 $wgOut->addHTML('<div class="searchdidyoumean">'.wfMsg('search-suggest',$suggestLink).'</div>');
1095 $wgOut->addHTML( $extra );
1097 $wgOut->wrapWikiMsg( "<div class='mw-searchresult'>\n$1</div>", 'searchresulttext' );
1099 if( '' === trim( $term ) ) {
1100 // Empty query -- straight view of search form
1101 $wgOut->setSubtitle( '' );
1102 $wgOut->addHTML( $this->powerSearchBox( $term ) );
1103 $wgOut->addHTML( $this->powerSearchFocus() );
1104 wfProfileOut( __METHOD__ );
1105 return;
1108 global $wgDisableTextSearch;
1109 if ( $wgDisableTextSearch ) {
1110 global $wgSearchForwardUrl;
1111 if( $wgSearchForwardUrl ) {
1112 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
1113 $wgOut->redirect( $url );
1114 wfProfileOut( __METHOD__ );
1115 return;
1117 global $wgInputEncoding;
1118 $wgOut->addHTML(
1119 Xml::openElement( 'fieldset' ) .
1120 Xml::element( 'legend', null, wfMsg( 'search-external' ) ) .
1121 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), wfMsg( 'searchdisabled' ) ) .
1122 wfMsg( 'googlesearch',
1123 htmlspecialchars( $term ),
1124 htmlspecialchars( $wgInputEncoding ),
1125 htmlspecialchars( wfMsg( 'searchbutton' ) )
1127 Xml::closeElement( 'fieldset' )
1129 wfProfileOut( __METHOD__ );
1130 return;
1133 $wgOut->addHTML( $this->shortDialog( $term ) );
1135 // Sometimes the search engine knows there are too many hits
1136 if ($titleMatches instanceof SearchResultTooMany) {
1137 $wgOut->addWikiText( '==' . wfMsg( 'toomanymatches' ) . "==\n" );
1138 $wgOut->addHTML( $this->powerSearchBox( $term ) );
1139 $wgOut->addHTML( $this->powerSearchFocus() );
1140 wfProfileOut( __METHOD__ );
1141 return;
1144 // show number of results
1145 $num = ( $titleMatches ? $titleMatches->numRows() : 0 )
1146 + ( $textMatches ? $textMatches->numRows() : 0);
1147 $totalNum = 0;
1148 if($titleMatches && !is_null($titleMatches->getTotalHits()))
1149 $totalNum += $titleMatches->getTotalHits();
1150 if($textMatches && !is_null($textMatches->getTotalHits()))
1151 $totalNum += $textMatches->getTotalHits();
1152 if ( $num > 0 ) {
1153 if ( $totalNum > 0 ){
1154 $top = wfMsgExt('showingresultstotal', array( 'parseinline' ),
1155 $this->offset+1, $this->offset+$num, $totalNum, $num );
1156 } elseif ( $num >= $this->limit ) {
1157 $top = wfShowingResults( $this->offset, $this->limit );
1158 } else {
1159 $top = wfShowingResultsNum( $this->offset, $this->limit, $num );
1161 $wgOut->addHTML( "<p class='mw-search-numberresults'>{$top}</p>\n" );
1164 // prev/next links
1165 if( $num || $this->offset ) {
1166 $prevnext = wfViewPrevNext( $this->offset, $this->limit,
1167 SpecialPage::getTitleFor( 'Search' ),
1168 wfArrayToCGI(
1169 $this->powerSearchOptions(),
1170 array( 'search' => $term ) ),
1171 ($num < $this->limit) );
1172 $wgOut->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
1173 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
1174 } else {
1175 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
1178 if( $titleMatches ) {
1179 if( $titleMatches->numRows() ) {
1180 $wgOut->wrapWikiMsg( "==$1==\n", 'titlematches' );
1181 $wgOut->addHTML( $this->showMatches( $titleMatches ) );
1183 $titleMatches->free();
1186 if( $textMatches ) {
1187 // output appropriate heading
1188 if( $textMatches->numRows() ) {
1189 if($titleMatches)
1190 $wgOut->wrapWikiMsg( "==$1==\n", 'textmatches' );
1191 else // if no title matches the heading is redundant
1192 $wgOut->addHTML("<hr/>");
1193 } elseif( $num == 0 ) {
1194 # Don't show the 'no text matches' if we received title matches
1195 $wgOut->wrapWikiMsg( "==$1==\n", 'notextmatches' );
1197 // show interwiki results if any
1198 if( $textMatches->hasInterwikiResults() )
1199 $wgOut->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ));
1200 // show results
1201 if( $textMatches->numRows() )
1202 $wgOut->addHTML( $this->showMatches( $textMatches ) );
1204 $textMatches->free();
1207 if ( $num == 0 ) {
1208 $wgOut->addWikiMsg( 'nonefound' );
1210 if( $num || $this->offset ) {
1211 $wgOut->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
1213 $wgOut->addHTML( $this->powerSearchBox( $term ) );
1214 wfProfileOut( __METHOD__ );
1217 #------------------------------------------------------------------
1218 # Private methods below this line
1223 function setupPage( $term ) {
1224 global $wgOut;
1225 if( !empty( $term ) ){
1226 $wgOut->setPageTitle( wfMsg( 'searchresults') );
1227 $wgOut->setHTMLTitle( wfMsg( 'pagetitle', wfMsg( 'searchresults-title', $term) ) );
1229 $subtitlemsg = ( Title::newFromText( $term ) ? 'searchsubtitle' : 'searchsubtitleinvalid' );
1230 $wgOut->setSubtitle( $wgOut->parse( wfMsg( $subtitlemsg, wfEscapeWikiText($term) ) ) );
1231 $wgOut->setArticleRelated( false );
1232 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1236 * Extract "power search" namespace settings from the request object,
1237 * returning a list of index numbers to search.
1239 * @param WebRequest $request
1240 * @return array
1241 * @private
1243 function powerSearch( &$request ) {
1244 $arr = array();
1245 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
1246 if( $request->getCheck( 'ns' . $ns ) ) {
1247 $arr[] = $ns;
1250 return $arr;
1254 * Reconstruct the 'power search' options for links
1255 * @return array
1256 * @private
1258 function powerSearchOptions() {
1259 $opt = array();
1260 foreach( $this->namespaces as $n ) {
1261 $opt['ns' . $n] = 1;
1263 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
1264 return $opt;
1268 * Show whole set of results
1270 * @param SearchResultSet $matches
1272 function showMatches( &$matches ) {
1273 wfProfileIn( __METHOD__ );
1275 global $wgContLang;
1276 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
1278 $out = "";
1280 $infoLine = $matches->getInfo();
1281 if( !is_null($infoLine) )
1282 $out .= "\n<!-- {$infoLine} -->\n";
1285 $off = $this->offset + 1;
1286 $out .= "<ul class='mw-search-results'>\n";
1288 while( $result = $matches->next() ) {
1289 $out .= $this->showHit( $result, $terms );
1291 $out .= "</ul>\n";
1293 // convert the whole thing to desired language variant
1294 global $wgContLang;
1295 $out = $wgContLang->convert( $out );
1296 wfProfileOut( __METHOD__ );
1297 return $out;
1301 * Format a single hit result
1302 * @param SearchResult $result
1303 * @param array $terms terms to highlight
1305 function showHit( $result, $terms ) {
1306 wfProfileIn( __METHOD__ );
1307 global $wgUser, $wgContLang, $wgLang;
1309 if( $result->isBrokenTitle() ) {
1310 wfProfileOut( __METHOD__ );
1311 return "<!-- Broken link in search result -->\n";
1314 $t = $result->getTitle();
1315 $sk = $wgUser->getSkin();
1317 $titleSnippet = $result->getTitleSnippet($terms);
1319 if( $titleSnippet == '' )
1320 $titleSnippet = null;
1322 $link = $sk->linkKnown(
1324 $titleSnippet
1327 //If page content is not readable, just return the title.
1328 //This is not quite safe, but better than showing excerpts from non-readable pages
1329 //Note that hiding the entry entirely would screw up paging.
1330 if (!$t->userCanRead()) {
1331 wfProfileOut( __METHOD__ );
1332 return "<li>{$link}</li>\n";
1335 // If the page doesn't *exist*... our search index is out of date.
1336 // The least confusing at this point is to drop the result.
1337 // You may get less results, but... oh well. :P
1338 if( $result->isMissingRevision() ) {
1339 wfProfileOut( __METHOD__ );
1340 return "<!-- missing page " .
1341 htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
1344 // format redirects / relevant sections
1345 $redirectTitle = $result->getRedirectTitle();
1346 $redirectText = $result->getRedirectSnippet($terms);
1347 $sectionTitle = $result->getSectionTitle();
1348 $sectionText = $result->getSectionSnippet($terms);
1349 $redirect = '';
1350 if( !is_null($redirectTitle) ) {
1351 if( $redirectText == '' )
1352 $redirectText = null;
1354 $redirect = "<span class='searchalttitle'>" .
1355 wfMsg(
1356 'search-redirect',
1357 $sk->linkKnown(
1358 $redirectTitle,
1359 $redirectText
1362 "</span>";
1365 $section = '';
1367 if( !is_null($sectionTitle) ) {
1368 if( $sectionText == '' )
1369 $sectionText = null;
1371 $section = "<span class='searchalttitle'>" .
1372 wfMsg(
1373 'search-section',
1374 $sk->linkKnown(
1375 $sectionTitle,
1376 $sectionText
1379 "</span>";
1382 // format text extract
1383 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
1385 // format score
1386 if( is_null( $result->getScore() ) ) {
1387 // Search engine doesn't report scoring info
1388 $score = '';
1389 } else {
1390 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
1391 $score = wfMsg( 'search-result-score', $wgLang->formatNum( $percent ) )
1392 . ' - ';
1395 // format description
1396 $byteSize = $result->getByteSize();
1397 $wordCount = $result->getWordCount();
1398 $timestamp = $result->getTimestamp();
1399 $size = wfMsgExt( 'search-result-size', array( 'parsemag', 'escape' ),
1400 $sk->formatSize( $byteSize ),
1401 $wordCount );
1402 $date = $wgLang->timeanddate( $timestamp );
1404 // link to related articles if supported
1405 $related = '';
1406 if( $result->hasRelated() ){
1407 $st = SpecialPage::getTitleFor( 'Search' );
1408 $stParams = array_merge(
1409 $this->powerSearchOptions(),
1410 array(
1411 'search' => wfMsgForContent( 'searchrelated' ) . ':' . $t->getPrefixedText(),
1412 'fulltext' => wfMsg( 'search' )
1416 $related = ' -- ' . $sk->linkKnown(
1417 $st,
1418 wfMsg('search-relatedarticle'),
1419 array(),
1420 $stParams
1424 // Include a thumbnail for media files...
1425 if( $t->getNamespace() == NS_FILE ) {
1426 $img = wfFindFile( $t );
1427 if( $img ) {
1428 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
1429 if( $thumb ) {
1430 $desc = $img->getShortDesc();
1431 wfProfileOut( __METHOD__ );
1432 // Ugly table. :D
1433 // Float doesn't seem to interact well with the bullets.
1434 // Table messes up vertical alignment of the bullet, but I'm
1435 // not sure what more I can do about that. :(
1436 return "<li>" .
1437 '<table class="searchResultImage">' .
1438 '<tr>' .
1439 '<td width="120" align="center">' .
1440 $thumb->toHtml( array( 'desc-link' => true ) ) .
1441 '</td>' .
1442 '<td valign="top">' .
1443 $link .
1444 $extract .
1445 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
1446 '</td>' .
1447 '</tr>' .
1448 '</table>' .
1449 "</li>\n";
1454 wfProfileOut( __METHOD__ );
1455 return "<li>{$link} {$redirect} {$section} {$extract}\n" .
1456 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
1457 "</li>\n";
1462 * Show results from other wikis
1464 * @param SearchResultSet $matches
1466 function showInterwiki( &$matches, $query ) {
1467 wfProfileIn( __METHOD__ );
1469 global $wgContLang;
1470 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
1472 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".wfMsg('search-interwiki-caption')."</div>\n";
1473 $off = $this->offset + 1;
1474 $out .= "<ul start='{$off}' class='mw-search-iwresults'>\n";
1476 // work out custom project captions
1477 $customCaptions = array();
1478 $customLines = explode("\n",wfMsg('search-interwiki-custom')); // format per line <iwprefix>:<caption>
1479 foreach($customLines as $line){
1480 $parts = explode(":",$line,2);
1481 if(count($parts) == 2) // validate line
1482 $customCaptions[$parts[0]] = $parts[1];
1486 $prev = null;
1487 while( $result = $matches->next() ) {
1488 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
1489 $prev = $result->getInterwikiPrefix();
1491 // FIXME: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
1492 $out .= "</ul></div>\n";
1494 // convert the whole thing to desired language variant
1495 global $wgContLang;
1496 $out = $wgContLang->convert( $out );
1497 wfProfileOut( __METHOD__ );
1498 return $out;
1502 * Show single interwiki link
1504 * @param SearchResult $result
1505 * @param string $lastInterwiki
1506 * @param array $terms
1507 * @param string $query
1508 * @param array $customCaptions iw prefix -> caption
1510 function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
1511 wfProfileIn( __METHOD__ );
1512 global $wgUser, $wgContLang, $wgLang;
1514 if( $result->isBrokenTitle() ) {
1515 wfProfileOut( __METHOD__ );
1516 return "<!-- Broken link in search result -->\n";
1519 $t = $result->getTitle();
1520 $sk = $wgUser->getSkin();
1522 $titleSnippet = $result->getTitleSnippet($terms);
1524 if( $titleSnippet == '' )
1525 $titleSnippet = null;
1527 $link = $sk->linkKnown(
1529 $titleSnippet
1532 // format redirect if any
1533 $redirectTitle = $result->getRedirectTitle();
1534 $redirectText = $result->getRedirectSnippet($terms);
1535 $redirect = '';
1536 if( !is_null($redirectTitle) ) {
1537 if( $redirectText == '' )
1538 $redirectText = null;
1540 $redirect = "<span class='searchalttitle'>" .
1541 wfMsg(
1542 'search-redirect',
1543 $sk->linkKnown(
1544 $redirectTitle,
1545 $redirectText
1548 "</span>";
1551 $out = "";
1552 // display project name
1553 if(is_null($lastInterwiki) || $lastInterwiki != $t->getInterwiki()){
1554 if( key_exists($t->getInterwiki(),$customCaptions) )
1555 // captions from 'search-interwiki-custom'
1556 $caption = $customCaptions[$t->getInterwiki()];
1557 else{
1558 // default is to show the hostname of the other wiki which might suck
1559 // if there are many wikis on one hostname
1560 $parsed = parse_url($t->getFullURL());
1561 $caption = wfMsg('search-interwiki-default', $parsed['host']);
1563 // "more results" link (special page stuff could be localized, but we might not know target lang)
1564 $searchTitle = Title::newFromText($t->getInterwiki().":Special:Search");
1565 $searchLink = $sk->linkKnown(
1566 $searchTitle,
1567 wfMsg( 'search-interwiki-more' ),
1568 array(),
1569 array(
1570 'search' => $query,
1571 'fulltext' => 'Search'
1574 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>{$searchLink}</span>{$caption}</div>\n<ul>";
1577 $out .= "<li>{$link} {$redirect}</li>\n";
1578 wfProfileOut( __METHOD__ );
1579 return $out;
1584 * Generates the power search box at bottom of [[Special:Search]]
1585 * @param $term string: search term
1586 * @return $out string: HTML form
1588 function powerSearchBox( $term ) {
1589 global $wgScript, $wgContLang;
1591 $namespaces = SearchEngine::searchableNamespaces();
1593 // group namespaces into rows according to subject; try not to make too
1594 // many assumptions about namespace numbering
1595 $rows = array();
1596 foreach( $namespaces as $ns => $name ) {
1597 $subj = MWNamespace::getSubject( $ns );
1598 if( !array_key_exists( $subj, $rows ) ) {
1599 $rows[$subj] = "";
1601 $name = str_replace( '_', ' ', $name );
1602 if( '' == $name ) {
1603 $name = wfMsg( 'blanknamespace' );
1605 $rows[$subj] .= Xml::openElement( 'td', array( 'style' => 'white-space: nowrap' ) ) .
1606 Xml::checkLabel( $name, "ns{$ns}", "mw-search-ns{$ns}", in_array( $ns, $this->namespaces ) ) .
1607 Xml::closeElement( 'td' ) . "\n";
1609 $rows = array_values( $rows );
1610 $numRows = count( $rows );
1612 // lay out namespaces in multiple floating two-column tables so they'll
1613 // be arranged nicely while still accommodating different screen widths
1614 $rowsPerTable = 3; // seems to look nice
1616 // float to the right on RTL wikis
1617 $tableStyle = ( $wgContLang->isRTL() ?
1618 'float: right; margin: 0 0 1em 1em' :
1619 'float: left; margin: 0 1em 1em 0' );
1621 $tables = "";
1622 for( $i = 0; $i < $numRows; $i += $rowsPerTable ) {
1623 $tables .= Xml::openElement( 'table', array( 'style' => $tableStyle ) );
1624 for( $j = $i; $j < $i + $rowsPerTable && $j < $numRows; $j++ ) {
1625 $tables .= "<tr>\n" . $rows[$j] . "</tr>";
1627 $tables .= Xml::closeElement( 'table' ) . "\n";
1630 $redirect = Xml::check( 'redirs', $this->searchRedirects, array( 'value' => '1', 'id' => 'redirs' ) );
1631 $redirectLabel = Xml::label( wfMsg( 'powersearch-redir' ), 'redirs' );
1632 $searchField = Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'powerSearchText' ) );
1633 $searchButton = Xml::submitButton( wfMsg( 'powersearch' ) ) . "\n";
1634 $searchTitle = SpecialPage::getTitleFor( 'Search' );
1635 $searchHiddens = Xml::hidden( 'title', $searchTitle->getPrefixedText() ) . "\n";
1636 $searchHiddens .= Xml::hidden( 'fulltext', 'Advanced search' ) . "\n";
1638 $out = Xml::openElement( 'form', array( 'id' => 'powersearch', 'method' => 'get', 'action' => $wgScript ) ) .
1639 Xml::fieldset( wfMsg( 'powersearch-legend' ),
1640 "<p>" .
1641 wfMsgExt( 'powersearch-ns', array( 'parseinline' ) ) .
1642 "</p>\n" .
1643 $tables .
1644 "<hr style=\"clear: both\" />\n" .
1645 "<p>" .
1646 $redirect . " " . $redirectLabel .
1647 "</p>\n" .
1648 wfMsgExt( 'powersearch-field', array( 'parseinline' ) ) .
1649 "&nbsp;" .
1650 $searchField .
1651 "&nbsp;" .
1652 $searchHiddens .
1653 $searchButton ) .
1654 "</form>";
1656 return $out;
1659 function powerSearchFocus() {
1660 global $wgJsMimeType;
1661 return "<script type=\"$wgJsMimeType\">" .
1662 "hookEvent(\"load\", function(){" .
1663 "document.getElementById('powerSearchText').focus();" .
1664 "});" .
1665 "</script>";
1668 function shortDialog($term) {
1669 global $wgScript;
1671 $out = Xml::openElement( 'form', array(
1672 'id' => 'search',
1673 'method' => 'get',
1674 'action' => $wgScript
1676 $searchTitle = SpecialPage::getTitleFor( 'Search' );
1677 $out .= Xml::input( 'search', 50, $term, array( 'type' => 'text', 'id' => 'searchText' ) ) . ' ';
1678 foreach( SearchEngine::searchableNamespaces() as $ns => $name ) {
1679 if( in_array( $ns, $this->namespaces ) ) {
1680 $out .= Xml::hidden( "ns{$ns}", '1' );
1683 $out .= Xml::hidden( 'title', $searchTitle->getPrefixedText() );
1684 $out .= Xml::hidden( 'fulltext', 'Search' );
1685 $out .= Xml::submitButton( wfMsg( 'searchbutton' ) );
1686 $out .= Xml::closeElement( 'form' );
1688 return $out;