Merge "Whitelist the <wbr> element."
[mediawiki.git] / includes / specials / SpecialSearch.php
blob8a2163b56cfd296894c1aeeb032b8189afff6b6b
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 /// For links
46 protected $extraParams = array();
48 /// No idea, apparently used by some other classes
49 protected $mPrefix;
51 /**
52 * @var int
54 protected $limit, $offset;
56 /**
57 * @var array
59 protected $namespaces;
60 function getNamespaces() { return $this->namespaces; }
62 /**
63 * @var bool
65 protected $searchRedirects;
67 /**
68 * @var string
70 protected $didYouMeanHtml, $fulltext;
72 const NAMESPACES_CURRENT = 'sense';
74 public function __construct() {
75 parent::__construct( 'Search' );
78 /**
79 * Entry point
81 * @param string $par or null
83 public function execute( $par ) {
84 $this->setHeaders();
85 $this->outputHeader();
86 $out = $this->getOutput();
87 $out->allowClickjacking();
88 $out->addModuleStyles( 'mediawiki.special' );
90 // Strip underscores from title parameter; most of the time we'll want
91 // text form here. But don't strip underscores from actual text params!
92 $titleParam = str_replace( '_', ' ', $par );
94 $request = $this->getRequest();
96 // Fetch the search term
97 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
99 $this->load();
101 if ( $request->getVal( 'fulltext' )
102 || !is_null( $request->getVal( 'offset' ) )
103 || !is_null( $request->getVal( 'searchx' ) ) )
105 $this->showResults( $search );
106 } else {
107 $this->goResult( $search );
112 * Set up basic search parameters from the request and user settings.
114 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
116 public function load() {
117 $request = $this->getRequest();
118 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
119 $this->mPrefix = $request->getVal( 'prefix', '' );
121 $user = $this->getUser();
123 # Extract manually requested namespaces
124 $nslist = $this->powerSearch( $request );
125 if ( !count( $nslist ) ) {
126 # Fallback to user preference
127 $nslist = SearchEngine::userNamespaces( $user );
130 $profile = null;
131 if ( !count( $nslist ) ) {
132 $profile = 'default';
135 $profile = $request->getVal( 'profile', $profile );
136 $profiles = $this->getSearchProfiles();
137 if ( $profile === null ) {
138 // BC with old request format
139 $profile = 'advanced';
140 foreach ( $profiles as $key => $data ) {
141 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
142 $profile = $key;
145 $this->namespaces = $nslist;
146 } elseif ( $profile === 'advanced' ) {
147 $this->namespaces = $nslist;
148 } else {
149 if ( isset( $profiles[$profile]['namespaces'] ) ) {
150 $this->namespaces = $profiles[$profile]['namespaces'];
151 } else {
152 // Unknown profile requested
153 $profile = 'default';
154 $this->namespaces = $profiles['default']['namespaces'];
158 // Redirects defaults to true, but we don't know whether it was ticked of or just missing
159 $default = $request->getBool( 'profile' ) ? 0 : 1;
160 $this->searchRedirects = $request->getBool( 'redirs', $default ) ? 1 : 0;
161 $this->didYouMeanHtml = ''; # html of did you mean... link
162 $this->fulltext = $request->getVal( 'fulltext' );
163 $this->profile = $profile;
167 * If an exact title match can be found, jump straight ahead to it.
169 * @param $term String
171 public function goResult( $term ) {
172 $this->setupPage( $term );
173 # Try to go to page as entered.
174 $t = Title::newFromText( $term );
175 # If the string cannot be used to create a title
176 if ( is_null( $t ) ) {
177 $this->showResults( $term );
178 return;
180 # If there's an exact or very near match, jump right there.
181 $t = SearchEngine::getNearMatch( $term );
183 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
184 # Hook requested termination
185 return;
188 if ( !is_null( $t ) ) {
189 $this->getOutput()->redirect( $t->getFullURL() );
190 return;
192 # No match, generate an edit URL
193 $t = Title::newFromText( $term );
194 if ( !is_null( $t ) ) {
195 global $wgGoToEdit;
196 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
197 wfDebugLog( 'nogomatch', $t->getText(), false );
199 # If the feature is enabled, go straight to the edit page
200 if ( $wgGoToEdit ) {
201 $this->getOutput()->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
202 return;
205 $this->showResults( $term );
209 * @param $term String
211 public function showResults( $term ) {
212 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
213 wfProfileIn( __METHOD__ );
215 $search = $this->getSearchEngine();
216 $search->setLimitOffset( $this->limit, $this->offset );
217 $search->setNamespaces( $this->namespaces );
218 $search->showRedirects = $this->searchRedirects; // BC
219 $search->setFeatureData( 'list-redirects', $this->searchRedirects );
220 $search->prefix = $this->mPrefix;
221 $term = $search->transformSearchTerm( $term );
223 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile, $search ) );
225 $this->setupPage( $term );
227 $out = $this->getOutput();
229 if ( $wgDisableTextSearch ) {
230 if ( $wgSearchForwardUrl ) {
231 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
232 $out->redirect( $url );
233 } else {
234 $out->addHTML(
235 Xml::openElement( 'fieldset' ) .
236 Xml::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
237 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), $this->msg( 'searchdisabled' )->text() ) .
238 $this->msg( 'googlesearch' )->rawParams(
239 htmlspecialchars( $term ),
240 'UTF-8',
241 $this->msg( 'searchbutton' )->escaped()
242 )->text() .
243 Xml::closeElement( 'fieldset' )
246 wfProfileOut( __METHOD__ );
247 return;
250 $t = Title::newFromText( $term );
252 // fetch search results
253 $rewritten = $search->replacePrefixes( $term );
255 $titleMatches = $search->searchTitle( $rewritten );
256 if ( !( $titleMatches instanceof SearchResultTooMany ) ) {
257 $textMatches = $search->searchText( $rewritten );
260 $textStatus = null;
261 if ( $textMatches instanceof Status ) {
262 $textStatus = $textMatches;
263 $textMatches = null;
266 // did you mean... suggestions
267 if ( $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
268 $st = SpecialPage::getTitleFor( 'Search' );
270 # mirror Go/Search behavior of original request ..
271 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
273 if ( $this->fulltext != null ) {
274 $didYouMeanParams['fulltext'] = $this->fulltext;
277 $stParams = array_merge(
278 $didYouMeanParams,
279 $this->powerSearchOptions()
282 $suggestionSnippet = $textMatches->getSuggestionSnippet();
284 if ( $suggestionSnippet == '' ) {
285 $suggestionSnippet = null;
288 $suggestLink = Linker::linkKnown(
289 $st,
290 $suggestionSnippet,
291 array(),
292 $stParams
295 $this->didYouMeanHtml = '<div class="searchdidyoumean">' . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
298 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
299 # Hook requested termination
300 wfProfileOut( __METHOD__ );
301 return;
304 // start rendering the page
305 $out->addHtml(
306 Xml::openElement(
307 'form',
308 array(
309 'id' => ( $this->profile === 'advanced' ? 'powersearch' : 'search' ),
310 'method' => 'get',
311 'action' => $wgScript
315 $out->addHtml(
316 Xml::openElement( 'table', array( 'id' => 'mw-search-top-table', 'cellpadding' => 0, 'cellspacing' => 0 ) ) .
317 Xml::openElement( 'tr' ) .
318 Xml::openElement( 'td' ) . "\n" .
319 $this->shortDialog( $term ) .
320 Xml::closeElement( 'td' ) .
321 Xml::closeElement( 'tr' ) .
322 Xml::closeElement( 'table' )
325 // Sometimes the search engine knows there are too many hits
326 if ( $titleMatches instanceof SearchResultTooMany ) {
327 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
328 wfProfileOut( __METHOD__ );
329 return;
332 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
333 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
334 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
335 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
336 $out->addHTML( '</form>' );
337 // Empty query -- straight view of search form
338 wfProfileOut( __METHOD__ );
339 return;
342 // Get number of results
343 $titleMatchesNum = $titleMatches ? $titleMatches->numRows() : 0;
344 $textMatchesNum = $textMatches ? $textMatches->numRows() : 0;
345 // Total initial query matches (possible false positives)
346 $num = $titleMatchesNum + $textMatchesNum;
348 // Get total actual results (after second filtering, if any)
349 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
350 $titleMatches->getTotalHits() : $titleMatchesNum;
351 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
352 $textMatches->getTotalHits() : $textMatchesNum;
354 // get total number of results if backend can calculate it
355 $totalRes = 0;
356 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
357 $totalRes += $titleMatches->getTotalHits();
359 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
360 $totalRes += $textMatches->getTotalHits();
363 // show number of results and current offset
364 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
365 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
367 $out->addHtml( Xml::closeElement( 'form' ) );
368 $out->addHtml( "<div class='searchresults'>" );
370 // prev/next links
371 if ( $num || $this->offset ) {
372 // Show the create link ahead
373 $this->showCreateLink( $t );
374 $prevnext = $this->getLanguage()->viewPrevNext( $this->getTitle(), $this->offset, $this->limit,
375 $this->powerSearchOptions() + array( 'search' => $term ),
376 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
378 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
379 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
380 } else {
381 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
384 $out->parserOptions()->setEditSection( false );
385 if ( $titleMatches ) {
386 if ( $numTitleMatches > 0 ) {
387 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
388 $out->addHTML( $this->showMatches( $titleMatches ) );
390 $titleMatches->free();
392 if ( $textMatches && !$textStatus ) {
393 // output appropriate heading
394 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
395 // if no title matches the heading is redundant
396 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
397 } elseif ( $totalRes == 0 ) {
398 # Don't show the 'no text matches' if we received title matches
399 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
401 // show interwiki results if any
402 if ( $textMatches->hasInterwikiResults() ) {
403 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
405 // show results
406 if ( $numTextMatches > 0 ) {
407 $out->addHTML( $this->showMatches( $textMatches ) );
410 $textMatches->free();
412 if ( $num === 0 ) {
413 if ( $textStatus ) {
414 $out->addHTML( '<div class="error">' .
415 htmlspecialchars( $textStatus->getWikiText( 'search-error' ) ) . '</div>' );
416 } else {
417 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
418 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
419 $this->showCreateLink( $t );
422 $out->addHtml( "</div>" );
424 if ( $num || $this->offset ) {
425 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
427 wfRunHooks( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
428 wfProfileOut( __METHOD__ );
432 * @param $t Title
434 protected function showCreateLink( $t ) {
435 // show direct page/create link if applicable
437 // Check DBkey !== '' in case of fragment link only.
438 if ( is_null( $t ) || $t->getDBkey() === '' ) {
439 // invalid title
440 // preserve the paragraph for margins etc...
441 $this->getOutput()->addHtml( '<p></p>' );
442 return;
445 if ( $t->isKnown() ) {
446 $messageName = 'searchmenu-exists';
447 } elseif ( $t->userCan( 'create', $this->getUser() ) ) {
448 $messageName = 'searchmenu-new';
449 } else {
450 $messageName = 'searchmenu-new-nocreate';
452 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ) );
453 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
455 // Extensions using the hook might still return an empty $messageName
456 if ( $messageName ) {
457 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
458 } else {
459 // preserve the paragraph for margins etc...
460 $this->getOutput()->addHtml( '<p></p>' );
465 * @param $term string
467 protected function setupPage( $term ) {
468 # Should advanced UI be used?
469 $this->searchAdvanced = ( $this->profile === 'advanced' );
470 $out = $this->getOutput();
471 if ( strval( $term ) !== '' ) {
472 $out->setPageTitle( $this->msg( 'searchresults' ) );
473 $out->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams(
474 $this->msg( 'searchresults-title' )->rawParams( $term )->text()
475 ) );
477 // add javascript specific to special:search
478 $out->addModules( 'mediawiki.special.search' );
482 * Extract "power search" namespace settings from the request object,
483 * returning a list of index numbers to search.
485 * @param $request WebRequest
486 * @return Array
488 protected function powerSearch( &$request ) {
489 $arr = array();
490 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
491 if ( $request->getCheck( 'ns' . $ns ) ) {
492 $arr[] = $ns;
496 return $arr;
500 * Reconstruct the 'power search' options for links
502 * @return Array
504 protected function powerSearchOptions() {
505 $opt = array();
506 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
507 if ( $this->profile !== 'advanced' ) {
508 $opt['profile'] = $this->profile;
509 } else {
510 foreach ( $this->namespaces as $n ) {
511 $opt['ns' . $n] = 1;
514 return $opt + $this->extraParams;
518 * Show whole set of results
520 * @param $matches SearchResultSet
522 * @return string
524 protected function showMatches( &$matches ) {
525 global $wgContLang;
526 wfProfileIn( __METHOD__ );
528 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
530 $out = "";
531 $infoLine = $matches->getInfo();
532 if ( !is_null( $infoLine ) ) {
533 $out .= "\n<!-- {$infoLine} -->\n";
535 $out .= "<ul class='mw-search-results'>\n";
536 $result = $matches->next();
537 while ( $result ) {
538 $out .= $this->showHit( $result, $terms );
539 $result = $matches->next();
541 $out .= "</ul>\n";
543 // convert the whole thing to desired language variant
544 $out = $wgContLang->convert( $out );
545 wfProfileOut( __METHOD__ );
546 return $out;
550 * Format a single hit result
552 * @param $result SearchResult
553 * @param array $terms terms to highlight
555 * @return string
557 protected function showHit( $result, $terms ) {
558 wfProfileIn( __METHOD__ );
560 if ( $result->isBrokenTitle() ) {
561 wfProfileOut( __METHOD__ );
562 return "<!-- Broken link in search result -->\n";
565 $t = $result->getTitle();
567 $titleSnippet = $result->getTitleSnippet( $terms );
569 if ( $titleSnippet == '' ) {
570 $titleSnippet = null;
573 $link_t = clone $t;
575 wfRunHooks( 'ShowSearchHitTitle',
576 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
578 $link = Linker::linkKnown(
579 $link_t,
580 $titleSnippet
583 //If page content is not readable, just return the title.
584 //This is not quite safe, but better than showing excerpts from non-readable pages
585 //Note that hiding the entry entirely would screw up paging.
586 if ( !$t->userCan( 'read', $this->getUser() ) ) {
587 wfProfileOut( __METHOD__ );
588 return "<li>{$link}</li>\n";
591 // If the page doesn't *exist*... our search index is out of date.
592 // The least confusing at this point is to drop the result.
593 // You may get less results, but... oh well. :P
594 if ( $result->isMissingRevision() ) {
595 wfProfileOut( __METHOD__ );
596 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
599 // format redirects / relevant sections
600 $redirectTitle = $result->getRedirectTitle();
601 $redirectText = $result->getRedirectSnippet( $terms );
602 $sectionTitle = $result->getSectionTitle();
603 $sectionText = $result->getSectionSnippet( $terms );
604 $redirect = '';
606 if ( !is_null( $redirectTitle ) ) {
607 if ( $redirectText == '' ) {
608 $redirectText = null;
611 $redirect = "<span class='searchalttitle'>" .
612 $this->msg( 'search-redirect' )->rawParams(
613 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
614 "</span>";
617 $section = '';
619 if ( !is_null( $sectionTitle ) ) {
620 if ( $sectionText == '' ) {
621 $sectionText = null;
624 $section = "<span class='searchalttitle'>" .
625 $this->msg( 'search-section' )->rawParams(
626 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
627 "</span>";
630 // format text extract
631 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
633 $lang = $this->getLanguage();
635 // format score
636 if ( is_null( $result->getScore() ) ) {
637 // Search engine doesn't report scoring info
638 $score = '';
639 } else {
640 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
641 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
642 . ' - ';
645 // format description
646 $byteSize = $result->getByteSize();
647 $wordCount = $result->getWordCount();
648 $timestamp = $result->getTimestamp();
649 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
650 ->numParams( $wordCount )->escaped();
652 if ( $t->getNamespace() == NS_CATEGORY ) {
653 $cat = Category::newFromTitle( $t );
654 $size = $this->msg( 'search-result-category-size' )
655 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
656 ->escaped();
659 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
661 // link to related articles if supported
662 $related = '';
663 if ( $result->hasRelated() ) {
664 $st = SpecialPage::getTitleFor( 'Search' );
665 $stParams = array_merge(
666 $this->powerSearchOptions(),
667 array(
668 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
669 ':' . $t->getPrefixedText(),
670 'fulltext' => $this->msg( 'search' )->text()
674 $related = ' -- ' . Linker::linkKnown(
675 $st,
676 $this->msg( 'search-relatedarticle' )->text(),
677 array(),
678 $stParams
682 // Include a thumbnail for media files...
683 if ( $t->getNamespace() == NS_FILE ) {
684 $img = wfFindFile( $t );
685 if ( $img ) {
686 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
687 if ( $thumb ) {
688 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
689 wfProfileOut( __METHOD__ );
690 // Float doesn't seem to interact well with the bullets.
691 // Table messes up vertical alignment of the bullets.
692 // Bullets are therefore disabled (didn't look great anyway).
693 return "<li>" .
694 '<table class="searchResultImage">' .
695 '<tr>' .
696 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
697 $thumb->toHtml( array( 'desc-link' => true ) ) .
698 '</td>' .
699 '<td style="vertical-align: top;">' .
700 $link .
701 $extract .
702 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
703 '</td>' .
704 '</tr>' .
705 '</table>' .
706 "</li>\n";
711 $html = null;
713 if ( wfRunHooks( 'ShowSearchHit', array(
714 $this, $result, $terms,
715 &$link, &$redirect, &$section, &$extract,
716 &$score, &$size, &$date, &$related,
717 &$html
718 ) ) ) {
719 $html = "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
720 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
721 "</li>\n";
724 wfProfileOut( __METHOD__ );
725 return $html;
729 * Show results from other wikis
731 * @param $matches SearchResultSet
732 * @param $query String
734 * @return string
736 protected function showInterwiki( &$matches, $query ) {
737 global $wgContLang;
738 wfProfileIn( __METHOD__ );
739 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
741 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
742 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
743 $out .= "<ul class='mw-search-iwresults'>\n";
745 // work out custom project captions
746 $customCaptions = array();
747 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() ); // format per line <iwprefix>:<caption>
748 foreach ( $customLines as $line ) {
749 $parts = explode( ":", $line, 2 );
750 if ( count( $parts ) == 2 ) { // validate line
751 $customCaptions[$parts[0]] = $parts[1];
755 $prev = null;
756 $result = $matches->next();
757 while ( $result ) {
758 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
759 $prev = $result->getInterwikiPrefix();
760 $result = $matches->next();
762 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
763 $out .= "</ul></div>\n";
765 // convert the whole thing to desired language variant
766 $out = $wgContLang->convert( $out );
767 wfProfileOut( __METHOD__ );
768 return $out;
772 * Show single interwiki link
774 * @param $result SearchResult
775 * @param $lastInterwiki String
776 * @param $terms Array
777 * @param $query String
778 * @param array $customCaptions iw prefix -> caption
780 * @return string
782 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions ) {
783 wfProfileIn( __METHOD__ );
785 if ( $result->isBrokenTitle() ) {
786 wfProfileOut( __METHOD__ );
787 return "<!-- Broken link in search result -->\n";
790 $t = $result->getTitle();
792 $titleSnippet = $result->getTitleSnippet( $terms );
794 if ( $titleSnippet == '' ) {
795 $titleSnippet = null;
798 $link = Linker::linkKnown(
800 $titleSnippet
803 // format redirect if any
804 $redirectTitle = $result->getRedirectTitle();
805 $redirectText = $result->getRedirectSnippet( $terms );
806 $redirect = '';
807 if ( !is_null( $redirectTitle ) ) {
808 if ( $redirectText == '' ) {
809 $redirectText = null;
812 $redirect = "<span class='searchalttitle'>" .
813 $this->msg( 'search-redirect' )->rawParams(
814 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
815 "</span>";
818 $out = "";
819 // display project name
820 if ( is_null( $lastInterwiki ) || $lastInterwiki != $t->getInterwiki() ) {
821 if ( array_key_exists( $t->getInterwiki(), $customCaptions ) ) {
822 // captions from 'search-interwiki-custom'
823 $caption = $customCaptions[$t->getInterwiki()];
824 } else {
825 // default is to show the hostname of the other wiki which might suck
826 // if there are many wikis on one hostname
827 $parsed = wfParseUrl( $t->getFullURL() );
828 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
830 // "more results" link (special page stuff could be localized, but we might not know target lang)
831 $searchTitle = Title::newFromText( $t->getInterwiki() . ":Special:Search" );
832 $searchLink = Linker::linkKnown(
833 $searchTitle,
834 $this->msg( 'search-interwiki-more' )->text(),
835 array(),
836 array(
837 'search' => $query,
838 'fulltext' => 'Search'
841 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
842 {$searchLink}</span>{$caption}</div>\n<ul>";
845 $out .= "<li>{$link} {$redirect}</li>\n";
846 wfProfileOut( __METHOD__ );
847 return $out;
851 * @param $profile
852 * @param $term
853 * @return String
855 protected function getProfileForm( $profile, $term ) {
856 // Hidden stuff
857 $opts = array();
858 $opts['redirs'] = $this->searchRedirects;
859 $opts['profile'] = $this->profile;
861 if ( $profile === 'advanced' ) {
862 return $this->powerSearchBox( $term, $opts );
863 } else {
864 $form = '';
865 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
866 return $form;
871 * Generates the power search box at [[Special:Search]]
873 * @param string $term search term
874 * @param $opts array
875 * @return String: HTML form
877 protected function powerSearchBox( $term, $opts ) {
878 // Groups namespaces into rows according to subject
879 $rows = array();
880 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
881 $subject = MWNamespace::getSubject( $namespace );
882 if ( !array_key_exists( $subject, $rows ) ) {
883 $rows[$subject] = "";
885 $name = str_replace( '_', ' ', $name );
886 if ( $name == '' ) {
887 $name = $this->msg( 'blanknamespace' )->text();
889 $rows[$subject] .=
890 Xml::openElement(
891 'td', array( 'style' => 'white-space: nowrap' )
893 Xml::checkLabel(
894 $name,
895 "ns{$namespace}",
896 "mw-search-ns{$namespace}",
897 in_array( $namespace, $this->namespaces )
899 Xml::closeElement( 'td' );
901 $rows = array_values( $rows );
902 $numRows = count( $rows );
904 // Lays out namespaces in multiple floating two-column tables so they'll
905 // be arranged nicely while still accommodating different screen widths
906 $namespaceTables = '';
907 for ( $i = 0; $i < $numRows; $i += 4 ) {
908 $namespaceTables .= Xml::openElement(
909 'table',
910 array( 'cellpadding' => 0, 'cellspacing' => 0 )
912 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
913 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
915 $namespaceTables .= Xml::closeElement( 'table' );
918 $showSections = array( 'namespaceTables' => $namespaceTables );
920 // Show redirects check only if backend supports it
921 if ( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
922 $showSections['redirects'] =
923 Xml::checkLabel( $this->msg( 'powersearch-redir' )->text(), 'redirs', 'redirs', $this->searchRedirects );
926 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
928 $hidden = '';
929 unset( $opts['redirs'] );
930 foreach ( $opts as $key => $value ) {
931 $hidden .= Html::hidden( $key, $value );
933 // Return final output
934 return Xml::openElement(
935 'fieldset',
936 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
938 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
939 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
940 Html::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
941 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
942 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
943 $hidden .
944 Xml::closeElement( 'fieldset' );
948 * @return array
950 protected function getSearchProfiles() {
951 // Builds list of Search Types (profiles)
952 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
954 $profiles = array(
955 'default' => array(
956 'message' => 'searchprofile-articles',
957 'tooltip' => 'searchprofile-articles-tooltip',
958 'namespaces' => SearchEngine::defaultNamespaces(),
959 'namespace-messages' => SearchEngine::namespacesAsText(
960 SearchEngine::defaultNamespaces()
963 'images' => array(
964 'message' => 'searchprofile-images',
965 'tooltip' => 'searchprofile-images-tooltip',
966 'namespaces' => array( NS_FILE ),
968 'help' => array(
969 'message' => 'searchprofile-project',
970 'tooltip' => 'searchprofile-project-tooltip',
971 'namespaces' => SearchEngine::helpNamespaces(),
972 'namespace-messages' => SearchEngine::namespacesAsText(
973 SearchEngine::helpNamespaces()
976 'all' => array(
977 'message' => 'searchprofile-everything',
978 'tooltip' => 'searchprofile-everything-tooltip',
979 'namespaces' => $nsAllSet,
981 'advanced' => array(
982 'message' => 'searchprofile-advanced',
983 'tooltip' => 'searchprofile-advanced-tooltip',
984 'namespaces' => self::NAMESPACES_CURRENT,
988 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
990 foreach ( $profiles as &$data ) {
991 if ( !is_array( $data['namespaces'] ) ) {
992 continue;
994 sort( $data['namespaces'] );
997 return $profiles;
1001 * @param $term
1002 * @param $resultsShown
1003 * @param $totalNum
1004 * @return string
1006 protected function formHeader( $term, $resultsShown, $totalNum ) {
1007 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1009 $bareterm = $term;
1010 if ( $this->startsWithImage( $term ) ) {
1011 // Deletes prefixes
1012 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1015 $profiles = $this->getSearchProfiles();
1016 $lang = $this->getLanguage();
1018 // Outputs XML for Search Types
1019 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1020 $out .= Xml::openElement( 'ul' );
1021 foreach ( $profiles as $id => $profile ) {
1022 if ( !isset( $profile['parameters'] ) ) {
1023 $profile['parameters'] = array();
1025 $profile['parameters']['profile'] = $id;
1027 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1028 $lang->commaList( $profile['namespace-messages'] ) : null;
1029 $out .= Xml::tags(
1030 'li',
1031 array(
1032 'class' => $this->profile === $id ? 'current' : 'normal'
1034 $this->makeSearchLink(
1035 $bareterm,
1036 array(),
1037 $this->msg( $profile['message'] )->text(),
1038 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1039 $profile['parameters']
1043 $out .= Xml::closeElement( 'ul' );
1044 $out .= Xml::closeElement( 'div' );
1046 // Results-info
1047 if ( $resultsShown > 0 ) {
1048 if ( $totalNum > 0 ) {
1049 $top = $this->msg( 'showingresultsheader' )
1050 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1051 ->params( wfEscapeWikiText( $term ) )
1052 ->numParams( $resultsShown )
1053 ->parse();
1054 } elseif ( $resultsShown >= $this->limit ) {
1055 $top = $this->msg( 'showingresults' )
1056 ->numParams( $this->limit, $this->offset + 1 )
1057 ->parse();
1058 } else {
1059 $top = $this->msg( 'showingresultsnum' )
1060 ->numParams( $this->limit, $this->offset + 1, $resultsShown )
1061 ->parse();
1063 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
1064 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
1068 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1069 $out .= Xml::closeElement( 'div' );
1071 return $out;
1075 * @param $term string
1076 * @return string
1078 protected function shortDialog( $term ) {
1079 $out = Html::hidden( 'title', $this->getTitle()->getPrefixedText() );
1080 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1081 // Term box
1082 $out .= Html::input( 'search', $term, 'search', array(
1083 'id' => $this->profile === 'advanced' ? 'powerSearchText' : 'searchText',
1084 'size' => '50',
1085 'autofocus'
1086 ) ) . "\n";
1087 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1088 $out .= Xml::submitButton( $this->msg( 'searchbutton' )->text() ) . "\n";
1089 return $out . $this->didYouMeanHtml;
1093 * Make a search link with some target namespaces
1095 * @param $term String
1096 * @param array $namespaces ignored
1097 * @param string $label link's text
1098 * @param string $tooltip link's tooltip
1099 * @param array $params query string parameters
1100 * @return String: HTML fragment
1102 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1103 $opt = $params;
1104 foreach ( $namespaces as $n ) {
1105 $opt['ns' . $n] = 1;
1107 $opt['redirs'] = $this->searchRedirects;
1109 $stParams = array_merge(
1110 array(
1111 'search' => $term,
1112 'fulltext' => $this->msg( 'search' )->text()
1114 $opt
1117 return Xml::element(
1118 'a',
1119 array(
1120 'href' => $this->getTitle()->getLocalURL( $stParams ),
1121 'title' => $tooltip
1123 $label
1128 * Check if query starts with image: prefix
1130 * @param string $term the string to check
1131 * @return Boolean
1133 protected function startsWithImage( $term ) {
1134 global $wgContLang;
1136 $p = explode( ':', $term );
1137 if ( count( $p ) > 1 ) {
1138 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
1140 return false;
1144 * Check if query starts with all: prefix
1146 * @param string $term the string to check
1147 * @return Boolean
1149 protected function startsWithAll( $term ) {
1151 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1153 $p = explode( ':', $term );
1154 if ( count( $p ) > 1 ) {
1155 return $p[0] == $allkeyword;
1157 return false;
1161 * @since 1.18
1163 * @return SearchEngine
1165 public function getSearchEngine() {
1166 if ( $this->searchEngine === null ) {
1167 $this->searchEngine = SearchEngine::create();
1169 return $this->searchEngine;
1173 * Users of hook SpecialSearchSetupEngine can use this to
1174 * add more params to links to not lose selection when
1175 * user navigates search results.
1176 * @since 1.18
1178 * @param $key
1179 * @param $value
1181 public function setExtraParam( $key, $value ) {
1182 $this->extraParams[$key] = $value;
1185 protected function getGroupName() {
1186 return 'pages';