Move FSFile classes to /fsfile
[mediawiki.git] / includes / specials / SpecialSearch.php
blob6daf19f5c3e7607ca792c6187057a9d81851cc04
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 use MediaWiki\MediaWikiServices;
28 /**
29 * implements Special:Search - Run text & title search and display the output
30 * @ingroup SpecialPage
32 class SpecialSearch extends SpecialPage {
33 /**
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.
39 * @var null|string
41 protected $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 = [];
52 /**
53 * @var string The prefix url parameter. Set on the searcher and the
54 * is expected to treat it as prefix filter on titles.
56 protected $mPrefix;
58 /**
59 * @var int
61 protected $limit, $offset;
63 /**
64 * @var array
66 protected $namespaces;
68 /**
69 * @var string
71 protected $fulltext;
73 /**
74 * @var bool
76 protected $runSuggestion = true;
78 /**
79 * Names of the wikis, in format: Interwiki prefix -> caption
80 * @var array
82 protected $customCaptions;
84 /**
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();
97 /**
98 * Entry point
100 * @param string $par
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
111 // URL.
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 );
119 return;
122 $this->setHeaders();
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',
129 ] );
130 $this->addHelpLink( 'Help:Searching' );
132 $this->load();
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 ) );
141 return;
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 );
151 } else {
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 );
175 $profile = null;
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' ) {
187 $profile = $key;
190 $this->namespaces = $nslist;
191 } elseif ( $profile === 'advanced' ) {
192 $this->namespaces = $nslist;
193 } else {
194 if ( isset( $profiles[$profile]['namespaces'] ) ) {
195 $this->namespaces = $profiles[$profile]['namespaces'];
196 } else {
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 );
221 return;
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 );
235 return;
237 # No match, generate an edit URL
238 $title = Title::newFromText( $term );
239 if ( !is_null( $title ) ) {
240 Hooks::run( 'SpecialSearchNogomatch', [ &$title ] );
242 $this->showResults( $term );
246 * @param string $term
248 public function showResults( $term ) {
249 global $wgContLang;
251 $search = $this->getSearchEngine();
252 $search->setFeatureData( 'rewrite', $this->runSuggestion );
253 $search->setLimitOffset( $this->limit, $this->offset );
254 $search->setNamespaces( $this->namespaces );
255 $search->prefix = $this->mPrefix;
256 $term = $search->transformSearchTerm( $term );
258 Hooks::run( 'SpecialSearchSetupEngine', [ $this, $this->profile, $search ] );
260 $this->setupPage( $term );
262 $out = $this->getOutput();
264 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
265 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
266 if ( $searchFowardUrl ) {
267 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
268 $out->redirect( $url );
269 } else {
270 $out->addHTML(
271 Xml::openElement( 'fieldset' ) .
272 Xml::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
273 Xml::element(
274 'p',
275 [ 'class' => 'mw-searchdisabled' ],
276 $this->msg( 'searchdisabled' )->text()
278 $this->msg( 'googlesearch' )->rawParams(
279 htmlspecialchars( $term ),
280 'UTF-8',
281 $this->msg( 'searchbutton' )->escaped()
282 )->text() .
283 Xml::closeElement( 'fieldset' )
287 return;
290 $title = Title::newFromText( $term );
291 $showSuggestion = $title === null || !$title->isKnown();
292 $search->setShowSuggestion( $showSuggestion );
294 // fetch search results
295 $rewritten = $search->replacePrefixes( $term );
297 $titleMatches = $search->searchTitle( $rewritten );
298 $textMatches = $search->searchText( $rewritten );
300 $textStatus = null;
301 if ( $textMatches instanceof Status ) {
302 $textStatus = $textMatches;
303 $textMatches = null;
306 // did you mean... suggestions
307 $didYouMeanHtml = '';
308 if ( $showSuggestion && $textMatches && !$textStatus ) {
309 if ( $textMatches->hasRewrittenQuery() ) {
310 $didYouMeanHtml = $this->getDidYouMeanRewrittenHtml( $term, $textMatches );
311 } elseif ( $textMatches->hasSuggestion() ) {
312 $didYouMeanHtml = $this->getDidYouMeanHtml( $textMatches );
316 if ( !Hooks::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
317 # Hook requested termination
318 return;
321 // start rendering the page
322 $out->addHTML(
323 Xml::openElement(
324 'form',
326 'id' => ( $this->isPowerSearch() ? 'powersearch' : 'search' ),
327 'method' => 'get',
328 'action' => wfScript(),
333 // Get number of results
334 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
335 if ( $titleMatches ) {
336 $titleMatchesNum = $titleMatches->numRows();
337 $numTitleMatches = $titleMatches->getTotalHits();
339 if ( $textMatches ) {
340 $textMatchesNum = $textMatches->numRows();
341 $numTextMatches = $textMatches->getTotalHits();
343 $num = $titleMatchesNum + $textMatchesNum;
344 $totalRes = $numTitleMatches + $numTextMatches;
346 $out->enableOOUI();
347 $out->addHTML(
348 # This is an awful awful ID name. It's not a table, but we
349 # named it poorly from when this was a table so now we're
350 # stuck with it
351 Xml::openElement( 'div', [ 'id' => 'mw-search-top-table' ] ) .
352 $this->shortDialog( $term, $num, $totalRes ) .
353 Xml::closeElement( 'div' ) .
354 $this->searchProfileTabs( $term ) .
355 $this->searchOptions( $term ) .
356 Xml::closeElement( 'form' ) .
357 $didYouMeanHtml
360 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
361 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
362 // Empty query -- straight view of search form
363 return;
366 $out->addHTML( "<div class='searchresults'>" );
368 // prev/next links
369 $prevnext = null;
370 if ( $num || $this->offset ) {
371 // Show the create link ahead
372 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
373 if ( $totalRes > $this->limit || $this->offset ) {
374 if ( $this->searchEngineType !== null ) {
375 $this->setExtraParam( 'srbackend', $this->searchEngineType );
377 $prevnext = $this->getLanguage()->viewPrevNext(
378 $this->getPageTitle(),
379 $this->offset,
380 $this->limit,
381 $this->powerSearchOptions() + [ 'search' => $term ],
382 $this->limit + $this->offset >= $totalRes
386 Hooks::run( 'SpecialSearchResults', [ $term, &$titleMatches, &$textMatches ] );
388 $out->parserOptions()->setEditSection( false );
389 if ( $titleMatches ) {
390 if ( $numTitleMatches > 0 ) {
391 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
392 $out->addHTML( $this->showMatches( $titleMatches ) );
394 $titleMatches->free();
396 if ( $textMatches && !$textStatus ) {
397 // output appropriate heading
398 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
399 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
400 // if no title matches the heading is redundant
401 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
404 // show results
405 if ( $numTextMatches > 0 ) {
406 $search->augmentSearchResults( $textMatches );
407 $out->addHTML( $this->showMatches( $textMatches ) );
410 // show secondary interwiki results if any
411 if ( $textMatches->hasInterwikiResults( SearchResultSet::SECONDARY_RESULTS ) ) {
412 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(
413 SearchResultSet::SECONDARY_RESULTS ), $term ) );
417 $hasOtherResults = $textMatches &&
418 $textMatches->hasInterwikiResults( SearchResultSet::INLINE_RESULTS );
420 if ( $num === 0 ) {
421 if ( $textStatus ) {
422 $out->addHTML( '<div class="error">' .
423 $textStatus->getMessage( 'search-error' ) . '</div>' );
424 } else {
425 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
426 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
427 [ $hasOtherResults ? 'search-nonefound-thiswiki' : 'search-nonefound',
428 wfEscapeWikiText( $term )
429 ] );
433 if ( $hasOtherResults ) {
434 foreach ( $textMatches->getInterwikiResults( SearchResultSet::INLINE_RESULTS )
435 as $interwiki => $interwikiResult ) {
436 if ( $interwikiResult instanceof Status || $interwikiResult->numRows() == 0 ) {
437 // ignore bad interwikis for now
438 continue;
440 // TODO: wiki header
441 $out->addHTML( $this->showMatches( $interwikiResult, $interwiki ) );
445 if ( $textMatches ) {
446 $textMatches->free();
449 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
451 if ( $prevnext ) {
452 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
455 $out->addHTML( "</div>" );
457 Hooks::run( 'SpecialSearchResultsAppend', [ $this, $out, $term ] );
462 * Produce wiki header for interwiki results
463 * @param string $interwiki Interwiki name
464 * @param SearchResultSet $interwikiResult The result set
465 * @return string
467 protected function interwikiHeader( $interwiki, $interwikiResult ) {
468 // TODO: we need to figure out how to name wikis correctly
469 $wikiMsg = $this->msg( 'search-interwiki-results-' . $interwiki )->parse();
470 return "<p class=\"mw-search-interwiki-header mw-search-visualclear\">\n$wikiMsg</p>";
474 * Decide if the suggested query should be run, and it's results returned
475 * instead of the provided $textMatches
477 * @param SearchResultSet $textMatches The results of a users query
478 * @return bool
480 protected function shouldRunSuggestedQuery( SearchResultSet $textMatches ) {
481 if ( !$this->runSuggestion ||
482 !$textMatches->hasSuggestion() ||
483 $textMatches->numRows() > 0 ||
484 $textMatches->searchContainedSyntax()
486 return false;
489 return $this->getConfig()->get( 'SearchRunSuggestedQuery' );
493 * Generates HTML shown to the user when we have a suggestion about a query
494 * that might give more results than their current query.
496 protected function getDidYouMeanHtml( SearchResultSet $textMatches ) {
497 # mirror Go/Search behavior of original request ..
498 $params = [ 'search' => $textMatches->getSuggestionQuery() ];
499 if ( $this->fulltext === null ) {
500 $params['fulltext'] = 'Search';
501 } else {
502 $params['fulltext'] = $this->fulltext;
504 $stParams = array_merge( $params, $this->powerSearchOptions() );
506 $suggest = Linker::linkKnown(
507 $this->getPageTitle(),
508 $textMatches->getSuggestionSnippet() ?: null,
509 [ 'id' => 'mw-search-DYM-suggestion' ],
510 $stParams
513 # HTML of did you mean... search suggestion link
514 return Html::rawElement(
515 'div',
516 [ 'class' => 'searchdidyoumean' ],
517 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
522 * Generates HTML shown to user when their query has been internally rewritten,
523 * and the results of the rewritten query are being returned.
525 * @param string $term The users search input
526 * @param SearchResultSet $textMatches The response to the users initial search request
527 * @return string HTML linking the user to their original $term query, and the one
528 * suggested by $textMatches.
530 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet $textMatches ) {
531 // Showing results for '$rewritten'
532 // Search instead for '$orig'
534 $params = [ 'search' => $textMatches->getQueryAfterRewrite() ];
535 if ( $this->fulltext === null ) {
536 $params['fulltext'] = 'Search';
537 } else {
538 $params['fulltext'] = $this->fulltext;
540 $stParams = array_merge( $params, $this->powerSearchOptions() );
542 $rewritten = Linker::linkKnown(
543 $this->getPageTitle(),
544 $textMatches->getQueryAfterRewriteSnippet() ?: null,
545 [ 'id' => 'mw-search-DYM-rewritten' ],
546 $stParams
549 $stParams['search'] = $term;
550 $stParams['runsuggestion'] = 0;
551 $original = Linker::linkKnown(
552 $this->getPageTitle(),
553 htmlspecialchars( $term ),
554 [ 'id' => 'mw-search-DYM-original' ],
555 $stParams
558 return Html::rawElement(
559 'div',
560 [ 'class' => 'searchdidyoumean' ],
561 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
566 * @param Title $title
567 * @param int $num The number of search results found
568 * @param null|SearchResultSet $titleMatches Results from title search
569 * @param null|SearchResultSet $textMatches Results from text search
571 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
572 // show direct page/create link if applicable
574 // Check DBkey !== '' in case of fragment link only.
575 if ( is_null( $title ) || $title->getDBkey() === ''
576 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
577 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
579 // invalid title
580 // preserve the paragraph for margins etc...
581 $this->getOutput()->addHTML( '<p></p>' );
583 return;
586 $messageName = 'searchmenu-new-nocreate';
587 $linkClass = 'mw-search-createlink';
589 if ( !$title->isExternal() ) {
590 if ( $title->isKnown() ) {
591 $messageName = 'searchmenu-exists';
592 $linkClass = 'mw-search-exists';
593 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
594 $messageName = 'searchmenu-new';
598 $params = [
599 $messageName,
600 wfEscapeWikiText( $title->getPrefixedText() ),
601 Message::numParam( $num )
603 Hooks::run( 'SpecialSearchCreateLink', [ $title, &$params ] );
605 // Extensions using the hook might still return an empty $messageName
606 if ( $messageName ) {
607 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
608 } else {
609 // preserve the paragraph for margins etc...
610 $this->getOutput()->addHTML( '<p></p>' );
615 * @param string $term
617 protected function setupPage( $term ) {
618 $out = $this->getOutput();
619 if ( strval( $term ) !== '' ) {
620 $out->setPageTitle( $this->msg( 'searchresults' ) );
621 $out->setHTMLTitle( $this->msg( 'pagetitle' )
622 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
623 ->inContentLanguage()->text()
626 // add javascript specific to special:search
627 $out->addModules( 'mediawiki.special.search' );
631 * Return true if current search is a power (advanced) search
633 * @return bool
635 protected function isPowerSearch() {
636 return $this->profile === 'advanced';
640 * Extract "power search" namespace settings from the request object,
641 * returning a list of index numbers to search.
643 * @param WebRequest $request
644 * @return array
646 protected function powerSearch( &$request ) {
647 $arr = [];
648 foreach ( $this->searchConfig->searchableNamespaces() as $ns => $name ) {
649 if ( $request->getCheck( 'ns' . $ns ) ) {
650 $arr[] = $ns;
654 return $arr;
658 * Reconstruct the 'power search' options for links
660 * @return array
662 protected function powerSearchOptions() {
663 $opt = [];
664 if ( !$this->isPowerSearch() ) {
665 $opt['profile'] = $this->profile;
666 } else {
667 foreach ( $this->namespaces as $n ) {
668 $opt['ns' . $n] = 1;
672 return $opt + $this->extraParams;
676 * Save namespace preferences when we're supposed to
678 * @return bool Whether we wrote something
680 protected function saveNamespaces() {
681 $user = $this->getUser();
682 $request = $this->getRequest();
684 if ( $user->isLoggedIn() &&
685 $user->matchEditToken(
686 $request->getVal( 'nsRemember' ),
687 'searchnamespace',
688 $request
689 ) && !wfReadOnly()
691 // Reset namespace preferences: namespaces are not searched
692 // when they're not mentioned in the URL parameters.
693 foreach ( MWNamespace::getValidNamespaces() as $n ) {
694 $user->setOption( 'searchNs' . $n, false );
696 // The request parameters include all the namespaces to be searched.
697 // Even if they're the same as an existing profile, they're not eaten.
698 foreach ( $this->namespaces as $n ) {
699 $user->setOption( 'searchNs' . $n, true );
702 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
703 $user->saveSettings();
704 } );
706 return true;
709 return false;
713 * Show whole set of results
715 * @param SearchResultSet $matches
716 * @param string $interwiki Interwiki name
718 * @return string
720 protected function showMatches( $matches, $interwiki = null ) {
721 global $wgContLang;
723 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
724 $out = '';
725 $result = $matches->next();
726 $pos = $this->offset;
728 if ( $result && $interwiki ) {
729 $out .= $this->interwikiHeader( $interwiki, $matches );
732 $out .= "<ul class='mw-search-results'>\n";
733 while ( $result ) {
734 $out .= $this->showHit( $result, $terms, $pos++ );
735 $result = $matches->next();
737 $out .= "</ul>\n";
739 // convert the whole thing to desired language variant
740 $out = $wgContLang->convert( $out );
742 return $out;
746 * Format a single hit result
748 * @param SearchResult $result
749 * @param array $terms Terms to highlight
750 * @param int $position Position within the search results, including offset.
752 * @return string
754 protected function showHit( SearchResult $result, $terms, $position ) {
756 if ( $result->isBrokenTitle() ) {
757 return '';
760 $title = $result->getTitle();
762 $titleSnippet = $result->getTitleSnippet();
764 if ( $titleSnippet == '' ) {
765 $titleSnippet = null;
768 $link_t = clone $title;
769 $query = [];
771 Hooks::run( 'ShowSearchHitTitle',
772 [ &$link_t, &$titleSnippet, $result, $terms, $this, &$query ] );
774 $link = Linker::linkKnown(
775 $link_t,
776 $titleSnippet,
777 [ 'data-serp-pos' => $position ], // HTML attributes
778 $query
781 // If page content is not readable, just return the title.
782 // This is not quite safe, but better than showing excerpts from non-readable pages
783 // Note that hiding the entry entirely would screw up paging.
784 if ( !$title->userCan( 'read', $this->getUser() ) ) {
785 return "<li>{$link}</li>\n";
788 // If the page doesn't *exist*... our search index is out of date.
789 // The least confusing at this point is to drop the result.
790 // You may get less results, but... oh well. :P
791 if ( $result->isMissingRevision() ) {
792 return '';
795 // format redirects / relevant sections
796 $redirectTitle = $result->getRedirectTitle();
797 $redirectText = $result->getRedirectSnippet();
798 $sectionTitle = $result->getSectionTitle();
799 $sectionText = $result->getSectionSnippet();
800 $categorySnippet = $result->getCategorySnippet();
802 $redirect = '';
803 if ( !is_null( $redirectTitle ) ) {
804 if ( $redirectText == '' ) {
805 $redirectText = null;
808 $redirect = "<span class='searchalttitle'>" .
809 $this->msg( 'search-redirect' )->rawParams(
810 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
811 "</span>";
814 $section = '';
815 if ( !is_null( $sectionTitle ) ) {
816 if ( $sectionText == '' ) {
817 $sectionText = null;
820 $section = "<span class='searchalttitle'>" .
821 $this->msg( 'search-section' )->rawParams(
822 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
823 "</span>";
826 $category = '';
827 if ( $categorySnippet ) {
828 $category = "<span class='searchalttitle'>" .
829 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
830 "</span>";
833 // format text extract
834 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
836 $lang = $this->getLanguage();
838 // format description
839 $byteSize = $result->getByteSize();
840 $wordCount = $result->getWordCount();
841 $timestamp = $result->getTimestamp();
842 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
843 ->numParams( $wordCount )->escaped();
845 if ( $title->getNamespace() == NS_CATEGORY ) {
846 $cat = Category::newFromTitle( $title );
847 $size = $this->msg( 'search-result-category-size' )
848 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
849 ->escaped();
852 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
854 $fileMatch = '';
855 // Include a thumbnail for media files...
856 if ( $title->getNamespace() == NS_FILE ) {
857 $img = $result->getFile();
858 $img = $img ?: wfFindFile( $title );
859 if ( $result->isFileMatch() ) {
860 $fileMatch = "<span class='searchalttitle'>" .
861 $this->msg( 'search-file-match' )->escaped() . "</span>";
863 if ( $img ) {
864 $thumb = $img->transform( [ 'width' => 120, 'height' => 120 ] );
865 if ( $thumb ) {
866 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
867 // Float doesn't seem to interact well with the bullets.
868 // Table messes up vertical alignment of the bullets.
869 // Bullets are therefore disabled (didn't look great anyway).
870 return "<li>" .
871 '<table class="searchResultImage">' .
872 '<tr>' .
873 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
874 $thumb->toHtml( [ 'desc-link' => true ] ) .
875 '</td>' .
876 '<td style="vertical-align: top;">' .
877 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
878 $extract .
879 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
880 '</td>' .
881 '</tr>' .
882 '</table>' .
883 "</li>\n";
888 $html = null;
890 $score = '';
891 $related = '';
892 if ( Hooks::run( 'ShowSearchHit', [
893 $this, $result, $terms,
894 &$link, &$redirect, &$section, &$extract,
895 &$score, &$size, &$date, &$related,
896 &$html
897 ] ) ) {
898 $html = "<li><div class='mw-search-result-heading'>" .
899 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
900 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
901 "</li>\n";
904 return $html;
908 * Extract custom captions from search-interwiki-custom message
910 protected function getCustomCaptions() {
911 if ( is_null( $this->customCaptions ) ) {
912 $this->customCaptions = [];
913 // format per line <iwprefix>:<caption>
914 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
915 foreach ( $customLines as $line ) {
916 $parts = explode( ":", $line, 2 );
917 if ( count( $parts ) == 2 ) { // validate line
918 $this->customCaptions[$parts[0]] = $parts[1];
925 * Show results from other wikis
927 * @param SearchResultSet|array $matches
928 * @param string $query
930 * @return string
932 protected function showInterwiki( $matches, $query ) {
933 global $wgContLang;
935 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
936 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
937 $out .= "<ul class='mw-search-iwresults'>\n";
939 // work out custom project captions
940 $this->getCustomCaptions();
942 if ( !is_array( $matches ) ) {
943 $matches = [ $matches ];
946 foreach ( $matches as $set ) {
947 $prev = null;
948 $result = $set->next();
949 while ( $result ) {
950 $out .= $this->showInterwikiHit( $result, $prev, $query );
951 $prev = $result->getInterwikiPrefix();
952 $result = $set->next();
956 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
957 $out .= "</ul></div>\n";
959 // convert the whole thing to desired language variant
960 $out = $wgContLang->convert( $out );
962 return $out;
966 * Show single interwiki link
968 * @param SearchResult $result
969 * @param string $lastInterwiki
970 * @param string $query
972 * @return string
974 protected function showInterwikiHit( $result, $lastInterwiki, $query ) {
976 if ( $result->isBrokenTitle() ) {
977 return '';
980 $title = $result->getTitle();
982 $titleSnippet = $result->getTitleSnippet();
984 if ( $titleSnippet == '' ) {
985 $titleSnippet = null;
988 $link = Linker::linkKnown(
989 $title,
990 $titleSnippet
993 // format redirect if any
994 $redirectTitle = $result->getRedirectTitle();
995 $redirectText = $result->getRedirectSnippet();
996 $redirect = '';
997 if ( !is_null( $redirectTitle ) ) {
998 if ( $redirectText == '' ) {
999 $redirectText = null;
1002 $redirect = "<span class='searchalttitle'>" .
1003 $this->msg( 'search-redirect' )->rawParams(
1004 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
1005 "</span>";
1008 $out = "";
1009 // display project name
1010 if ( is_null( $lastInterwiki ) || $lastInterwiki != $title->getInterwiki() ) {
1011 if ( array_key_exists( $title->getInterwiki(), $this->customCaptions ) ) {
1012 // captions from 'search-interwiki-custom'
1013 $caption = $this->customCaptions[$title->getInterwiki()];
1014 } else {
1015 // default is to show the hostname of the other wiki which might suck
1016 // if there are many wikis on one hostname
1017 $parsed = wfParseUrl( $title->getFullURL() );
1018 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
1020 // "more results" link (special page stuff could be localized, but we might not know target lang)
1021 $searchTitle = Title::newFromText( $title->getInterwiki() . ":Special:Search" );
1022 $searchLink = Linker::linkKnown(
1023 $searchTitle,
1024 $this->msg( 'search-interwiki-more' )->text(),
1027 'search' => $query,
1028 'fulltext' => 'Search'
1031 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
1032 {$searchLink}</span>{$caption}</div>\n<ul>";
1035 $out .= "<li>{$link} {$redirect}</li>\n";
1037 return $out;
1041 * Generates the power search box at [[Special:Search]]
1043 * @param string $term Search term
1044 * @param array $opts
1045 * @return string HTML form
1047 protected function powerSearchBox( $term, $opts ) {
1048 global $wgContLang;
1050 // Groups namespaces into rows according to subject
1051 $rows = [];
1052 foreach ( $this->searchConfig->searchableNamespaces() as $namespace => $name ) {
1053 $subject = MWNamespace::getSubject( $namespace );
1054 if ( !array_key_exists( $subject, $rows ) ) {
1055 $rows[$subject] = "";
1058 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
1059 if ( $name == '' ) {
1060 $name = $this->msg( 'blanknamespace' )->text();
1063 $rows[$subject] .=
1064 Xml::openElement( 'td' ) .
1065 Xml::checkLabel(
1066 $name,
1067 "ns{$namespace}",
1068 "mw-search-ns{$namespace}",
1069 in_array( $namespace, $this->namespaces )
1071 Xml::closeElement( 'td' );
1074 $rows = array_values( $rows );
1075 $numRows = count( $rows );
1077 // Lays out namespaces in multiple floating two-column tables so they'll
1078 // be arranged nicely while still accommodating different screen widths
1079 $namespaceTables = '';
1080 for ( $i = 0; $i < $numRows; $i += 4 ) {
1081 $namespaceTables .= Xml::openElement( 'table' );
1083 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
1084 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
1087 $namespaceTables .= Xml::closeElement( 'table' );
1090 $showSections = [ 'namespaceTables' => $namespaceTables ];
1092 Hooks::run( 'SpecialSearchPowerBox', [ &$showSections, $term, $opts ] );
1094 $hidden = '';
1095 foreach ( $opts as $key => $value ) {
1096 $hidden .= Html::hidden( $key, $value );
1099 # Stuff to feed saveNamespaces()
1100 $remember = '';
1101 $user = $this->getUser();
1102 if ( $user->isLoggedIn() ) {
1103 $remember .= Xml::checkLabel(
1104 $this->msg( 'powersearch-remember' )->text(),
1105 'nsRemember',
1106 'mw-search-powersearch-remember',
1107 false,
1108 // The token goes here rather than in a hidden field so it
1109 // is only sent when necessary (not every form submission).
1110 [ 'value' => $user->getEditToken(
1111 'searchnamespace',
1112 $this->getRequest()
1117 // Return final output
1118 return Xml::openElement( 'fieldset', [ 'id' => 'mw-searchoptions' ] ) .
1119 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1120 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1121 Xml::element( 'div', [ 'id' => 'mw-search-togglebox' ], '', false ) .
1122 Xml::element( 'div', [ 'class' => 'divider' ], '', false ) .
1123 implode( Xml::element( 'div', [ 'class' => 'divider' ], '', false ), $showSections ) .
1124 $hidden .
1125 Xml::element( 'div', [ 'class' => 'divider' ], '', false ) .
1126 $remember .
1127 Xml::closeElement( 'fieldset' );
1131 * @return array
1133 protected function getSearchProfiles() {
1134 // Builds list of Search Types (profiles)
1135 $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
1136 $defaultNs = $this->searchConfig->defaultNamespaces();
1137 $profiles = [
1138 'default' => [
1139 'message' => 'searchprofile-articles',
1140 'tooltip' => 'searchprofile-articles-tooltip',
1141 'namespaces' => $defaultNs,
1142 'namespace-messages' => $this->searchConfig->namespacesAsText(
1143 $defaultNs
1146 'images' => [
1147 'message' => 'searchprofile-images',
1148 'tooltip' => 'searchprofile-images-tooltip',
1149 'namespaces' => [ NS_FILE ],
1151 'all' => [
1152 'message' => 'searchprofile-everything',
1153 'tooltip' => 'searchprofile-everything-tooltip',
1154 'namespaces' => $nsAllSet,
1156 'advanced' => [
1157 'message' => 'searchprofile-advanced',
1158 'tooltip' => 'searchprofile-advanced-tooltip',
1159 'namespaces' => self::NAMESPACES_CURRENT,
1163 Hooks::run( 'SpecialSearchProfiles', [ &$profiles ] );
1165 foreach ( $profiles as &$data ) {
1166 if ( !is_array( $data['namespaces'] ) ) {
1167 continue;
1169 sort( $data['namespaces'] );
1172 return $profiles;
1176 * @param string $term
1177 * @return string
1179 protected function searchProfileTabs( $term ) {
1180 $out = Html::element( 'div', [ 'class' => 'mw-search-visualclear' ] ) .
1181 Xml::openElement( 'div', [ 'class' => 'mw-search-profile-tabs' ] );
1183 $bareterm = $term;
1184 if ( $this->startsWithImage( $term ) ) {
1185 // Deletes prefixes
1186 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1189 $profiles = $this->getSearchProfiles();
1190 $lang = $this->getLanguage();
1192 // Outputs XML for Search Types
1193 $out .= Xml::openElement( 'div', [ 'class' => 'search-types' ] );
1194 $out .= Xml::openElement( 'ul' );
1195 foreach ( $profiles as $id => $profile ) {
1196 if ( !isset( $profile['parameters'] ) ) {
1197 $profile['parameters'] = [];
1199 $profile['parameters']['profile'] = $id;
1201 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1202 $lang->commaList( $profile['namespace-messages'] ) : null;
1203 $out .= Xml::tags(
1204 'li',
1206 'class' => $this->profile === $id ? 'current' : 'normal'
1208 $this->makeSearchLink(
1209 $bareterm,
1211 $this->msg( $profile['message'] )->text(),
1212 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1213 $profile['parameters']
1217 $out .= Xml::closeElement( 'ul' );
1218 $out .= Xml::closeElement( 'div' );
1219 $out .= Xml::element( 'div', [ 'style' => 'clear:both' ], '', false );
1220 $out .= Xml::closeElement( 'div' );
1222 return $out;
1226 * @param string $term Search term
1227 * @return string
1229 protected function searchOptions( $term ) {
1230 $out = '';
1231 $opts = [];
1232 $opts['profile'] = $this->profile;
1234 if ( $this->isPowerSearch() ) {
1235 $out .= $this->powerSearchBox( $term, $opts );
1236 } else {
1237 $form = '';
1238 Hooks::run( 'SpecialSearchProfileForm', [ $this, &$form, $this->profile, $term, $opts ] );
1239 $out .= $form;
1242 return $out;
1246 * @param string $term
1247 * @param int $resultsShown
1248 * @param int $totalNum
1249 * @return string
1251 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1252 $searchWidget = new MediaWiki\Widget\SearchInputWidget( [
1253 'id' => 'searchText',
1254 'name' => 'search',
1255 'autofocus' => trim( $term ) === '',
1256 'value' => $term,
1257 'dataLocation' => 'content',
1258 'infusable' => true,
1259 ] );
1261 $layout = new OOUI\ActionFieldLayout( $searchWidget, new OOUI\ButtonInputWidget( [
1262 'type' => 'submit',
1263 'label' => $this->msg( 'searchbutton' )->text(),
1264 'flags' => [ 'progressive', 'primary' ],
1265 ] ), [
1266 'align' => 'top',
1267 ] );
1269 $out =
1270 Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
1271 Html::hidden( 'profile', $this->profile ) .
1272 Html::hidden( 'fulltext', 'Search' ) .
1273 $layout;
1275 // Results-info
1276 if ( $totalNum > 0 && $this->offset < $totalNum ) {
1277 $top = $this->msg( 'search-showingresults' )
1278 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1279 ->numParams( $resultsShown )
1280 ->parse();
1281 $out .= Xml::tags( 'div', [ 'class' => 'results-info' ], $top );
1284 return $out;
1288 * Make a search link with some target namespaces
1290 * @param string $term
1291 * @param array $namespaces Ignored
1292 * @param string $label Link's text
1293 * @param string $tooltip Link's tooltip
1294 * @param array $params Query string parameters
1295 * @return string HTML fragment
1297 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = [] ) {
1298 $opt = $params;
1299 foreach ( $namespaces as $n ) {
1300 $opt['ns' . $n] = 1;
1303 $stParams = array_merge(
1305 'search' => $term,
1306 'fulltext' => $this->msg( 'search' )->text()
1308 $opt
1311 return Xml::element(
1312 'a',
1314 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1315 'title' => $tooltip
1317 $label
1322 * Check if query starts with image: prefix
1324 * @param string $term The string to check
1325 * @return bool
1327 protected function startsWithImage( $term ) {
1328 global $wgContLang;
1330 $parts = explode( ':', $term );
1331 if ( count( $parts ) > 1 ) {
1332 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1335 return false;
1339 * Check if query starts with all: prefix
1341 * @param string $term The string to check
1342 * @return bool
1344 protected function startsWithAll( $term ) {
1346 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1348 $parts = explode( ':', $term );
1349 if ( count( $parts ) > 1 ) {
1350 return $parts[0] == $allkeyword;
1353 return false;
1357 * @since 1.18
1359 * @return SearchEngine
1361 public function getSearchEngine() {
1362 if ( $this->searchEngine === null ) {
1363 $this->searchEngine = $this->searchEngineType ?
1364 MediaWikiServices::getInstance()->getSearchEngineFactory()->create( $this->searchEngineType ) :
1365 MediaWikiServices::getInstance()->newSearchEngine();
1368 return $this->searchEngine;
1372 * Current search profile.
1373 * @return null|string
1375 function getProfile() {
1376 return $this->profile;
1380 * Current namespaces.
1381 * @return array
1383 function getNamespaces() {
1384 return $this->namespaces;
1388 * Users of hook SpecialSearchSetupEngine can use this to
1389 * add more params to links to not lose selection when
1390 * user navigates search results.
1391 * @since 1.18
1393 * @param string $key
1394 * @param mixed $value
1396 public function setExtraParam( $key, $value ) {
1397 $this->extraParams[$key] = $value;
1400 protected function getGroupName() {
1401 return 'pages';