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
23 * @ingroup SpecialPage
26 use MediaWiki\MediaWikiServices
;
29 * implements Special:Search - Run text & title search and display the output
30 * @ingroup SpecialPage
32 class SpecialSearch
extends SpecialPage
{
34 * Current search profile. Search profile is just a name that identifies
35 * the active search tab on the search page (content, discussions...)
36 * For users tt replaces the set of enabled namespaces from the query
37 * string when applicable. Extensions can add new profiles with hooks
38 * with custom search options just for that profile.
43 /** @var SearchEngine Search engine */
44 protected $searchEngine;
46 /** @var string Search engine type, if not default */
47 protected $searchEngineType;
49 /** @var array For links */
50 protected $extraParams = [];
53 * @var string The prefix url parameter. Set on the searcher and the
54 * is expected to treat it as prefix filter on titles.
61 protected $limit, $offset;
66 protected $namespaces;
76 protected $runSuggestion = true;
79 * Names of the wikis, in format: Interwiki prefix -> caption
82 protected $customCaptions;
85 * Search engine configurations.
86 * @var SearchEngineConfig
88 protected $searchConfig;
90 const NAMESPACES_CURRENT
= 'sense';
92 public function __construct() {
93 parent
::__construct( 'Search' );
94 $this->searchConfig
= MediaWikiServices
::getInstance()->getSearchEngineConfig();
102 public function execute( $par ) {
103 $request = $this->getRequest();
105 // Fetch the search term
106 $search = str_replace( "\n", " ", $request->getText( 'search' ) );
108 // Historically search terms have been accepted not only in the search query
109 // parameter, but also as part of the primary url. This can have PII implications
110 // in releasing page view data. As such issue a 301 redirect to the correct
112 if ( strlen( $par ) && !strlen( $search ) ) {
113 $query = $request->getValues();
114 unset( $query['title'] );
115 // Strip underscores from title parameter; most of the time we'll want
116 // text form here. But don't strip underscores from actual text params!
117 $query['search'] = str_replace( '_', ' ', $par );
118 $this->getOutput()->redirect( $this->getPageTitle()->getFullURL( $query ), 301 );
123 $this->outputHeader();
124 $out = $this->getOutput();
125 $out->allowClickjacking();
126 $out->addModuleStyles( [
127 'mediawiki.special', 'mediawiki.special.search.styles', 'mediawiki.ui', 'mediawiki.ui.button',
128 'mediawiki.ui.input', 'mediawiki.widgets.SearchInputWidget.styles',
130 $this->addHelpLink( 'Help:Searching' );
133 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
134 $this->saveNamespaces();
135 // Remove the token from the URL to prevent the user from inadvertently
136 // exposing it (e.g. by pasting it into a public wiki page) or undoing
137 // later settings changes (e.g. by reloading the page).
138 $query = $request->getValues();
139 unset( $query['title'], $query['nsRemember'] );
140 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
144 $out->addJsConfigVars( [ 'searchTerm' => $search ] );
145 $this->searchEngineType
= $request->getVal( 'srbackend' );
147 if ( $request->getVal( 'fulltext' )
148 ||
!is_null( $request->getVal( 'offset' ) )
150 $this->showResults( $search );
152 $this->goResult( $search );
157 * Set up basic search parameters from the request and user settings.
159 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
161 public function load() {
162 $request = $this->getRequest();
163 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, '' );
164 $this->mPrefix
= $request->getVal( 'prefix', '' );
166 $user = $this->getUser();
168 # Extract manually requested namespaces
169 $nslist = $this->powerSearch( $request );
170 if ( !count( $nslist ) ) {
171 # Fallback to user preference
172 $nslist = $this->searchConfig
->userNamespaces( $user );
176 if ( !count( $nslist ) ) {
177 $profile = 'default';
180 $profile = $request->getVal( 'profile', $profile );
181 $profiles = $this->getSearchProfiles();
182 if ( $profile === null ) {
183 // BC with old request format
184 $profile = 'advanced';
185 foreach ( $profiles as $key => $data ) {
186 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
190 $this->namespaces
= $nslist;
191 } elseif ( $profile === 'advanced' ) {
192 $this->namespaces
= $nslist;
194 if ( isset( $profiles[$profile]['namespaces'] ) ) {
195 $this->namespaces
= $profiles[$profile]['namespaces'];
197 // Unknown profile requested
198 $profile = 'default';
199 $this->namespaces
= $profiles['default']['namespaces'];
203 $this->fulltext
= $request->getVal( 'fulltext' );
204 $this->runSuggestion
= (bool)$request->getVal( 'runsuggestion', true );
205 $this->profile
= $profile;
209 * If an exact title match can be found, jump straight ahead to it.
211 * @param string $term
213 public function goResult( $term ) {
214 $this->setupPage( $term );
215 # Try to go to page as entered.
216 $title = Title
::newFromText( $term );
217 # If the string cannot be used to create a title
218 if ( is_null( $title ) ) {
219 $this->showResults( $term );
223 # If there's an exact or very near match, jump right there.
224 $title = $this->getSearchEngine()
225 ->getNearMatcher( $this->getConfig() )->getNearMatch( $term );
227 if ( !is_null( $title ) &&
228 Hooks
::run( 'SpecialSearchGoResult', [ $term, $title, &$url ] )
230 if ( $url === null ) {
231 $url = $title->getFullURL();
233 $this->getOutput()->redirect( $url );
237 $this->showResults( $term );
241 * @param string $term
243 public function showResults( $term ) {
246 $search = $this->getSearchEngine();
247 $search->setFeatureData( 'rewrite', $this->runSuggestion
);
248 $search->setLimitOffset( $this->limit
, $this->offset
);
249 $search->setNamespaces( $this->namespaces
);
250 $search->prefix
= $this->mPrefix
;
251 $term = $search->transformSearchTerm( $term );
253 Hooks
::run( 'SpecialSearchSetupEngine', [ $this, $this->profile
, $search ] );
255 $this->setupPage( $term );
257 $out = $this->getOutput();
259 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
260 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
261 if ( $searchFowardUrl ) {
262 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
263 $out->redirect( $url );
266 Xml
::openElement( 'fieldset' ) .
267 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
270 [ 'class' => 'mw-searchdisabled' ],
271 $this->msg( 'searchdisabled' )->text()
273 $this->msg( 'googlesearch' )->rawParams(
274 htmlspecialchars( $term ),
276 $this->msg( 'searchbutton' )->escaped()
278 Xml
::closeElement( 'fieldset' )
285 $title = Title
::newFromText( $term );
286 $showSuggestion = $title === null ||
!$title->isKnown();
287 $search->setShowSuggestion( $showSuggestion );
289 // fetch search results
290 $rewritten = $search->replacePrefixes( $term );
292 $titleMatches = $search->searchTitle( $rewritten );
293 $textMatches = $search->searchText( $rewritten );
296 if ( $textMatches instanceof Status
) {
297 $textStatus = $textMatches;
298 $textMatches = $textStatus->getValue();
301 // did you mean... suggestions
302 $didYouMeanHtml = '';
303 if ( $showSuggestion && $textMatches ) {
304 if ( $textMatches->hasRewrittenQuery() ) {
305 $didYouMeanHtml = $this->getDidYouMeanRewrittenHtml( $term, $textMatches );
306 } elseif ( $textMatches->hasSuggestion() ) {
307 $didYouMeanHtml = $this->getDidYouMeanHtml( $textMatches );
311 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
312 # Hook requested termination
316 // start rendering the page
321 'id' => ( $this->isPowerSearch() ?
'powersearch' : 'search' ),
323 'action' => wfScript(),
328 // Get number of results
329 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
330 if ( $titleMatches ) {
331 $titleMatchesNum = $titleMatches->numRows();
332 $numTitleMatches = $titleMatches->getTotalHits();
334 if ( $textMatches ) {
335 $textMatchesNum = $textMatches->numRows();
336 $numTextMatches = $textMatches->getTotalHits();
338 $num = $titleMatchesNum +
$textMatchesNum;
339 $totalRes = $numTitleMatches +
$numTextMatches;
343 # This is an awful awful ID name. It's not a table, but we
344 # named it poorly from when this was a table so now we're
346 Xml
::openElement( 'div', [ 'id' => 'mw-search-top-table' ] ) .
347 $this->shortDialog( $term, $num, $totalRes ) .
348 Xml
::closeElement( 'div' ) .
349 $this->searchProfileTabs( $term ) .
350 $this->searchOptions( $term ) .
351 Xml
::closeElement( 'form' ) .
355 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
356 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
357 // Empty query -- straight view of search form
361 $out->addHTML( "<div class='searchresults'>" );
363 $hasErrors = $textStatus && $textStatus->getErrors();
365 list( $error, $warning ) = $textStatus->splitByErrorType();
366 if ( $error->getErrors() ) {
367 $out->addHTML( Html
::rawElement(
369 [ 'class' => 'errorbox' ],
370 $error->getHTML( 'search-error' )
373 if ( $warning->getErrors() ) {
374 $out->addHTML( Html
::rawElement(
376 [ 'class' => 'warningbox' ],
377 $warning->getHTML( 'search-warning' )
384 if ( $num ||
$this->offset
) {
385 // Show the create link ahead
386 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
387 if ( $totalRes > $this->limit ||
$this->offset
) {
388 if ( $this->searchEngineType
!== null ) {
389 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
391 $prevnext = $this->getLanguage()->viewPrevNext(
392 $this->getPageTitle(),
395 $this->powerSearchOptions() +
[ 'search' => $term ],
396 $this->limit +
$this->offset
>= $totalRes
400 Hooks
::run( 'SpecialSearchResults', [ $term, &$titleMatches, &$textMatches ] );
402 $out->parserOptions()->setEditSection( false );
403 if ( $titleMatches ) {
404 if ( $numTitleMatches > 0 ) {
405 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
406 $out->addHTML( $this->showMatches( $titleMatches ) );
408 $titleMatches->free();
411 if ( $textMatches ) {
412 // output appropriate heading
413 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
414 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
415 // if no title matches the heading is redundant
416 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
420 if ( $numTextMatches > 0 ) {
421 $search->augmentSearchResults( $textMatches );
422 $out->addHTML( $this->showMatches( $textMatches ) );
425 // show secondary interwiki results if any
426 if ( $textMatches->hasInterwikiResults( SearchResultSet
::SECONDARY_RESULTS
) ) {
427 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(
428 SearchResultSet
::SECONDARY_RESULTS
), $term ) );
432 $hasOtherResults = $textMatches &&
433 $textMatches->hasInterwikiResults( SearchResultSet
::INLINE_RESULTS
);
435 // If we have no results and we have not already displayed an error message
436 if ( $num === 0 && !$hasErrors ) {
437 if ( !$this->offset
) {
438 // If we have an offset the create link was rendered earlier in this function.
439 // This class needs a good de-spaghettification, but for now this will
441 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
443 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", [
444 $hasOtherResults ?
'search-nonefound-thiswiki' : 'search-nonefound',
445 wfEscapeWikiText( $term )
449 if ( $hasOtherResults ) {
450 foreach ( $textMatches->getInterwikiResults( SearchResultSet
::INLINE_RESULTS
)
451 as $interwiki => $interwikiResult ) {
452 if ( $interwikiResult instanceof Status ||
$interwikiResult->numRows() == 0 ) {
453 // ignore bad interwikis for now
457 $out->addHTML( $this->showMatches( $interwikiResult, $interwiki ) );
461 if ( $textMatches ) {
462 $textMatches->free();
465 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
468 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
471 $out->addHTML( "</div>" );
473 Hooks
::run( 'SpecialSearchResultsAppend', [ $this, $out, $term ] );
477 * Produce wiki header for interwiki results
478 * @param string $interwiki Interwiki name
479 * @param SearchResultSet $interwikiResult The result set
482 protected function interwikiHeader( $interwiki, $interwikiResult ) {
483 // TODO: we need to figure out how to name wikis correctly
484 $wikiMsg = $this->msg( 'search-interwiki-results-' . $interwiki )->parse();
485 return "<p class=\"mw-search-interwiki-header mw-search-visualclear\">\n$wikiMsg</p>";
489 * Generates HTML shown to the user when we have a suggestion about a query
490 * that might give more results than their current query.
492 protected function getDidYouMeanHtml( SearchResultSet
$textMatches ) {
493 # mirror Go/Search behavior of original request ..
494 $params = [ 'search' => $textMatches->getSuggestionQuery() ];
495 if ( $this->fulltext
=== null ) {
496 $params['fulltext'] = 'Search';
498 $params['fulltext'] = $this->fulltext
;
500 $stParams = array_merge( $params, $this->powerSearchOptions() );
502 $linkRenderer = $this->getLinkRenderer();
504 $snippet = $textMatches->getSuggestionSnippet() ?
: null;
505 if ( $snippet !== null ) {
506 $snippet = new HtmlArmor( $snippet );
509 $suggest = $linkRenderer->makeKnownLink(
510 $this->getPageTitle(),
512 [ 'id' => 'mw-search-DYM-suggestion' ],
516 # HTML of did you mean... search suggestion link
517 return Html
::rawElement(
519 [ 'class' => 'searchdidyoumean' ],
520 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
525 * Generates HTML shown to user when their query has been internally rewritten,
526 * and the results of the rewritten query are being returned.
528 * @param string $term The users search input
529 * @param SearchResultSet $textMatches The response to the users initial search request
530 * @return string HTML linking the user to their original $term query, and the one
531 * suggested by $textMatches.
533 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet
$textMatches ) {
534 // Showing results for '$rewritten'
535 // Search instead for '$orig'
537 $params = [ 'search' => $textMatches->getQueryAfterRewrite() ];
538 if ( $this->fulltext
=== null ) {
539 $params['fulltext'] = 'Search';
541 $params['fulltext'] = $this->fulltext
;
543 $stParams = array_merge( $params, $this->powerSearchOptions() );
545 $linkRenderer = $this->getLinkRenderer();
547 $snippet = $textMatches->getQueryAfterRewriteSnippet() ?
: null;
548 if ( $snippet !== null ) {
549 $snippet = new HtmlArmor( $snippet );
552 $rewritten = $linkRenderer->makeKnownLink(
553 $this->getPageTitle(),
555 [ 'id' => 'mw-search-DYM-rewritten' ],
559 $stParams['search'] = $term;
560 $stParams['runsuggestion'] = 0;
561 $original = $linkRenderer->makeKnownLink(
562 $this->getPageTitle(),
564 [ 'id' => 'mw-search-DYM-original' ],
568 return Html
::rawElement(
570 [ 'class' => 'searchdidyoumean' ],
571 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
576 * @param Title $title
577 * @param int $num The number of search results found
578 * @param null|SearchResultSet $titleMatches Results from title search
579 * @param null|SearchResultSet $textMatches Results from text search
581 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
582 // show direct page/create link if applicable
584 // Check DBkey !== '' in case of fragment link only.
585 if ( is_null( $title ) ||
$title->getDBkey() === ''
586 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
587 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
590 // preserve the paragraph for margins etc...
591 $this->getOutput()->addHTML( '<p></p>' );
596 $messageName = 'searchmenu-new-nocreate';
597 $linkClass = 'mw-search-createlink';
599 if ( !$title->isExternal() ) {
600 if ( $title->isKnown() ) {
601 $messageName = 'searchmenu-exists';
602 $linkClass = 'mw-search-exists';
603 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
604 $messageName = 'searchmenu-new';
610 wfEscapeWikiText( $title->getPrefixedText() ),
611 Message
::numParam( $num )
613 Hooks
::run( 'SpecialSearchCreateLink', [ $title, &$params ] );
615 // Extensions using the hook might still return an empty $messageName
616 if ( $messageName ) {
617 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
619 // preserve the paragraph for margins etc...
620 $this->getOutput()->addHTML( '<p></p>' );
625 * @param string $term
627 protected function setupPage( $term ) {
628 $out = $this->getOutput();
629 if ( strval( $term ) !== '' ) {
630 $out->setPageTitle( $this->msg( 'searchresults' ) );
631 $out->setHTMLTitle( $this->msg( 'pagetitle' )
632 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
633 ->inContentLanguage()->text()
636 // add javascript specific to special:search
637 $out->addModules( 'mediawiki.special.search' );
641 * Return true if current search is a power (advanced) search
645 protected function isPowerSearch() {
646 return $this->profile
=== 'advanced';
650 * Extract "power search" namespace settings from the request object,
651 * returning a list of index numbers to search.
653 * @param WebRequest $request
656 protected function powerSearch( &$request ) {
658 foreach ( $this->searchConfig
->searchableNamespaces() as $ns => $name ) {
659 if ( $request->getCheck( 'ns' . $ns ) ) {
668 * Reconstruct the 'power search' options for links
672 protected function powerSearchOptions() {
674 if ( !$this->isPowerSearch() ) {
675 $opt['profile'] = $this->profile
;
677 foreach ( $this->namespaces
as $n ) {
682 return $opt +
$this->extraParams
;
686 * Save namespace preferences when we're supposed to
688 * @return bool Whether we wrote something
690 protected function saveNamespaces() {
691 $user = $this->getUser();
692 $request = $this->getRequest();
694 if ( $user->isLoggedIn() &&
695 $user->matchEditToken(
696 $request->getVal( 'nsRemember' ),
701 // Reset namespace preferences: namespaces are not searched
702 // when they're not mentioned in the URL parameters.
703 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
704 $user->setOption( 'searchNs' . $n, false );
706 // The request parameters include all the namespaces to be searched.
707 // Even if they're the same as an existing profile, they're not eaten.
708 foreach ( $this->namespaces
as $n ) {
709 $user->setOption( 'searchNs' . $n, true );
712 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
713 $user->saveSettings();
723 * Show whole set of results
725 * @param SearchResultSet $matches
726 * @param string $interwiki Interwiki name
730 protected function showMatches( $matches, $interwiki = null ) {
733 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
735 $result = $matches->next();
736 $pos = $this->offset
;
738 if ( $result && $interwiki ) {
739 $out .= $this->interwikiHeader( $interwiki, $matches );
742 $out .= "<ul class='mw-search-results'>\n";
744 $out .= $this->showHit( $result, $terms, $pos++
);
745 $result = $matches->next();
749 // convert the whole thing to desired language variant
750 $out = $wgContLang->convert( $out );
756 * Format a single hit result
758 * @param SearchResult $result
759 * @param array $terms Terms to highlight
760 * @param int $position Position within the search results, including offset.
764 protected function showHit( SearchResult
$result, $terms, $position ) {
765 if ( $result->isBrokenTitle() ) {
769 $title = $result->getTitle();
771 $titleSnippet = $result->getTitleSnippet();
773 if ( $titleSnippet == '' ) {
774 $titleSnippet = null;
777 $link_t = clone $title;
780 Hooks
::run( 'ShowSearchHitTitle',
781 [ &$link_t, &$titleSnippet, $result, $terms, $this, &$query ] );
783 $linkRenderer = $this->getLinkRenderer();
785 if ( $titleSnippet !== null ) {
786 $titleSnippet = new HtmlArmor( $titleSnippet );
789 $link = $linkRenderer->makeKnownLink(
792 [ 'data-serp-pos' => $position ], // HTML attributes
796 // If page content is not readable, just return the title.
797 // This is not quite safe, but better than showing excerpts from non-readable pages
798 // Note that hiding the entry entirely would screw up paging.
799 if ( !$title->userCan( 'read', $this->getUser() ) ) {
800 return "<li>{$link}</li>\n";
803 // If the page doesn't *exist*... our search index is out of date.
804 // The least confusing at this point is to drop the result.
805 // You may get less results, but... oh well. :P
806 if ( $result->isMissingRevision() ) {
810 // format redirects / relevant sections
811 $redirectTitle = $result->getRedirectTitle();
812 $redirectText = $result->getRedirectSnippet();
813 $sectionTitle = $result->getSectionTitle();
814 $sectionText = $result->getSectionSnippet();
815 $categorySnippet = $result->getCategorySnippet();
818 if ( !is_null( $redirectTitle ) ) {
819 if ( $redirectText == '' ) {
820 $redirectText = null;
823 if ( $redirectText !== null ) {
824 $redirectText = new HtmlArmor( $redirectText );
827 $redirect = "<span class='searchalttitle'>" .
828 $this->msg( 'search-redirect' )->rawParams(
829 $linkRenderer->makeKnownLink( $redirectTitle, $redirectText ) )->text() .
834 if ( !is_null( $sectionTitle ) ) {
835 if ( $sectionText == '' ) {
839 if ( $sectionText !== null ) {
840 $sectionText = new HtmlArmor( $sectionText );
843 $section = "<span class='searchalttitle'>" .
844 $this->msg( 'search-section' )->rawParams(
845 $linkRenderer->makeKnownLink( $sectionTitle, $sectionText ) )->text() .
850 if ( $categorySnippet ) {
851 $category = "<span class='searchalttitle'>" .
852 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
856 // format text extract
857 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
859 $lang = $this->getLanguage();
861 // format description
862 $byteSize = $result->getByteSize();
863 $wordCount = $result->getWordCount();
864 $timestamp = $result->getTimestamp();
865 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
866 ->numParams( $wordCount )->escaped();
868 if ( $title->getNamespace() == NS_CATEGORY
) {
869 $cat = Category
::newFromTitle( $title );
870 $size = $this->msg( 'search-result-category-size' )
871 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
875 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
878 // Include a thumbnail for media files...
879 if ( $title->getNamespace() == NS_FILE
) {
880 $img = $result->getFile();
881 $img = $img ?
: wfFindFile( $title );
882 if ( $result->isFileMatch() ) {
883 $fileMatch = "<span class='searchalttitle'>" .
884 $this->msg( 'search-file-match' )->escaped() . "</span>";
887 $thumb = $img->transform( [ 'width' => 120, 'height' => 120 ] );
889 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
890 // Float doesn't seem to interact well with the bullets.
891 // Table messes up vertical alignment of the bullets.
892 // Bullets are therefore disabled (didn't look great anyway).
894 '<table class="searchResultImage">' .
896 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
897 $thumb->toHtml( [ 'desc-link' => true ] ) .
899 '<td style="vertical-align: top;">' .
900 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
902 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
915 if ( Hooks
::run( 'ShowSearchHit', [
916 $this, $result, $terms,
917 &$link, &$redirect, &$section, &$extract,
918 &$score, &$size, &$date, &$related,
921 $html = "<li><div class='mw-search-result-heading'>" .
922 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
923 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
931 * Extract custom captions from search-interwiki-custom message
933 protected function getCustomCaptions() {
934 if ( is_null( $this->customCaptions
) ) {
935 $this->customCaptions
= [];
936 // format per line <iwprefix>:<caption>
937 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
938 foreach ( $customLines as $line ) {
939 $parts = explode( ":", $line, 2 );
940 if ( count( $parts ) == 2 ) { // validate line
941 $this->customCaptions
[$parts[0]] = $parts[1];
948 * Show results from other wikis
950 * @param SearchResultSet|array $matches
951 * @param string $query
955 protected function showInterwiki( $matches, $query ) {
958 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
959 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
960 $out .= "<ul class='mw-search-iwresults'>\n";
962 // work out custom project captions
963 $this->getCustomCaptions();
965 if ( !is_array( $matches ) ) {
966 $matches = [ $matches ];
969 foreach ( $matches as $set ) {
971 $result = $set->next();
973 $out .= $this->showInterwikiHit( $result, $prev, $query );
974 $prev = $result->getInterwikiPrefix();
975 $result = $set->next();
979 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
980 $out .= "</ul></div>\n";
982 // convert the whole thing to desired language variant
983 $out = $wgContLang->convert( $out );
989 * Show single interwiki link
991 * @param SearchResult $result
992 * @param string $lastInterwiki
993 * @param string $query
997 protected function showInterwikiHit( $result, $lastInterwiki, $query ) {
998 if ( $result->isBrokenTitle() ) {
1002 $linkRenderer = $this->getLinkRenderer();
1004 $title = $result->getTitle();
1006 $titleSnippet = $result->getTitleSnippet();
1008 if ( $titleSnippet == '' ) {
1009 $titleSnippet = null;
1012 if ( $titleSnippet !== null ) {
1013 $titleSnippet = new HtmlArmor( $titleSnippet );
1016 $link = $linkRenderer->makeKnownLink(
1021 // format redirect if any
1022 $redirectTitle = $result->getRedirectTitle();
1023 $redirectText = $result->getRedirectSnippet();
1025 if ( !is_null( $redirectTitle ) ) {
1026 if ( $redirectText == '' ) {
1027 $redirectText = null;
1030 if ( $redirectText !== null ) {
1031 $redirectText = new HtmlArmor( $redirectText );
1034 $redirect = "<span class='searchalttitle'>" .
1035 $this->msg( 'search-redirect' )->rawParams(
1036 $linkRenderer->makeKnownLink( $redirectTitle, $redirectText ) )->text() .
1041 // display project name
1042 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
1043 if ( array_key_exists( $title->getInterwiki(), $this->customCaptions
) ) {
1044 // captions from 'search-interwiki-custom'
1045 $caption = $this->customCaptions
[$title->getInterwiki()];
1047 // default is to show the hostname of the other wiki which might suck
1048 // if there are many wikis on one hostname
1049 $parsed = wfParseUrl( $title->getFullURL() );
1050 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
1052 // "more results" link (special page stuff could be localized, but we might not know target lang)
1053 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
1054 $searchLink = $linkRenderer->makeKnownLink(
1056 $this->msg( 'search-interwiki-more' )->text(),
1060 'fulltext' => 'Search'
1063 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
1064 {$searchLink}</span>{$caption}</div>\n<ul>";
1067 $out .= "<li>{$link} {$redirect}</li>\n";
1073 * Generates the power search box at [[Special:Search]]
1075 * @param string $term Search term
1076 * @param array $opts
1077 * @return string HTML form
1079 protected function powerSearchBox( $term, $opts ) {
1082 // Groups namespaces into rows according to subject
1084 foreach ( $this->searchConfig
->searchableNamespaces() as $namespace => $name ) {
1085 $subject = MWNamespace
::getSubject( $namespace );
1086 if ( !array_key_exists( $subject, $rows ) ) {
1087 $rows[$subject] = "";
1090 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
1091 if ( $name == '' ) {
1092 $name = $this->msg( 'blanknamespace' )->text();
1096 Xml
::openElement( 'td' ) .
1100 "mw-search-ns{$namespace}",
1101 in_array( $namespace, $this->namespaces
)
1103 Xml
::closeElement( 'td' );
1106 $rows = array_values( $rows );
1107 $numRows = count( $rows );
1109 // Lays out namespaces in multiple floating two-column tables so they'll
1110 // be arranged nicely while still accommodating different screen widths
1111 $namespaceTables = '';
1112 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
1113 $namespaceTables .= Xml
::openElement( 'table' );
1115 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
1116 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
1119 $namespaceTables .= Xml
::closeElement( 'table' );
1122 $showSections = [ 'namespaceTables' => $namespaceTables ];
1124 Hooks
::run( 'SpecialSearchPowerBox', [ &$showSections, $term, $opts ] );
1127 foreach ( $opts as $key => $value ) {
1128 $hidden .= Html
::hidden( $key, $value );
1131 # Stuff to feed saveNamespaces()
1133 $user = $this->getUser();
1134 if ( $user->isLoggedIn() ) {
1135 $remember .= Xml
::checkLabel(
1136 $this->msg( 'powersearch-remember' )->text(),
1138 'mw-search-powersearch-remember',
1140 // The token goes here rather than in a hidden field so it
1141 // is only sent when necessary (not every form submission).
1142 [ 'value' => $user->getEditToken(
1149 // Return final output
1150 return Xml
::openElement( 'fieldset', [ 'id' => 'mw-searchoptions' ] ) .
1151 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1152 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1153 Xml
::element( 'div', [ 'id' => 'mw-search-togglebox' ], '', false ) .
1154 Xml
::element( 'div', [ 'class' => 'divider' ], '', false ) .
1155 implode( Xml
::element( 'div', [ 'class' => 'divider' ], '', false ), $showSections ) .
1157 Xml
::element( 'div', [ 'class' => 'divider' ], '', false ) .
1159 Xml
::closeElement( 'fieldset' );
1165 protected function getSearchProfiles() {
1166 // Builds list of Search Types (profiles)
1167 $nsAllSet = array_keys( $this->searchConfig
->searchableNamespaces() );
1168 $defaultNs = $this->searchConfig
->defaultNamespaces();
1171 'message' => 'searchprofile-articles',
1172 'tooltip' => 'searchprofile-articles-tooltip',
1173 'namespaces' => $defaultNs,
1174 'namespace-messages' => $this->searchConfig
->namespacesAsText(
1179 'message' => 'searchprofile-images',
1180 'tooltip' => 'searchprofile-images-tooltip',
1181 'namespaces' => [ NS_FILE
],
1184 'message' => 'searchprofile-everything',
1185 'tooltip' => 'searchprofile-everything-tooltip',
1186 'namespaces' => $nsAllSet,
1189 'message' => 'searchprofile-advanced',
1190 'tooltip' => 'searchprofile-advanced-tooltip',
1191 'namespaces' => self
::NAMESPACES_CURRENT
,
1195 Hooks
::run( 'SpecialSearchProfiles', [ &$profiles ] );
1197 foreach ( $profiles as &$data ) {
1198 if ( !is_array( $data['namespaces'] ) ) {
1201 sort( $data['namespaces'] );
1208 * @param string $term
1211 protected function searchProfileTabs( $term ) {
1212 $out = Html
::element( 'div', [ 'class' => 'mw-search-visualclear' ] ) .
1213 Xml
::openElement( 'div', [ 'class' => 'mw-search-profile-tabs' ] );
1216 if ( $this->startsWithImage( $term ) ) {
1218 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1221 $profiles = $this->getSearchProfiles();
1222 $lang = $this->getLanguage();
1224 // Outputs XML for Search Types
1225 $out .= Xml
::openElement( 'div', [ 'class' => 'search-types' ] );
1226 $out .= Xml
::openElement( 'ul' );
1227 foreach ( $profiles as $id => $profile ) {
1228 if ( !isset( $profile['parameters'] ) ) {
1229 $profile['parameters'] = [];
1231 $profile['parameters']['profile'] = $id;
1233 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1234 $lang->commaList( $profile['namespace-messages'] ) : null;
1238 'class' => $this->profile
=== $id ?
'current' : 'normal'
1240 $this->makeSearchLink(
1243 $this->msg( $profile['message'] )->text(),
1244 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1245 $profile['parameters']
1249 $out .= Xml
::closeElement( 'ul' );
1250 $out .= Xml
::closeElement( 'div' );
1251 $out .= Xml
::element( 'div', [ 'style' => 'clear:both' ], '', false );
1252 $out .= Xml
::closeElement( 'div' );
1258 * @param string $term Search term
1261 protected function searchOptions( $term ) {
1264 $opts['profile'] = $this->profile
;
1266 if ( $this->isPowerSearch() ) {
1267 $out .= $this->powerSearchBox( $term, $opts );
1270 Hooks
::run( 'SpecialSearchProfileForm', [ $this, &$form, $this->profile
, $term, $opts ] );
1278 * @param string $term
1279 * @param int $resultsShown
1280 * @param int $totalNum
1283 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1284 $searchWidget = new MediaWiki\Widget\
SearchInputWidget( [
1285 'id' => 'searchText',
1287 'autofocus' => trim( $term ) === '',
1289 'dataLocation' => 'content',
1290 'infusable' => true,
1293 $layout = new OOUI\
ActionFieldLayout( $searchWidget, new OOUI\
ButtonInputWidget( [
1295 'label' => $this->msg( 'searchbutton' )->text(),
1296 'flags' => [ 'progressive', 'primary' ],
1302 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
1303 Html
::hidden( 'profile', $this->profile
) .
1304 Html
::hidden( 'fulltext', 'Search' ) .
1308 if ( $totalNum > 0 && $this->offset
< $totalNum ) {
1309 $top = $this->msg( 'search-showingresults' )
1310 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1311 ->numParams( $resultsShown )
1313 $out .= Xml
::tags( 'div', [ 'class' => 'results-info' ], $top );
1320 * Make a search link with some target namespaces
1322 * @param string $term
1323 * @param array $namespaces Ignored
1324 * @param string $label Link's text
1325 * @param string $tooltip Link's tooltip
1326 * @param array $params Query string parameters
1327 * @return string HTML fragment
1329 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = [] ) {
1331 foreach ( $namespaces as $n ) {
1332 $opt['ns' . $n] = 1;
1335 $stParams = array_merge(
1338 'fulltext' => $this->msg( 'search' )->text()
1343 return Xml
::element(
1346 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1354 * Check if query starts with image: prefix
1356 * @param string $term The string to check
1359 protected function startsWithImage( $term ) {
1362 $parts = explode( ':', $term );
1363 if ( count( $parts ) > 1 ) {
1364 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1373 * @return SearchEngine
1375 public function getSearchEngine() {
1376 if ( $this->searchEngine
=== null ) {
1377 $this->searchEngine
= $this->searchEngineType ?
1378 MediaWikiServices
::getInstance()->getSearchEngineFactory()->create( $this->searchEngineType
) :
1379 MediaWikiServices
::getInstance()->newSearchEngine();
1382 return $this->searchEngine
;
1386 * Current search profile.
1387 * @return null|string
1389 function getProfile() {
1390 return $this->profile
;
1394 * Current namespaces.
1397 function getNamespaces() {
1398 return $this->namespaces
;
1402 * Users of hook SpecialSearchSetupEngine can use this to
1403 * add more params to links to not lose selection when
1404 * user navigates search results.
1407 * @param string $key
1408 * @param mixed $value
1410 public function setExtraParam( $key, $value ) {
1411 $this->extraParams
[$key] = $value;
1414 protected function getGroupName() {