wfMsgForContentNoTrans() was removed
[mediawiki.git] / includes / specials / SpecialSearch.php
blob8809900eb502024c6fdd50af241d2452f2e1a6c2
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, discussions...)
34 * For users tt replaces the set of enabled namespaces from the query
35 * string when applicable. Extensions can add new profiles with hooks
36 * with custom search options just for that profile.
37 * @var null|string
39 protected $profile;
41 /** @var SearchEngine Search engine */
42 protected $searchEngine;
44 /** @var string Search engine type, if not default */
45 protected $searchEngineType;
47 /** @var array For links */
48 protected $extraParams = array();
50 /**
51 * @var string The prefix url parameter. Set on the searcher and the
52 * is expected to treat it as prefix filter on titles.
54 protected $mPrefix;
56 /**
57 * @var int
59 protected $limit, $offset;
61 /**
62 * @var array
64 protected $namespaces;
66 /**
67 * @var string
69 protected $fulltext;
71 /**
72 * @var bool
74 protected $runSuggestion = true;
76 /**
77 * Names of the wikis, in format: Interwiki prefix -> caption
78 * @var array
80 protected $customCaptions;
82 const NAMESPACES_CURRENT = 'sense';
84 public function __construct() {
85 parent::__construct( 'Search' );
88 /**
89 * Entry point
91 * @param string $par
93 public function execute( $par ) {
94 $this->setHeaders();
95 $this->outputHeader();
96 $out = $this->getOutput();
97 $out->allowClickjacking();
98 $out->addModuleStyles( array(
99 'mediawiki.special', 'mediawiki.special.search', 'mediawiki.ui', 'mediawiki.ui.button',
100 'mediawiki.ui.input',
101 ) );
102 $this->addHelpLink( 'Help:Searching' );
104 // Strip underscores from title parameter; most of the time we'll want
105 // text form here. But don't strip underscores from actual text params!
106 $titleParam = str_replace( '_', ' ', $par );
108 $request = $this->getRequest();
110 // Fetch the search term
111 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
113 $this->load();
114 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
115 $this->saveNamespaces();
116 // Remove the token from the URL to prevent the user from inadvertently
117 // exposing it (e.g. by pasting it into a public wiki page) or undoing
118 // later settings changes (e.g. by reloading the page).
119 $query = $request->getValues();
120 unset( $query['title'], $query['nsRemember'] );
121 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
122 return;
125 $out->addJsConfigVars( array( 'searchTerm' => $search ) );
126 $this->searchEngineType = $request->getVal( 'srbackend' );
128 if ( $request->getVal( 'fulltext' )
129 || !is_null( $request->getVal( 'offset' ) )
131 $this->showResults( $search );
132 } else {
133 $this->goResult( $search );
138 * Set up basic search parameters from the request and user settings.
140 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
142 public function load() {
143 $request = $this->getRequest();
144 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, '' );
145 $this->mPrefix = $request->getVal( 'prefix', '' );
147 $user = $this->getUser();
149 # Extract manually requested namespaces
150 $nslist = $this->powerSearch( $request );
151 if ( !count( $nslist ) ) {
152 # Fallback to user preference
153 $nslist = SearchEngine::userNamespaces( $user );
156 $profile = null;
157 if ( !count( $nslist ) ) {
158 $profile = 'default';
161 $profile = $request->getVal( 'profile', $profile );
162 $profiles = $this->getSearchProfiles();
163 if ( $profile === null ) {
164 // BC with old request format
165 $profile = 'advanced';
166 foreach ( $profiles as $key => $data ) {
167 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
168 $profile = $key;
171 $this->namespaces = $nslist;
172 } elseif ( $profile === 'advanced' ) {
173 $this->namespaces = $nslist;
174 } else {
175 if ( isset( $profiles[$profile]['namespaces'] ) ) {
176 $this->namespaces = $profiles[$profile]['namespaces'];
177 } else {
178 // Unknown profile requested
179 $profile = 'default';
180 $this->namespaces = $profiles['default']['namespaces'];
184 $this->fulltext = $request->getVal( 'fulltext' );
185 $this->runSuggestion = (bool)$request->getVal( 'runsuggestion', true );
186 $this->profile = $profile;
190 * If an exact title match can be found, jump straight ahead to it.
192 * @param string $term
194 public function goResult( $term ) {
195 $this->setupPage( $term );
196 # Try to go to page as entered.
197 $title = Title::newFromText( $term );
198 # If the string cannot be used to create a title
199 if ( is_null( $title ) ) {
200 $this->showResults( $term );
202 return;
204 # If there's an exact or very near match, jump right there.
205 $title = SearchEngine::getNearMatch( $term );
207 if ( !is_null( $title ) ) {
208 $this->getOutput()->redirect( $title->getFullURL() );
210 return;
212 # No match, generate an edit URL
213 $title = Title::newFromText( $term );
214 if ( !is_null( $title ) ) {
215 Hooks::run( 'SpecialSearchNogomatch', array( &$title ) );
217 $this->showResults( $term );
221 * @param string $term
223 public function showResults( $term ) {
224 global $wgContLang;
226 $search = $this->getSearchEngine();
227 $search->setFeatureData( 'rewrite', $this->runSuggestion );
228 $search->setLimitOffset( $this->limit, $this->offset );
229 $search->setNamespaces( $this->namespaces );
230 $search->prefix = $this->mPrefix;
231 $term = $search->transformSearchTerm( $term );
233 Hooks::run( 'SpecialSearchSetupEngine', array( $this, $this->profile, $search ) );
235 $this->setupPage( $term );
237 $out = $this->getOutput();
239 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
240 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
241 if ( $searchFowardUrl ) {
242 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
243 $out->redirect( $url );
244 } else {
245 $out->addHTML(
246 Xml::openElement( 'fieldset' ) .
247 Xml::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
248 Xml::element(
249 'p',
250 array( 'class' => 'mw-searchdisabled' ),
251 $this->msg( 'searchdisabled' )->text()
253 $this->msg( 'googlesearch' )->rawParams(
254 htmlspecialchars( $term ),
255 'UTF-8',
256 $this->msg( 'searchbutton' )->escaped()
257 )->text() .
258 Xml::closeElement( 'fieldset' )
262 return;
265 $title = Title::newFromText( $term );
266 $showSuggestion = $title === null || !$title->isKnown();
267 $search->setShowSuggestion( $showSuggestion );
269 // fetch search results
270 $rewritten = $search->replacePrefixes( $term );
272 $titleMatches = $search->searchTitle( $rewritten );
273 $textMatches = $search->searchText( $rewritten );
275 $textStatus = null;
276 if ( $textMatches instanceof Status ) {
277 $textStatus = $textMatches;
278 $textMatches = null;
281 // did you mean... suggestions
282 $didYouMeanHtml = '';
283 if ( $showSuggestion && $textMatches && !$textStatus ) {
284 if ( $textMatches->hasRewrittenQuery() ) {
285 $didYouMeanHtml = $this->getDidYouMeanRewrittenHtml( $term, $textMatches );
286 } elseif ( $textMatches->hasSuggestion() ) {
287 $didYouMeanHtml = $this->getDidYouMeanHtml( $textMatches );
291 if ( !Hooks::run( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
292 # Hook requested termination
293 return;
296 // start rendering the page
297 $out->addHtml(
298 Xml::openElement(
299 'form',
300 array(
301 'id' => ( $this->isPowerSearch() ? 'powersearch' : 'search' ),
302 'method' => 'get',
303 'action' => wfScript(),
308 // Get number of results
309 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
310 if ( $titleMatches ) {
311 $titleMatchesNum = $titleMatches->numRows();
312 $numTitleMatches = $titleMatches->getTotalHits();
314 if ( $textMatches ) {
315 $textMatchesNum = $textMatches->numRows();
316 $numTextMatches = $textMatches->getTotalHits();
318 $num = $titleMatchesNum + $textMatchesNum;
319 $totalRes = $numTitleMatches + $numTextMatches;
321 $out->addHtml(
322 # This is an awful awful ID name. It's not a table, but we
323 # named it poorly from when this was a table so now we're
324 # stuck with it
325 Xml::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
326 $this->shortDialog( $term, $num, $totalRes ) .
327 Xml::closeElement( 'div' ) .
328 $this->searchProfileTabs( $term ) .
329 $this->searchOptions( $term ) .
330 Xml::closeElement( 'form' ) .
331 $didYouMeanHtml
334 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
335 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
336 // Empty query -- straight view of search form
337 return;
340 $out->addHtml( "<div class='searchresults'>" );
342 // prev/next links
343 $prevnext = null;
344 if ( $num || $this->offset ) {
345 // Show the create link ahead
346 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
347 if ( $totalRes > $this->limit || $this->offset ) {
348 if ( $this->searchEngineType !== null ) {
349 $this->setExtraParam( 'srbackend', $this->searchEngineType );
351 $prevnext = $this->getLanguage()->viewPrevNext(
352 $this->getPageTitle(),
353 $this->offset,
354 $this->limit,
355 $this->powerSearchOptions() + array( 'search' => $term ),
356 $this->limit + $this->offset >= $totalRes
360 Hooks::run( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
362 $out->parserOptions()->setEditSection( false );
363 if ( $titleMatches ) {
364 if ( $numTitleMatches > 0 ) {
365 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
366 $out->addHTML( $this->showMatches( $titleMatches ) );
368 $titleMatches->free();
370 if ( $textMatches && !$textStatus ) {
371 // output appropriate heading
372 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
373 // if no title matches the heading is redundant
374 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
377 // show results
378 if ( $numTextMatches > 0 ) {
379 $out->addHTML( $this->showMatches( $textMatches ) );
382 // show secondary interwiki results if any
383 if ( $textMatches->hasInterwikiResults( SearchResultSet::SECONDARY_RESULTS ) ) {
384 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(
385 SearchResultSet::SECONDARY_RESULTS ), $term ) );
389 $hasOtherResults = $textMatches &&
390 $textMatches->hasInterwikiResults( SearchResultSet::INLINE_RESULTS );
392 if ( $num === 0 ) {
393 if ( $textStatus ) {
394 $out->addHTML( '<div class="error">' .
395 $textStatus->getMessage( 'search-error' ) . '</div>' );
396 } else {
397 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
398 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
399 array( $hasOtherResults ? 'search-nonefound-thiswiki' : 'search-nonefound',
400 wfEscapeWikiText( $term )
401 ) );
405 if ( $hasOtherResults ) {
406 foreach ( $textMatches->getInterwikiResults( SearchResultSet::INLINE_RESULTS )
407 as $interwiki => $interwikiResult ) {
408 if ( $interwikiResult instanceof Status || $interwikiResult->numRows() == 0 ) {
409 // ignore bad interwikis for now
410 continue;
412 // TODO: wiki header
413 $out->addHTML( $this->showMatches( $interwikiResult, $interwiki ) );
417 if ( $textMatches ) {
418 $textMatches->free();
421 $out->addHTML( '<div class="visualClear"></div>' );
423 if ( $prevnext ) {
424 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
427 $out->addHtml( "</div>" );
429 Hooks::run( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
434 * Produce wiki header for interwiki results
435 * @param string $interwiki Interwiki name
436 * @param SearchResultSet $interwikiResult The result set
437 * @return string
439 protected function interwikiHeader( $interwiki, $interwikiResult ) {
440 // TODO: we need to figure out how to name wikis correctly
441 $wikiMsg = $this->msg( 'search-interwiki-results-' . $interwiki )->parse();
442 return "<p class=\"mw-search-interwiki-header\">\n$wikiMsg</p>";
446 * Decide if the suggested query should be run, and it's results returned
447 * instead of the provided $textMatches
449 * @param SearchResultSet $textMatches The results of a users query
450 * @return bool
452 protected function shouldRunSuggestedQuery( SearchResultSet $textMatches ) {
453 if ( !$this->runSuggestion ||
454 !$textMatches->hasSuggestion() ||
455 $textMatches->numRows() > 0 ||
456 $textMatches->searchContainedSyntax()
458 return false;
461 return $this->getConfig()->get( 'SearchRunSuggestedQuery' );
465 * Generates HTML shown to the user when we have a suggestion about a query
466 * that might give more results than their current query.
468 protected function getDidYouMeanHtml( SearchResultSet $textMatches ) {
469 # mirror Go/Search behavior of original request ..
470 $params = array( 'search' => $textMatches->getSuggestionQuery() );
471 if ( $this->fulltext != null ) {
472 $params['fulltext'] = $this->fulltext;
474 $stParams = array_merge( $params, $this->powerSearchOptions() );
476 $suggest = Linker::linkKnown(
477 $this->getPageTitle(),
478 $textMatches->getSuggestionSnippet() ?: null,
479 array( 'id' => 'mw-search-DYM-suggestion' ),
480 $stParams
483 # HTML of did you mean... search suggestion link
484 return Html::rawElement(
485 'div',
486 array( 'class' => 'searchdidyoumean' ),
487 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
492 * Generates HTML shown to user when their query has been internally rewritten,
493 * and the results of the rewritten query are being returned.
495 * @param string $term The users search input
496 * @param SearchResultSet $textMatches The response to the users initial search request
497 * @return string HTML linking the user to their original $term query, and the one
498 * suggested by $textMatches.
500 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet $textMatches ) {
501 // Showing results for '$rewritten'
502 // Search instead for '$orig'
504 $params = array( 'search' => $textMatches->getQueryAfterRewrite() );
505 if ( $this->fulltext != null ) {
506 $params['fulltext'] = $this->fulltext;
508 $stParams = array_merge( $params, $this->powerSearchOptions() );
510 $rewritten = Linker::linkKnown(
511 $this->getPageTitle(),
512 $textMatches->getQueryAfterRewriteSnippet() ?: null,
513 array( 'id' => 'mw-search-DYM-rewritten' ),
514 $stParams
517 $stParams['search'] = $term;
518 $stParams['runsuggestion'] = 0;
519 $original = Linker::linkKnown(
520 $this->getPageTitle(),
521 htmlspecialchars( $term ),
522 array( 'id' => 'mw-search-DYM-original' ),
523 $stParams
526 return Html::rawElement(
527 'div',
528 array( 'class' => 'searchdidyoumean' ),
529 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
534 * @param Title $title
535 * @param int $num The number of search results found
536 * @param null|SearchResultSet $titleMatches Results from title search
537 * @param null|SearchResultSet $textMatches Results from text search
539 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
540 // show direct page/create link if applicable
542 // Check DBkey !== '' in case of fragment link only.
543 if ( is_null( $title ) || $title->getDBkey() === ''
544 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
545 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
547 // invalid title
548 // preserve the paragraph for margins etc...
549 $this->getOutput()->addHtml( '<p></p>' );
551 return;
554 $messageName = 'searchmenu-new-nocreate';
555 $linkClass = 'mw-search-createlink';
557 if ( !$title->isExternal() ) {
558 if ( $title->isKnown() ) {
559 $messageName = 'searchmenu-exists';
560 $linkClass = 'mw-search-exists';
561 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
562 $messageName = 'searchmenu-new';
566 $params = array(
567 $messageName,
568 wfEscapeWikiText( $title->getPrefixedText() ),
569 Message::numParam( $num )
571 Hooks::run( 'SpecialSearchCreateLink', array( $title, &$params ) );
573 // Extensions using the hook might still return an empty $messageName
574 if ( $messageName ) {
575 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
576 } else {
577 // preserve the paragraph for margins etc...
578 $this->getOutput()->addHtml( '<p></p>' );
583 * @param string $term
585 protected function setupPage( $term ) {
586 $out = $this->getOutput();
587 if ( strval( $term ) !== '' ) {
588 $out->setPageTitle( $this->msg( 'searchresults' ) );
589 $out->setHTMLTitle( $this->msg( 'pagetitle' )
590 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
591 ->inContentLanguage()->text()
594 // add javascript specific to special:search
595 $out->addModules( 'mediawiki.special.search' );
599 * Return true if current search is a power (advanced) search
601 * @return bool
603 protected function isPowerSearch() {
604 return $this->profile === 'advanced';
608 * Extract "power search" namespace settings from the request object,
609 * returning a list of index numbers to search.
611 * @param WebRequest $request
612 * @return array
614 protected function powerSearch( &$request ) {
615 $arr = array();
616 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
617 if ( $request->getCheck( 'ns' . $ns ) ) {
618 $arr[] = $ns;
622 return $arr;
626 * Reconstruct the 'power search' options for links
628 * @return array
630 protected function powerSearchOptions() {
631 $opt = array();
632 if ( !$this->isPowerSearch() ) {
633 $opt['profile'] = $this->profile;
634 } else {
635 foreach ( $this->namespaces as $n ) {
636 $opt['ns' . $n] = 1;
640 return $opt + $this->extraParams;
644 * Save namespace preferences when we're supposed to
646 * @return bool Whether we wrote something
648 protected function saveNamespaces() {
649 $user = $this->getUser();
650 $request = $this->getRequest();
652 if ( $user->isLoggedIn() &&
653 $user->matchEditToken(
654 $request->getVal( 'nsRemember' ),
655 'searchnamespace',
656 $request
657 ) && !wfReadOnly()
659 // Reset namespace preferences: namespaces are not searched
660 // when they're not mentioned in the URL parameters.
661 foreach ( MWNamespace::getValidNamespaces() as $n ) {
662 $user->setOption( 'searchNs' . $n, false );
664 // The request parameters include all the namespaces to be searched.
665 // Even if they're the same as an existing profile, they're not eaten.
666 foreach ( $this->namespaces as $n ) {
667 $user->setOption( 'searchNs' . $n, true );
670 $user->saveSettings();
671 return true;
674 return false;
678 * Show whole set of results
680 * @param SearchResultSet $matches
681 * @param string $interwiki Interwiki name
683 * @return string
685 protected function showMatches( &$matches, $interwiki = null ) {
686 global $wgContLang;
688 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
689 $out = '';
690 $result = $matches->next();
691 $pos = $this->offset;
693 if ( $result && $interwiki ) {
694 $out .= $this->interwikiHeader( $interwiki, $result );
697 $out .= "<ul class='mw-search-results'>\n";
698 while ( $result ) {
699 $out .= $this->showHit( $result, $terms, ++$pos );
700 $result = $matches->next();
702 $out .= "</ul>\n";
704 // convert the whole thing to desired language variant
705 $out = $wgContLang->convert( $out );
707 return $out;
711 * Format a single hit result
713 * @param SearchResult $result
714 * @param array $terms Terms to highlight
715 * @param int $position Position within the search results, including offset.
717 * @return string
719 protected function showHit( $result, $terms, $position ) {
721 if ( $result->isBrokenTitle() ) {
722 return '';
725 $title = $result->getTitle();
727 $titleSnippet = $result->getTitleSnippet();
729 if ( $titleSnippet == '' ) {
730 $titleSnippet = null;
733 $link_t = clone $title;
734 $query = array();
736 Hooks::run( 'ShowSearchHitTitle',
737 array( &$link_t, &$titleSnippet, $result, $terms, $this, &$query ) );
739 $link = Linker::linkKnown(
740 $link_t,
741 $titleSnippet,
742 array( 'data-serp-pos' => $position ), // HTML attributes
743 $query
746 // If page content is not readable, just return the title.
747 // This is not quite safe, but better than showing excerpts from non-readable pages
748 // Note that hiding the entry entirely would screw up paging.
749 if ( !$title->userCan( 'read', $this->getUser() ) ) {
750 return "<li>{$link}</li>\n";
753 // If the page doesn't *exist*... our search index is out of date.
754 // The least confusing at this point is to drop the result.
755 // You may get less results, but... oh well. :P
756 if ( $result->isMissingRevision() ) {
757 return '';
760 // format redirects / relevant sections
761 $redirectTitle = $result->getRedirectTitle();
762 $redirectText = $result->getRedirectSnippet();
763 $sectionTitle = $result->getSectionTitle();
764 $sectionText = $result->getSectionSnippet();
765 $categorySnippet = $result->getCategorySnippet();
767 $redirect = '';
768 if ( !is_null( $redirectTitle ) ) {
769 if ( $redirectText == '' ) {
770 $redirectText = null;
773 $redirect = "<span class='searchalttitle'>" .
774 $this->msg( 'search-redirect' )->rawParams(
775 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
776 "</span>";
779 $section = '';
780 if ( !is_null( $sectionTitle ) ) {
781 if ( $sectionText == '' ) {
782 $sectionText = null;
785 $section = "<span class='searchalttitle'>" .
786 $this->msg( 'search-section' )->rawParams(
787 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
788 "</span>";
791 $category = '';
792 if ( $categorySnippet ) {
793 $category = "<span class='searchalttitle'>" .
794 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
795 "</span>";
798 // format text extract
799 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
801 $lang = $this->getLanguage();
803 // format description
804 $byteSize = $result->getByteSize();
805 $wordCount = $result->getWordCount();
806 $timestamp = $result->getTimestamp();
807 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
808 ->numParams( $wordCount )->escaped();
810 if ( $title->getNamespace() == NS_CATEGORY ) {
811 $cat = Category::newFromTitle( $title );
812 $size = $this->msg( 'search-result-category-size' )
813 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
814 ->escaped();
817 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
819 $fileMatch = '';
820 // Include a thumbnail for media files...
821 if ( $title->getNamespace() == NS_FILE ) {
822 $img = $result->getFile();
823 $img = $img ?: wfFindFile( $title );
824 if ( $result->isFileMatch() ) {
825 $fileMatch = "<span class='searchalttitle'>" .
826 $this->msg( 'search-file-match' )->escaped() . "</span>";
828 if ( $img ) {
829 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
830 if ( $thumb ) {
831 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
832 // Float doesn't seem to interact well with the bullets.
833 // Table messes up vertical alignment of the bullets.
834 // Bullets are therefore disabled (didn't look great anyway).
835 return "<li>" .
836 '<table class="searchResultImage">' .
837 '<tr>' .
838 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
839 $thumb->toHtml( array( 'desc-link' => true ) ) .
840 '</td>' .
841 '<td style="vertical-align: top;">' .
842 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
843 $extract .
844 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
845 '</td>' .
846 '</tr>' .
847 '</table>' .
848 "</li>\n";
853 $html = null;
855 $score = '';
856 $related = '';
857 if ( Hooks::run( 'ShowSearchHit', array(
858 $this, $result, $terms,
859 &$link, &$redirect, &$section, &$extract,
860 &$score, &$size, &$date, &$related,
861 &$html
862 ) ) ) {
863 $html = "<li><div class='mw-search-result-heading'>" .
864 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
865 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
866 "</li>\n";
869 return $html;
873 * Extract custom captions from search-interwiki-custom message
875 protected function getCustomCaptions() {
876 if ( is_null( $this->customCaptions ) ) {
877 $this->customCaptions = array();
878 // format per line <iwprefix>:<caption>
879 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
880 foreach ( $customLines as $line ) {
881 $parts = explode( ":", $line, 2 );
882 if ( count( $parts ) == 2 ) { // validate line
883 $this->customCaptions[$parts[0]] = $parts[1];
890 * Show results from other wikis
892 * @param SearchResultSet|array $matches
893 * @param string $query
895 * @return string
897 protected function showInterwiki( $matches, $query ) {
898 global $wgContLang;
900 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
901 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
902 $out .= "<ul class='mw-search-iwresults'>\n";
904 // work out custom project captions
905 $this->getCustomCaptions();
907 if ( !is_array( $matches ) ) {
908 $matches = array( $matches );
911 foreach ( $matches as $set ) {
912 $prev = null;
913 $result = $set->next();
914 while ( $result ) {
915 $out .= $this->showInterwikiHit( $result, $prev, $query );
916 $prev = $result->getInterwikiPrefix();
917 $result = $set->next();
921 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
922 $out .= "</ul></div>\n";
924 // convert the whole thing to desired language variant
925 $out = $wgContLang->convert( $out );
927 return $out;
931 * Show single interwiki link
933 * @param SearchResult $result
934 * @param string $lastInterwiki
935 * @param string $query
937 * @return string
939 protected function showInterwikiHit( $result, $lastInterwiki, $query ) {
941 if ( $result->isBrokenTitle() ) {
942 return '';
945 $title = $result->getTitle();
947 $titleSnippet = $result->getTitleSnippet();
949 if ( $titleSnippet == '' ) {
950 $titleSnippet = null;
953 $link = Linker::linkKnown(
954 $title,
955 $titleSnippet
958 // format redirect if any
959 $redirectTitle = $result->getRedirectTitle();
960 $redirectText = $result->getRedirectSnippet();
961 $redirect = '';
962 if ( !is_null( $redirectTitle ) ) {
963 if ( $redirectText == '' ) {
964 $redirectText = null;
967 $redirect = "<span class='searchalttitle'>" .
968 $this->msg( 'search-redirect' )->rawParams(
969 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
970 "</span>";
973 $out = "";
974 // display project name
975 if ( is_null( $lastInterwiki ) || $lastInterwiki != $title->getInterwiki() ) {
976 if ( array_key_exists( $title->getInterwiki(), $this->customCaptions ) ) {
977 // captions from 'search-interwiki-custom'
978 $caption = $this->customCaptions[$title->getInterwiki()];
979 } else {
980 // default is to show the hostname of the other wiki which might suck
981 // if there are many wikis on one hostname
982 $parsed = wfParseUrl( $title->getFullURL() );
983 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
985 // "more results" link (special page stuff could be localized, but we might not know target lang)
986 $searchTitle = Title::newFromText( $title->getInterwiki() . ":Special:Search" );
987 $searchLink = Linker::linkKnown(
988 $searchTitle,
989 $this->msg( 'search-interwiki-more' )->text(),
990 array(),
991 array(
992 'search' => $query,
993 'fulltext' => 'Search'
996 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
997 {$searchLink}</span>{$caption}</div>\n<ul>";
1000 $out .= "<li>{$link} {$redirect}</li>\n";
1002 return $out;
1006 * Generates the power search box at [[Special:Search]]
1008 * @param string $term Search term
1009 * @param array $opts
1010 * @return string HTML form
1012 protected function powerSearchBox( $term, $opts ) {
1013 global $wgContLang;
1015 // Groups namespaces into rows according to subject
1016 $rows = array();
1017 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
1018 $subject = MWNamespace::getSubject( $namespace );
1019 if ( !array_key_exists( $subject, $rows ) ) {
1020 $rows[$subject] = "";
1023 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
1024 if ( $name == '' ) {
1025 $name = $this->msg( 'blanknamespace' )->text();
1028 $rows[$subject] .=
1029 Xml::openElement( 'td' ) .
1030 Xml::checkLabel(
1031 $name,
1032 "ns{$namespace}",
1033 "mw-search-ns{$namespace}",
1034 in_array( $namespace, $this->namespaces )
1036 Xml::closeElement( 'td' );
1039 $rows = array_values( $rows );
1040 $numRows = count( $rows );
1042 // Lays out namespaces in multiple floating two-column tables so they'll
1043 // be arranged nicely while still accommodating different screen widths
1044 $namespaceTables = '';
1045 for ( $i = 0; $i < $numRows; $i += 4 ) {
1046 $namespaceTables .= Xml::openElement( 'table' );
1048 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
1049 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
1052 $namespaceTables .= Xml::closeElement( 'table' );
1055 $showSections = array( 'namespaceTables' => $namespaceTables );
1057 Hooks::run( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
1059 $hidden = '';
1060 foreach ( $opts as $key => $value ) {
1061 $hidden .= Html::hidden( $key, $value );
1064 # Stuff to feed saveNamespaces()
1065 $remember = '';
1066 $user = $this->getUser();
1067 if ( $user->isLoggedIn() ) {
1068 $remember .= Xml::checkLabel(
1069 $this->msg( 'powersearch-remember' )->text(),
1070 'nsRemember',
1071 'mw-search-powersearch-remember',
1072 false,
1073 // The token goes here rather than in a hidden field so it
1074 // is only sent when necessary (not every form submission).
1075 array( 'value' => $user->getEditToken(
1076 'searchnamespace',
1077 $this->getRequest()
1082 // Return final output
1083 return Xml::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
1084 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1085 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1086 Xml::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
1087 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
1088 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
1089 $hidden .
1090 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
1091 $remember .
1092 Xml::closeElement( 'fieldset' );
1096 * @return array
1098 protected function getSearchProfiles() {
1099 // Builds list of Search Types (profiles)
1100 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
1102 $profiles = array(
1103 'default' => array(
1104 'message' => 'searchprofile-articles',
1105 'tooltip' => 'searchprofile-articles-tooltip',
1106 'namespaces' => SearchEngine::defaultNamespaces(),
1107 'namespace-messages' => SearchEngine::namespacesAsText(
1108 SearchEngine::defaultNamespaces()
1111 'images' => array(
1112 'message' => 'searchprofile-images',
1113 'tooltip' => 'searchprofile-images-tooltip',
1114 'namespaces' => array( NS_FILE ),
1116 'all' => array(
1117 'message' => 'searchprofile-everything',
1118 'tooltip' => 'searchprofile-everything-tooltip',
1119 'namespaces' => $nsAllSet,
1121 'advanced' => array(
1122 'message' => 'searchprofile-advanced',
1123 'tooltip' => 'searchprofile-advanced-tooltip',
1124 'namespaces' => self::NAMESPACES_CURRENT,
1128 Hooks::run( 'SpecialSearchProfiles', array( &$profiles ) );
1130 foreach ( $profiles as &$data ) {
1131 if ( !is_array( $data['namespaces'] ) ) {
1132 continue;
1134 sort( $data['namespaces'] );
1137 return $profiles;
1141 * @param string $term
1142 * @return string
1144 protected function searchProfileTabs( $term ) {
1145 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-profile-tabs' ) );
1147 $bareterm = $term;
1148 if ( $this->startsWithImage( $term ) ) {
1149 // Deletes prefixes
1150 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1153 $profiles = $this->getSearchProfiles();
1154 $lang = $this->getLanguage();
1156 // Outputs XML for Search Types
1157 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1158 $out .= Xml::openElement( 'ul' );
1159 foreach ( $profiles as $id => $profile ) {
1160 if ( !isset( $profile['parameters'] ) ) {
1161 $profile['parameters'] = array();
1163 $profile['parameters']['profile'] = $id;
1165 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1166 $lang->commaList( $profile['namespace-messages'] ) : null;
1167 $out .= Xml::tags(
1168 'li',
1169 array(
1170 'class' => $this->profile === $id ? 'current' : 'normal'
1172 $this->makeSearchLink(
1173 $bareterm,
1174 array(),
1175 $this->msg( $profile['message'] )->text(),
1176 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1177 $profile['parameters']
1181 $out .= Xml::closeElement( 'ul' );
1182 $out .= Xml::closeElement( 'div' );
1183 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1184 $out .= Xml::closeElement( 'div' );
1186 return $out;
1190 * @param string $term Search term
1191 * @return string
1193 protected function searchOptions( $term ) {
1194 $out = '';
1195 $opts = array();
1196 $opts['profile'] = $this->profile;
1198 if ( $this->isPowerSearch() ) {
1199 $out .= $this->powerSearchBox( $term, $opts );
1200 } else {
1201 $form = '';
1202 Hooks::run( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile, $term, $opts ) );
1203 $out .= $form;
1206 return $out;
1210 * @param string $term
1211 * @param int $resultsShown
1212 * @param int $totalNum
1213 * @return string
1215 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1216 $out = Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1217 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1218 // Term box
1219 $out .= Html::input( 'search', $term, 'search', array(
1220 'id' => $this->isPowerSearch() ? 'powerSearchText' : 'searchText',
1221 'size' => '50',
1222 'autofocus' => trim( $term ) === '',
1223 'class' => 'mw-ui-input mw-ui-input-inline',
1224 ) ) . "\n";
1225 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1226 $out .= Html::submitButton(
1227 $this->msg( 'searchbutton' )->text(),
1228 array( 'class' => 'mw-ui-button mw-ui-progressive' ),
1229 array( 'mw-ui-progressive' )
1230 ) . "\n";
1232 // Results-info
1233 if ( $totalNum > 0 && $this->offset < $totalNum ) {
1234 $top = $this->msg( 'search-showingresults' )
1235 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1236 ->numParams( $resultsShown )
1237 ->parse();
1238 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1239 Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1242 return $out;
1246 * Make a search link with some target namespaces
1248 * @param string $term
1249 * @param array $namespaces Ignored
1250 * @param string $label Link's text
1251 * @param string $tooltip Link's tooltip
1252 * @param array $params Query string parameters
1253 * @return string HTML fragment
1255 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1256 $opt = $params;
1257 foreach ( $namespaces as $n ) {
1258 $opt['ns' . $n] = 1;
1261 $stParams = array_merge(
1262 array(
1263 'search' => $term,
1264 'fulltext' => $this->msg( 'search' )->text()
1266 $opt
1269 return Xml::element(
1270 'a',
1271 array(
1272 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1273 'title' => $tooltip
1275 $label
1280 * Check if query starts with image: prefix
1282 * @param string $term The string to check
1283 * @return bool
1285 protected function startsWithImage( $term ) {
1286 global $wgContLang;
1288 $parts = explode( ':', $term );
1289 if ( count( $parts ) > 1 ) {
1290 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1293 return false;
1297 * Check if query starts with all: prefix
1299 * @param string $term The string to check
1300 * @return bool
1302 protected function startsWithAll( $term ) {
1304 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1306 $parts = explode( ':', $term );
1307 if ( count( $parts ) > 1 ) {
1308 return $parts[0] == $allkeyword;
1311 return false;
1315 * @since 1.18
1317 * @return SearchEngine
1319 public function getSearchEngine() {
1320 if ( $this->searchEngine === null ) {
1321 $this->searchEngine = $this->searchEngineType ?
1322 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1325 return $this->searchEngine;
1329 * Current search profile.
1330 * @return null|string
1332 function getProfile() {
1333 return $this->profile;
1337 * Current namespaces.
1338 * @return array
1340 function getNamespaces() {
1341 return $this->namespaces;
1345 * Users of hook SpecialSearchSetupEngine can use this to
1346 * add more params to links to not lose selection when
1347 * user navigates search results.
1348 * @since 1.18
1350 * @param string $key
1351 * @param mixed $value
1353 public function setExtraParam( $key, $value ) {
1354 $this->extraParams[$key] = $value;
1357 protected function getGroupName() {
1358 return 'pages';