DifferenceEngine cleanup
[mediawiki.git] / includes / specials / SpecialSearch.php
blob8c8de8e7dd64f8d4131e2d97c2a9c29f8e8c4849
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 * null|string
39 protected $profile;
40 function getProfile() { return $this->profile; }
42 /// Search engine
43 protected $searchEngine;
45 /// Search engine type, if not default
46 protected $searchEngineType;
48 /// For links
49 protected $extraParams = array();
51 /// No idea, apparently used by some other classes
52 protected $mPrefix;
54 /**
55 * @var int
57 protected $limit, $offset;
59 /**
60 * @var array
62 protected $namespaces;
63 function getNamespaces() { return $this->namespaces; }
65 /**
66 * @var bool
68 protected $searchRedirects;
70 /**
71 * @var string
73 protected $didYouMeanHtml, $fulltext;
75 const NAMESPACES_CURRENT = 'sense';
77 public function __construct() {
78 parent::__construct( 'Search' );
81 /**
82 * Entry point
84 * @param string $par or null
86 public function execute( $par ) {
87 $this->setHeaders();
88 $this->outputHeader();
89 $out = $this->getOutput();
90 $out->allowClickjacking();
91 $out->addModuleStyles( 'mediawiki.special' );
93 // Strip underscores from title parameter; most of the time we'll want
94 // text form here. But don't strip underscores from actual text params!
95 $titleParam = str_replace( '_', ' ', $par );
97 $request = $this->getRequest();
99 // Fetch the search term
100 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
102 $this->load();
104 $this->searchEngineType = $request->getVal( 'srbackend' );
106 if ( $request->getVal( 'fulltext' )
107 || !is_null( $request->getVal( 'offset' ) )
108 || !is_null( $request->getVal( 'searchx' ) ) )
110 $this->showResults( $search );
111 } else {
112 $this->goResult( $search );
117 * Set up basic search parameters from the request and user settings.
119 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
121 public function load() {
122 $request = $this->getRequest();
123 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
124 $this->mPrefix = $request->getVal( 'prefix', '' );
126 $user = $this->getUser();
128 # Extract manually requested namespaces
129 $nslist = $this->powerSearch( $request );
130 if ( !count( $nslist ) ) {
131 # Fallback to user preference
132 $nslist = SearchEngine::userNamespaces( $user );
135 $profile = null;
136 if ( !count( $nslist ) ) {
137 $profile = 'default';
140 $profile = $request->getVal( 'profile', $profile );
141 $profiles = $this->getSearchProfiles();
142 if ( $profile === null ) {
143 // BC with old request format
144 $profile = 'advanced';
145 foreach ( $profiles as $key => $data ) {
146 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
147 $profile = $key;
150 $this->namespaces = $nslist;
151 } elseif ( $profile === 'advanced' ) {
152 $this->namespaces = $nslist;
153 } else {
154 if ( isset( $profiles[$profile]['namespaces'] ) ) {
155 $this->namespaces = $profiles[$profile]['namespaces'];
156 } else {
157 // Unknown profile requested
158 $profile = 'default';
159 $this->namespaces = $profiles['default']['namespaces'];
163 // Redirects defaults to true, but we don't know whether it was ticked of or just missing
164 $default = $request->getBool( 'profile' ) ? 0 : 1;
165 $this->searchRedirects = $request->getBool( 'redirs', $default ) ? 1 : 0;
166 $this->didYouMeanHtml = ''; # html of did you mean... link
167 $this->fulltext = $request->getVal( 'fulltext' );
168 $this->profile = $profile;
172 * If an exact title match can be found, jump straight ahead to it.
174 * @param $term String
176 public function goResult( $term ) {
177 $this->setupPage( $term );
178 # Try to go to page as entered.
179 $t = Title::newFromText( $term );
180 # If the string cannot be used to create a title
181 if ( is_null( $t ) ) {
182 $this->showResults( $term );
183 return;
185 # If there's an exact or very near match, jump right there.
186 $t = SearchEngine::getNearMatch( $term );
188 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
189 # Hook requested termination
190 return;
193 if ( !is_null( $t ) ) {
194 $this->getOutput()->redirect( $t->getFullURL() );
195 return;
197 # No match, generate an edit URL
198 $t = Title::newFromText( $term );
199 if ( !is_null( $t ) ) {
200 global $wgGoToEdit;
201 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
202 wfDebugLog( 'nogomatch', $t->getText(), false );
204 # If the feature is enabled, go straight to the edit page
205 if ( $wgGoToEdit ) {
206 $this->getOutput()->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
207 return;
210 $this->showResults( $term );
214 * @param $term String
216 public function showResults( $term ) {
217 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
218 wfProfileIn( __METHOD__ );
220 $search = $this->getSearchEngine();
221 $search->setLimitOffset( $this->limit, $this->offset );
222 $search->setNamespaces( $this->namespaces );
223 $search->showRedirects = $this->searchRedirects; // BC
224 $search->setFeatureData( 'list-redirects', $this->searchRedirects );
225 $search->prefix = $this->mPrefix;
226 $term = $search->transformSearchTerm( $term );
228 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile, $search ) );
230 $this->setupPage( $term );
232 $out = $this->getOutput();
234 if ( $wgDisableTextSearch ) {
235 if ( $wgSearchForwardUrl ) {
236 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
237 $out->redirect( $url );
238 } else {
239 $out->addHTML(
240 Xml::openElement( 'fieldset' ) .
241 Xml::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
242 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), $this->msg( 'searchdisabled' )->text() ) .
243 $this->msg( 'googlesearch' )->rawParams(
244 htmlspecialchars( $term ),
245 'UTF-8',
246 $this->msg( 'searchbutton' )->escaped()
247 )->text() .
248 Xml::closeElement( 'fieldset' )
251 wfProfileOut( __METHOD__ );
252 return;
255 $t = Title::newFromText( $term );
257 // fetch search results
258 $rewritten = $search->replacePrefixes( $term );
260 $titleMatches = $search->searchTitle( $rewritten );
261 if ( !( $titleMatches instanceof SearchResultTooMany ) ) {
262 $textMatches = $search->searchText( $rewritten );
265 $textStatus = null;
266 if ( $textMatches instanceof Status ) {
267 $textStatus = $textMatches;
268 $textMatches = null;
271 // did you mean... suggestions
272 if ( $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
273 $st = SpecialPage::getTitleFor( 'Search' );
275 # mirror Go/Search behavior of original request ..
276 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
278 if ( $this->fulltext != null ) {
279 $didYouMeanParams['fulltext'] = $this->fulltext;
282 $stParams = array_merge(
283 $didYouMeanParams,
284 $this->powerSearchOptions()
287 $suggestionSnippet = $textMatches->getSuggestionSnippet();
289 if ( $suggestionSnippet == '' ) {
290 $suggestionSnippet = null;
293 $suggestLink = Linker::linkKnown(
294 $st,
295 $suggestionSnippet,
296 array(),
297 $stParams
300 $this->didYouMeanHtml = '<div class="searchdidyoumean">' . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
303 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
304 # Hook requested termination
305 wfProfileOut( __METHOD__ );
306 return;
309 // start rendering the page
310 $out->addHtml(
311 Xml::openElement(
312 'form',
313 array(
314 'id' => ( $this->profile === 'advanced' ? 'powersearch' : 'search' ),
315 'method' => 'get',
316 'action' => $wgScript
320 $out->addHtml(
321 # This is an awful awful ID name. It's not a table, but we
322 # named it poorly from when this was a table so now we're
323 # stuck with it
324 Xml::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
325 $this->shortDialog( $term ) .
326 Xml::closeElement( 'div' )
329 // Sometimes the search engine knows there are too many hits
330 if ( $titleMatches instanceof SearchResultTooMany ) {
331 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
332 wfProfileOut( __METHOD__ );
333 return;
336 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
337 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
338 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
339 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
340 $out->addHTML( '</form>' );
341 // Empty query -- straight view of search form
342 wfProfileOut( __METHOD__ );
343 return;
346 // Get number of results
347 $titleMatchesNum = $titleMatches ? $titleMatches->numRows() : 0;
348 $textMatchesNum = $textMatches ? $textMatches->numRows() : 0;
349 // Total initial query matches (possible false positives)
350 $num = $titleMatchesNum + $textMatchesNum;
352 // Get total actual results (after second filtering, if any)
353 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
354 $titleMatches->getTotalHits() : $titleMatchesNum;
355 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
356 $textMatches->getTotalHits() : $textMatchesNum;
358 // get total number of results if backend can calculate it
359 $totalRes = 0;
360 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
361 $totalRes += $titleMatches->getTotalHits();
363 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
364 $totalRes += $textMatches->getTotalHits();
367 // show number of results and current offset
368 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
369 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
371 $out->addHtml( Xml::closeElement( 'form' ) );
372 $out->addHtml( "<div class='searchresults'>" );
374 // prev/next links
375 if ( $num || $this->offset ) {
376 // Show the create link ahead
377 $this->showCreateLink( $t );
378 $prevnext = $this->getLanguage()->viewPrevNext( $this->getTitle(), $this->offset, $this->limit,
379 $this->powerSearchOptions() + array( 'search' => $term ),
380 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
382 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
383 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
384 } else {
385 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
388 $out->parserOptions()->setEditSection( false );
389 if ( $titleMatches ) {
390 if ( $numTitleMatches > 0 ) {
391 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
392 $out->addHTML( $this->showMatches( $titleMatches ) );
394 $titleMatches->free();
396 if ( $textMatches && !$textStatus ) {
397 // output appropriate heading
398 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
399 // if no title matches the heading is redundant
400 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
401 } elseif ( $totalRes == 0 ) {
402 # Don't show the 'no text matches' if we received title matches
403 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
405 // show interwiki results if any
406 if ( $textMatches->hasInterwikiResults() ) {
407 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
409 // show results
410 if ( $numTextMatches > 0 ) {
411 $out->addHTML( $this->showMatches( $textMatches ) );
414 $textMatches->free();
416 if ( $num === 0 ) {
417 if ( $textStatus ) {
418 $out->addHTML( '<div class="error">' .
419 htmlspecialchars( $textStatus->getWikiText( 'search-error' ) ) . '</div>' );
420 } else {
421 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
422 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
423 $this->showCreateLink( $t );
426 $out->addHtml( "</div>" );
428 if ( $num || $this->offset ) {
429 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
431 wfRunHooks( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
432 wfProfileOut( __METHOD__ );
436 * @param $t Title
438 protected function showCreateLink( $t ) {
439 // show direct page/create link if applicable
441 // Check DBkey !== '' in case of fragment link only.
442 if ( is_null( $t ) || $t->getDBkey() === '' ) {
443 // invalid title
444 // preserve the paragraph for margins etc...
445 $this->getOutput()->addHtml( '<p></p>' );
446 return;
449 if ( $t->isKnown() ) {
450 $messageName = 'searchmenu-exists';
451 } elseif ( $t->userCan( 'create', $this->getUser() ) ) {
452 $messageName = 'searchmenu-new';
453 } else {
454 $messageName = 'searchmenu-new-nocreate';
456 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ) );
457 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
459 // Extensions using the hook might still return an empty $messageName
460 if ( $messageName ) {
461 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
462 } else {
463 // preserve the paragraph for margins etc...
464 $this->getOutput()->addHtml( '<p></p>' );
469 * @param $term string
471 protected function setupPage( $term ) {
472 # Should advanced UI be used?
473 $this->searchAdvanced = ( $this->profile === 'advanced' );
474 $out = $this->getOutput();
475 if ( strval( $term ) !== '' ) {
476 $out->setPageTitle( $this->msg( 'searchresults' ) );
477 $out->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams(
478 $this->msg( 'searchresults-title' )->rawParams( $term )->text()
479 ) );
481 // add javascript specific to special:search
482 $out->addModules( 'mediawiki.special.search' );
486 * Extract "power search" namespace settings from the request object,
487 * returning a list of index numbers to search.
489 * @param $request WebRequest
490 * @return Array
492 protected function powerSearch( &$request ) {
493 $arr = array();
494 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
495 if ( $request->getCheck( 'ns' . $ns ) ) {
496 $arr[] = $ns;
500 return $arr;
504 * Reconstruct the 'power search' options for links
506 * @return Array
508 protected function powerSearchOptions() {
509 $opt = array();
510 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
511 if ( $this->profile !== 'advanced' ) {
512 $opt['profile'] = $this->profile;
513 } else {
514 foreach ( $this->namespaces as $n ) {
515 $opt['ns' . $n] = 1;
518 return $opt + $this->extraParams;
522 * Show whole set of results
524 * @param $matches SearchResultSet
526 * @return string
528 protected function showMatches( &$matches ) {
529 global $wgContLang;
530 wfProfileIn( __METHOD__ );
532 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
534 $out = "";
535 $infoLine = $matches->getInfo();
536 if ( !is_null( $infoLine ) ) {
537 $out .= "\n<!-- {$infoLine} -->\n";
539 $out .= "<ul class='mw-search-results'>\n";
540 $result = $matches->next();
541 while ( $result ) {
542 $out .= $this->showHit( $result, $terms );
543 $result = $matches->next();
545 $out .= "</ul>\n";
547 // convert the whole thing to desired language variant
548 $out = $wgContLang->convert( $out );
549 wfProfileOut( __METHOD__ );
550 return $out;
554 * Format a single hit result
556 * @param $result SearchResult
557 * @param array $terms terms to highlight
559 * @return string
561 protected function showHit( $result, $terms ) {
562 wfProfileIn( __METHOD__ );
564 if ( $result->isBrokenTitle() ) {
565 wfProfileOut( __METHOD__ );
566 return "<!-- Broken link in search result -->\n";
569 $t = $result->getTitle();
571 $titleSnippet = $result->getTitleSnippet( $terms );
573 if ( $titleSnippet == '' ) {
574 $titleSnippet = null;
577 $link_t = clone $t;
579 wfRunHooks( 'ShowSearchHitTitle',
580 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
582 $link = Linker::linkKnown(
583 $link_t,
584 $titleSnippet
587 //If page content is not readable, just return the title.
588 //This is not quite safe, but better than showing excerpts from non-readable pages
589 //Note that hiding the entry entirely would screw up paging.
590 if ( !$t->userCan( 'read', $this->getUser() ) ) {
591 wfProfileOut( __METHOD__ );
592 return "<li>{$link}</li>\n";
595 // If the page doesn't *exist*... our search index is out of date.
596 // The least confusing at this point is to drop the result.
597 // You may get less results, but... oh well. :P
598 if ( $result->isMissingRevision() ) {
599 wfProfileOut( __METHOD__ );
600 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
603 // format redirects / relevant sections
604 $redirectTitle = $result->getRedirectTitle();
605 $redirectText = $result->getRedirectSnippet( $terms );
606 $sectionTitle = $result->getSectionTitle();
607 $sectionText = $result->getSectionSnippet( $terms );
608 $redirect = '';
610 if ( !is_null( $redirectTitle ) ) {
611 if ( $redirectText == '' ) {
612 $redirectText = null;
615 $redirect = "<span class='searchalttitle'>" .
616 $this->msg( 'search-redirect' )->rawParams(
617 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
618 "</span>";
621 $section = '';
623 if ( !is_null( $sectionTitle ) ) {
624 if ( $sectionText == '' ) {
625 $sectionText = null;
628 $section = "<span class='searchalttitle'>" .
629 $this->msg( 'search-section' )->rawParams(
630 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
631 "</span>";
634 // format text extract
635 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
637 $lang = $this->getLanguage();
639 // format score
640 if ( is_null( $result->getScore() ) ) {
641 // Search engine doesn't report scoring info
642 $score = '';
643 } else {
644 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
645 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
646 . ' - ';
649 // format description
650 $byteSize = $result->getByteSize();
651 $wordCount = $result->getWordCount();
652 $timestamp = $result->getTimestamp();
653 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
654 ->numParams( $wordCount )->escaped();
656 if ( $t->getNamespace() == NS_CATEGORY ) {
657 $cat = Category::newFromTitle( $t );
658 $size = $this->msg( 'search-result-category-size' )
659 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
660 ->escaped();
663 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
665 // link to related articles if supported
666 $related = '';
667 if ( $result->hasRelated() ) {
668 $st = SpecialPage::getTitleFor( 'Search' );
669 $stParams = array_merge(
670 $this->powerSearchOptions(),
671 array(
672 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
673 ':' . $t->getPrefixedText(),
674 'fulltext' => $this->msg( 'search' )->text()
678 $related = ' -- ' . Linker::linkKnown(
679 $st,
680 $this->msg( 'search-relatedarticle' )->text(),
681 array(),
682 $stParams
686 // Include a thumbnail for media files...
687 if ( $t->getNamespace() == NS_FILE ) {
688 $img = wfFindFile( $t );
689 if ( $img ) {
690 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
691 if ( $thumb ) {
692 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
693 wfProfileOut( __METHOD__ );
694 // Float doesn't seem to interact well with the bullets.
695 // Table messes up vertical alignment of the bullets.
696 // Bullets are therefore disabled (didn't look great anyway).
697 return "<li>" .
698 '<table class="searchResultImage">' .
699 '<tr>' .
700 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
701 $thumb->toHtml( array( 'desc-link' => true ) ) .
702 '</td>' .
703 '<td style="vertical-align: top;">' .
704 $link .
705 $extract .
706 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
707 '</td>' .
708 '</tr>' .
709 '</table>' .
710 "</li>\n";
715 $html = null;
717 if ( wfRunHooks( 'ShowSearchHit', array(
718 $this, $result, $terms,
719 &$link, &$redirect, &$section, &$extract,
720 &$score, &$size, &$date, &$related,
721 &$html
722 ) ) ) {
723 $html = "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
724 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
725 "</li>\n";
728 wfProfileOut( __METHOD__ );
729 return $html;
733 * Show results from other wikis
735 * @param $matches SearchResultSet
736 * @param $query String
738 * @return string
740 protected function showInterwiki( $matches, $query ) {
741 global $wgContLang;
742 wfProfileIn( __METHOD__ );
743 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
745 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
746 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
747 $out .= "<ul class='mw-search-iwresults'>\n";
749 // work out custom project captions
750 $customCaptions = array();
751 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() ); // format per line <iwprefix>:<caption>
752 foreach ( $customLines as $line ) {
753 $parts = explode( ":", $line, 2 );
754 if ( count( $parts ) == 2 ) { // validate line
755 $customCaptions[$parts[0]] = $parts[1];
759 $prev = null;
760 $result = $matches->next();
761 while ( $result ) {
762 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
763 $prev = $result->getInterwikiPrefix();
764 $result = $matches->next();
766 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
767 $out .= "</ul></div>\n";
769 // convert the whole thing to desired language variant
770 $out = $wgContLang->convert( $out );
771 wfProfileOut( __METHOD__ );
772 return $out;
776 * Show single interwiki link
778 * @param $result SearchResult
779 * @param $lastInterwiki String
780 * @param $terms Array
781 * @param $query String
782 * @param array $customCaptions iw prefix -> caption
784 * @return string
786 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions ) {
787 wfProfileIn( __METHOD__ );
789 if ( $result->isBrokenTitle() ) {
790 wfProfileOut( __METHOD__ );
791 return "<!-- Broken link in search result -->\n";
794 $t = $result->getTitle();
796 $titleSnippet = $result->getTitleSnippet( $terms );
798 if ( $titleSnippet == '' ) {
799 $titleSnippet = null;
802 $link = Linker::linkKnown(
804 $titleSnippet
807 // format redirect if any
808 $redirectTitle = $result->getRedirectTitle();
809 $redirectText = $result->getRedirectSnippet( $terms );
810 $redirect = '';
811 if ( !is_null( $redirectTitle ) ) {
812 if ( $redirectText == '' ) {
813 $redirectText = null;
816 $redirect = "<span class='searchalttitle'>" .
817 $this->msg( 'search-redirect' )->rawParams(
818 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
819 "</span>";
822 $out = "";
823 // display project name
824 if ( is_null( $lastInterwiki ) || $lastInterwiki != $t->getInterwiki() ) {
825 if ( array_key_exists( $t->getInterwiki(), $customCaptions ) ) {
826 // captions from 'search-interwiki-custom'
827 $caption = $customCaptions[$t->getInterwiki()];
828 } else {
829 // default is to show the hostname of the other wiki which might suck
830 // if there are many wikis on one hostname
831 $parsed = wfParseUrl( $t->getFullURL() );
832 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
834 // "more results" link (special page stuff could be localized, but we might not know target lang)
835 $searchTitle = Title::newFromText( $t->getInterwiki() . ":Special:Search" );
836 $searchLink = Linker::linkKnown(
837 $searchTitle,
838 $this->msg( 'search-interwiki-more' )->text(),
839 array(),
840 array(
841 'search' => $query,
842 'fulltext' => 'Search'
845 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
846 {$searchLink}</span>{$caption}</div>\n<ul>";
849 $out .= "<li>{$link} {$redirect}</li>\n";
850 wfProfileOut( __METHOD__ );
851 return $out;
855 * @param $profile
856 * @param $term
857 * @return String
859 protected function getProfileForm( $profile, $term ) {
860 // Hidden stuff
861 $opts = array();
862 $opts['redirs'] = $this->searchRedirects;
863 $opts['profile'] = $this->profile;
865 if ( $profile === 'advanced' ) {
866 return $this->powerSearchBox( $term, $opts );
867 } else {
868 $form = '';
869 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
870 return $form;
875 * Generates the power search box at [[Special:Search]]
877 * @param string $term search term
878 * @param $opts array
879 * @return String: HTML form
881 protected function powerSearchBox( $term, $opts ) {
882 global $wgContLang;
884 // Groups namespaces into rows according to subject
885 $rows = array();
886 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
887 $subject = MWNamespace::getSubject( $namespace );
888 if ( !array_key_exists( $subject, $rows ) ) {
889 $rows[$subject] = "";
892 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
893 if ( $name == '' ) {
894 $name = $this->msg( 'blanknamespace' )->text();
897 $rows[$subject] .=
898 Xml::openElement(
899 'td', array( 'style' => 'white-space: nowrap' )
901 Xml::checkLabel(
902 $name,
903 "ns{$namespace}",
904 "mw-search-ns{$namespace}",
905 in_array( $namespace, $this->namespaces )
907 Xml::closeElement( 'td' );
910 $rows = array_values( $rows );
911 $numRows = count( $rows );
913 // Lays out namespaces in multiple floating two-column tables so they'll
914 // be arranged nicely while still accommodating different screen widths
915 $namespaceTables = '';
916 for ( $i = 0; $i < $numRows; $i += 4 ) {
917 $namespaceTables .= Xml::openElement(
918 'table',
919 array( 'cellpadding' => 0, 'cellspacing' => 0 )
922 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
923 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
926 $namespaceTables .= Xml::closeElement( 'table' );
929 $showSections = array( 'namespaceTables' => $namespaceTables );
931 // Show redirects check only if backend supports it
932 if ( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
933 $showSections['redirects'] =
934 Xml::checkLabel( $this->msg( 'powersearch-redir' )->text(), 'redirs', 'redirs', $this->searchRedirects );
937 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
939 $hidden = '';
940 unset( $opts['redirs'] );
941 foreach ( $opts as $key => $value ) {
942 $hidden .= Html::hidden( $key, $value );
944 // Return final output
945 return Xml::openElement(
946 'fieldset',
947 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
949 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
950 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
951 Html::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
952 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
953 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
954 $hidden .
955 Xml::closeElement( 'fieldset' );
959 * @return array
961 protected function getSearchProfiles() {
962 // Builds list of Search Types (profiles)
963 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
965 $profiles = array(
966 'default' => array(
967 'message' => 'searchprofile-articles',
968 'tooltip' => 'searchprofile-articles-tooltip',
969 'namespaces' => SearchEngine::defaultNamespaces(),
970 'namespace-messages' => SearchEngine::namespacesAsText(
971 SearchEngine::defaultNamespaces()
974 'images' => array(
975 'message' => 'searchprofile-images',
976 'tooltip' => 'searchprofile-images-tooltip',
977 'namespaces' => array( NS_FILE ),
979 'help' => array(
980 'message' => 'searchprofile-project',
981 'tooltip' => 'searchprofile-project-tooltip',
982 'namespaces' => SearchEngine::helpNamespaces(),
983 'namespace-messages' => SearchEngine::namespacesAsText(
984 SearchEngine::helpNamespaces()
987 'all' => array(
988 'message' => 'searchprofile-everything',
989 'tooltip' => 'searchprofile-everything-tooltip',
990 'namespaces' => $nsAllSet,
992 'advanced' => array(
993 'message' => 'searchprofile-advanced',
994 'tooltip' => 'searchprofile-advanced-tooltip',
995 'namespaces' => self::NAMESPACES_CURRENT,
999 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1001 foreach ( $profiles as &$data ) {
1002 if ( !is_array( $data['namespaces'] ) ) {
1003 continue;
1005 sort( $data['namespaces'] );
1008 return $profiles;
1012 * @param $term
1013 * @param $resultsShown
1014 * @param $totalNum
1015 * @return string
1017 protected function formHeader( $term, $resultsShown, $totalNum ) {
1018 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1020 $bareterm = $term;
1021 if ( $this->startsWithImage( $term ) ) {
1022 // Deletes prefixes
1023 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1026 $profiles = $this->getSearchProfiles();
1027 $lang = $this->getLanguage();
1029 // Outputs XML for Search Types
1030 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1031 $out .= Xml::openElement( 'ul' );
1032 foreach ( $profiles as $id => $profile ) {
1033 if ( !isset( $profile['parameters'] ) ) {
1034 $profile['parameters'] = array();
1036 $profile['parameters']['profile'] = $id;
1038 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1039 $lang->commaList( $profile['namespace-messages'] ) : null;
1040 $out .= Xml::tags(
1041 'li',
1042 array(
1043 'class' => $this->profile === $id ? 'current' : 'normal'
1045 $this->makeSearchLink(
1046 $bareterm,
1047 array(),
1048 $this->msg( $profile['message'] )->text(),
1049 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1050 $profile['parameters']
1054 $out .= Xml::closeElement( 'ul' );
1055 $out .= Xml::closeElement( 'div' );
1057 // Results-info
1058 if ( $resultsShown > 0 ) {
1059 if ( $totalNum > 0 ) {
1060 $top = $this->msg( 'showingresultsheader' )
1061 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1062 ->params( wfEscapeWikiText( $term ) )
1063 ->numParams( $resultsShown )
1064 ->parse();
1065 } elseif ( $resultsShown >= $this->limit ) {
1066 $top = $this->msg( 'showingresults' )
1067 ->numParams( $this->limit, $this->offset + 1 )
1068 ->parse();
1069 } else {
1070 $top = $this->msg( 'showingresultsnum' )
1071 ->numParams( $this->limit, $this->offset + 1, $resultsShown )
1072 ->parse();
1074 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
1075 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
1079 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1080 $out .= Xml::closeElement( 'div' );
1082 return $out;
1086 * @param $term string
1087 * @return string
1089 protected function shortDialog( $term ) {
1090 $out = Html::hidden( 'title', $this->getTitle()->getPrefixedText() );
1091 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1092 // Term box
1093 $out .= Html::input( 'search', $term, 'search', array(
1094 'id' => $this->profile === 'advanced' ? 'powerSearchText' : 'searchText',
1095 'size' => '50',
1096 'autofocus'
1097 ) ) . "\n";
1098 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1099 $out .= Xml::submitButton( $this->msg( 'searchbutton' )->text() ) . "\n";
1100 return $out . $this->didYouMeanHtml;
1104 * Make a search link with some target namespaces
1106 * @param $term String
1107 * @param array $namespaces ignored
1108 * @param string $label link's text
1109 * @param string $tooltip link's tooltip
1110 * @param array $params query string parameters
1111 * @return String: HTML fragment
1113 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1114 $opt = $params;
1115 foreach ( $namespaces as $n ) {
1116 $opt['ns' . $n] = 1;
1118 $opt['redirs'] = $this->searchRedirects;
1120 $stParams = array_merge(
1121 array(
1122 'search' => $term,
1123 'fulltext' => $this->msg( 'search' )->text()
1125 $opt
1128 return Xml::element(
1129 'a',
1130 array(
1131 'href' => $this->getTitle()->getLocalURL( $stParams ),
1132 'title' => $tooltip
1134 $label
1139 * Check if query starts with image: prefix
1141 * @param string $term the string to check
1142 * @return Boolean
1144 protected function startsWithImage( $term ) {
1145 global $wgContLang;
1147 $p = explode( ':', $term );
1148 if ( count( $p ) > 1 ) {
1149 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
1151 return false;
1155 * Check if query starts with all: prefix
1157 * @param string $term the string to check
1158 * @return Boolean
1160 protected function startsWithAll( $term ) {
1162 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1164 $p = explode( ':', $term );
1165 if ( count( $p ) > 1 ) {
1166 return $p[0] == $allkeyword;
1168 return false;
1172 * @since 1.18
1174 * @return SearchEngine
1176 public function getSearchEngine() {
1177 if ( $this->searchEngine === null ) {
1178 $this->searchEngine = $this->searchEngineType ?
1179 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1181 return $this->searchEngine;
1185 * Users of hook SpecialSearchSetupEngine can use this to
1186 * add more params to links to not lose selection when
1187 * user navigates search results.
1188 * @since 1.18
1190 * @param $key
1191 * @param $value
1193 public function setExtraParam( $key, $value ) {
1194 $this->extraParams[$key] = $value;
1197 protected function getGroupName() {
1198 return 'pages';