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();
104 $out = $this->getOutput();
106 // Fetch the search term
107 $term = str_replace( "\n", " ", $request->getText( 'search' ) );
109 // Historically search terms have been accepted not only in the search query
110 // parameter, but also as part of the primary url. This can have PII implications
111 // in releasing page view data. As such issue a 301 redirect to the correct
113 if ( strlen( $par ) && !strlen( $term ) ) {
114 $query = $request->getValues();
115 unset( $query['title'] );
116 // Strip underscores from title parameter; most of the time we'll want
117 // text form here. But don't strip underscores from actual text params!
118 $query['search'] = str_replace( '_', ' ', $par );
119 $out->redirect( $this->getPageTitle()->getFullURL( $query ), 301 );
123 // Need to load selected namespaces before handling nsRemember
125 // TODO: This performs database actions on GET request, which is going to
126 // be a problem for our multi-datacenter work.
127 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
128 $this->saveNamespaces();
129 // Remove the token from the URL to prevent the user from inadvertently
130 // exposing it (e.g. by pasting it into a public wiki page) or undoing
131 // later settings changes (e.g. by reloading the page).
132 $query = $request->getValues();
133 unset( $query['title'], $query['nsRemember'] );
134 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
138 $this->searchEngineType
= $request->getVal( 'srbackend' );
140 !$request->getVal( 'fulltext' ) &&
141 $request->getVal( 'offset' ) === null
143 $url = $this->goResult( $term );
144 if ( $url !== null ) {
146 $out->redirect( $url );
151 $this->setupPage( $term );
153 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
154 $searchForwardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
155 if ( $searchForwardUrl ) {
156 $url = str_replace( '$1', urlencode( $term ), $searchForwardUrl );
157 $out->redirect( $url );
162 $this->msg( 'search-external' )->escaped() .
164 "<p class='mw-searchdisabled'>" .
165 $this->msg( 'searchdisabled' )->escaped() .
167 $this->msg( 'googlesearch' )->rawParams(
168 htmlspecialchars( $term ),
170 $this->msg( 'searchbutton' )->escaped()
179 $this->showResults( $term );
183 * Set up basic search parameters from the request and user settings.
185 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
187 public function load() {
188 $request = $this->getRequest();
189 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, '' );
190 $this->mPrefix
= $request->getVal( 'prefix', '' );
192 $user = $this->getUser();
194 # Extract manually requested namespaces
195 $nslist = $this->powerSearch( $request );
196 if ( !count( $nslist ) ) {
197 # Fallback to user preference
198 $nslist = $this->searchConfig
->userNamespaces( $user );
202 if ( !count( $nslist ) ) {
203 $profile = 'default';
206 $profile = $request->getVal( 'profile', $profile );
207 $profiles = $this->getSearchProfiles();
208 if ( $profile === null ) {
209 // BC with old request format
210 $profile = 'advanced';
211 foreach ( $profiles as $key => $data ) {
212 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
216 $this->namespaces
= $nslist;
217 } elseif ( $profile === 'advanced' ) {
218 $this->namespaces
= $nslist;
220 if ( isset( $profiles[$profile]['namespaces'] ) ) {
221 $this->namespaces
= $profiles[$profile]['namespaces'];
223 // Unknown profile requested
224 $profile = 'default';
225 $this->namespaces
= $profiles['default']['namespaces'];
229 $this->fulltext
= $request->getVal( 'fulltext' );
230 $this->runSuggestion
= (bool)$request->getVal( 'runsuggestion', true );
231 $this->profile
= $profile;
235 * If an exact title match can be found, jump straight ahead to it.
237 * @param string $term
238 * @return string|null The url to redirect to, or null if no redirect.
240 public function goResult( $term ) {
241 # If the string cannot be used to create a title
242 if ( is_null( Title
::newFromText( $term ) ) ) {
245 # If there's an exact or very near match, jump right there.
246 $title = $this->getSearchEngine()
247 ->getNearMatcher( $this->getConfig() )->getNearMatch( $term );
248 if ( is_null( $title ) ) {
252 if ( !Hooks
::run( 'SpecialSearchGoResult', [ $term, $title, &$url ] ) ) {
256 return $url === null ?
$title->getFullURL() : $url;
260 * @param string $term
262 public function showResults( $term ) {
265 if ( $this->searchEngineType
!== null ) {
266 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
269 $search = $this->getSearchEngine();
270 $search->setFeatureData( 'rewrite', $this->runSuggestion
);
271 $search->setLimitOffset( $this->limit
, $this->offset
);
272 $search->setNamespaces( $this->namespaces
);
273 $search->prefix
= $this->mPrefix
;
274 $term = $search->transformSearchTerm( $term );
275 $out = $this->getOutput();
277 Hooks
::run( 'SpecialSearchSetupEngine', [ $this, $this->profile
, $search ] );
278 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
279 # Hook requested termination
283 $title = Title
::newFromText( $term );
284 $showSuggestion = $title === null ||
!$title->isKnown();
285 $search->setShowSuggestion( $showSuggestion );
287 // fetch search results
288 $rewritten = $search->replacePrefixes( $term );
290 $titleMatches = $search->searchTitle( $rewritten );
291 $textMatches = $search->searchText( $rewritten );
294 if ( $textMatches instanceof Status
) {
295 $textStatus = $textMatches;
296 $textMatches = $textStatus->getValue();
299 // Get number of results
300 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
301 if ( $titleMatches ) {
302 $titleMatchesNum = $titleMatches->numRows();
303 $numTitleMatches = $titleMatches->getTotalHits();
305 if ( $textMatches ) {
306 $textMatchesNum = $textMatches->numRows();
307 $numTextMatches = $textMatches->getTotalHits();
309 $num = $titleMatchesNum +
$textMatchesNum;
310 $totalRes = $numTitleMatches +
$numTextMatches;
312 // start rendering the page
318 'id' => ( $this->isPowerSearch() ?
'powersearch' : 'search' ),
320 'action' => wfScript(),
323 # This is an awful awful ID name. It's not a table, but we
324 # named it poorly from when this was a table so now we're
326 "<div id='mw-search-top-table'>" .
327 $this->shortDialog( $term, $num, $totalRes ) .
329 $this->searchProfileTabs( $term ) .
330 $this->searchOptions( $term ) .
334 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
335 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
336 // Empty query -- straight view of search form
340 // did you mean... suggestions
341 if ( $textMatches ) {
342 if ( $textMatches->hasRewrittenQuery() ) {
343 $out->addHTML( $this->getDidYouMeanRewrittenHtml( $term, $textMatches ) );
344 } elseif ( $textMatches->hasSuggestion() ) {
345 $out->addHTML( $this->getDidYouMeanHtml( $textMatches ) );
349 $out->addHTML( "<div class='searchresults'>" );
351 $hasErrors = $textStatus && $textStatus->getErrors();
352 $hasOtherResults = $textMatches &&
353 $textMatches->hasInterwikiResults( SearchResultSet
::INLINE_RESULTS
);
356 list( $error, $warning ) = $textStatus->splitByErrorType();
357 if ( $error->getErrors() ) {
358 $out->addHTML( Html
::rawElement(
360 [ 'class' => 'errorbox' ],
361 $error->getHTML( 'search-error' )
364 if ( $warning->getErrors() ) {
365 $out->addHTML( Html
::rawElement(
367 [ 'class' => 'warningbox' ],
368 $warning->getHTML( 'search-warning' )
373 // Show the create link ahead
374 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
376 // If we have no results and have not already displayed an error message
377 if ( $num === 0 && !$hasErrors ) {
378 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", [
379 $hasOtherResults ?
'search-nonefound-thiswiki' : 'search-nonefound',
380 wfEscapeWikiText( $term )
384 Hooks
::run( 'SpecialSearchResults', [ $term, $titleMatches, $textMatches ] );
386 $out->parserOptions()->setEditSection( false );
387 if ( $titleMatches ) {
388 if ( $numTitleMatches > 0 ) {
389 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
390 $out->addHTML( $this->showMatches( $titleMatches ) );
392 $titleMatches->free();
395 if ( $textMatches ) {
396 // output appropriate heading
397 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
398 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
399 // if no title matches the heading is redundant
400 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
404 if ( $numTextMatches > 0 ) {
405 $search->augmentSearchResults( $textMatches );
406 $out->addHTML( $this->showMatches( $textMatches ) );
409 // show secondary interwiki results if any
410 if ( $textMatches->hasInterwikiResults( SearchResultSet
::SECONDARY_RESULTS
) ) {
411 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(
412 SearchResultSet
::SECONDARY_RESULTS
), $term ) );
416 if ( $hasOtherResults ) {
417 foreach ( $textMatches->getInterwikiResults( SearchResultSet
::INLINE_RESULTS
)
418 as $interwiki => $interwikiResult ) {
419 if ( $interwikiResult instanceof Status ||
$interwikiResult->numRows() == 0 ) {
420 // ignore bad interwikis for now
424 $out->addHTML( $this->showMatches( $interwikiResult, $interwiki ) );
428 if ( $textMatches ) {
429 $textMatches->free();
432 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
435 if ( $totalRes > $this->limit ||
$this->offset
) {
436 $prevnext = $this->getLanguage()->viewPrevNext(
437 $this->getPageTitle(),
440 $this->powerSearchOptions() +
[ 'search' => $term ],
441 $this->limit +
$this->offset
>= $totalRes
443 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
446 // Close <div class='searchresults'>
447 $out->addHTML( "</div>" );
449 Hooks
::run( 'SpecialSearchResultsAppend', [ $this, $out, $term ] );
453 * Produce wiki header for interwiki results
454 * @param string $interwiki Interwiki name
455 * @param SearchResultSet $interwikiResult The result set
458 protected function interwikiHeader( $interwiki, $interwikiResult ) {
459 // TODO: we need to figure out how to name wikis correctly
460 $wikiMsg = $this->msg( 'search-interwiki-results-' . $interwiki )->parse();
461 return "<p class=\"mw-search-interwiki-header mw-search-visualclear\">\n$wikiMsg</p>";
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 = [ 'search' => $textMatches->getSuggestionQuery() ];
471 if ( $this->fulltext
=== null ) {
472 $params['fulltext'] = 'Search';
474 $params['fulltext'] = $this->fulltext
;
476 $stParams = array_merge( $params, $this->powerSearchOptions() );
478 $linkRenderer = $this->getLinkRenderer();
480 $snippet = $textMatches->getSuggestionSnippet() ?
: null;
481 if ( $snippet !== null ) {
482 $snippet = new HtmlArmor( $snippet );
485 $suggest = $linkRenderer->makeKnownLink(
486 $this->getPageTitle(),
488 [ 'id' => 'mw-search-DYM-suggestion' ],
492 # HTML of did you mean... search suggestion link
493 return Html
::rawElement(
495 [ 'class' => 'searchdidyoumean' ],
496 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
501 * Generates HTML shown to user when their query has been internally rewritten,
502 * and the results of the rewritten query are being returned.
504 * @param string $term The users search input
505 * @param SearchResultSet $textMatches The response to the users initial search request
506 * @return string HTML linking the user to their original $term query, and the one
507 * suggested by $textMatches.
509 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet
$textMatches ) {
510 // Showing results for '$rewritten'
511 // Search instead for '$orig'
513 $params = [ 'search' => $textMatches->getQueryAfterRewrite() ];
514 if ( $this->fulltext
=== null ) {
515 $params['fulltext'] = 'Search';
517 $params['fulltext'] = $this->fulltext
;
519 $stParams = array_merge( $params, $this->powerSearchOptions() );
521 $linkRenderer = $this->getLinkRenderer();
523 $snippet = $textMatches->getQueryAfterRewriteSnippet() ?
: null;
524 if ( $snippet !== null ) {
525 $snippet = new HtmlArmor( $snippet );
528 $rewritten = $linkRenderer->makeKnownLink(
529 $this->getPageTitle(),
531 [ 'id' => 'mw-search-DYM-rewritten' ],
535 $stParams['search'] = $term;
536 $stParams['runsuggestion'] = 0;
537 $original = $linkRenderer->makeKnownLink(
538 $this->getPageTitle(),
540 [ 'id' => 'mw-search-DYM-original' ],
544 return Html
::rawElement(
546 [ 'class' => 'searchdidyoumean' ],
547 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
552 * @param Title $title
553 * @param int $num The number of search results found
554 * @param null|SearchResultSet $titleMatches Results from title search
555 * @param null|SearchResultSet $textMatches Results from text search
557 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
558 // show direct page/create link if applicable
560 // Check DBkey !== '' in case of fragment link only.
561 if ( is_null( $title ) ||
$title->getDBkey() === ''
562 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
563 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
566 // preserve the paragraph for margins etc...
567 $this->getOutput()->addHTML( '<p></p>' );
572 $messageName = 'searchmenu-new-nocreate';
573 $linkClass = 'mw-search-createlink';
575 if ( !$title->isExternal() ) {
576 if ( $title->isKnown() ) {
577 $messageName = 'searchmenu-exists';
578 $linkClass = 'mw-search-exists';
579 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
580 $messageName = 'searchmenu-new';
586 wfEscapeWikiText( $title->getPrefixedText() ),
587 Message
::numParam( $num )
589 Hooks
::run( 'SpecialSearchCreateLink', [ $title, &$params ] );
591 // Extensions using the hook might still return an empty $messageName
592 if ( $messageName ) {
593 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
595 // preserve the paragraph for margins etc...
596 $this->getOutput()->addHTML( '<p></p>' );
601 * Sets up everything for the HTML output page including styles, javascript,
604 * @param string $term
606 protected function setupPage( $term ) {
607 $out = $this->getOutput();
610 $this->outputHeader();
611 // TODO: Is this true? The namespace remember uses a user token
613 $out->allowClickjacking();
614 $this->addHelpLink( 'Help:Searching' );
616 if ( strval( $term ) !== '' ) {
617 $out->setPageTitle( $this->msg( 'searchresults' ) );
618 $out->setHTMLTitle( $this->msg( 'pagetitle' )
619 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
620 ->inContentLanguage()->text()
624 $out->addJsConfigVars( [ 'searchTerm' => $term ] );
625 $out->addModules( 'mediawiki.special.search' );
626 $out->addModuleStyles( [
627 'mediawiki.special', 'mediawiki.special.search.styles', 'mediawiki.ui', 'mediawiki.ui.button',
628 'mediawiki.ui.input', 'mediawiki.widgets.SearchInputWidget.styles',
633 * Return true if current search is a power (advanced) search
637 protected function isPowerSearch() {
638 return $this->profile
=== 'advanced';
642 * Extract "power search" namespace settings from the request object,
643 * returning a list of index numbers to search.
645 * @param WebRequest $request
648 protected function powerSearch( &$request ) {
650 foreach ( $this->searchConfig
->searchableNamespaces() as $ns => $name ) {
651 if ( $request->getCheck( 'ns' . $ns ) ) {
660 * Reconstruct the 'power search' options for links
664 protected function powerSearchOptions() {
666 if ( $this->isPowerSearch() ) {
667 foreach ( $this->namespaces
as $n ) {
671 $opt['profile'] = $this->profile
;
674 return $opt +
$this->extraParams
;
678 * Save namespace preferences when we're supposed to
680 * @return bool Whether we wrote something
682 protected function saveNamespaces() {
683 $user = $this->getUser();
684 $request = $this->getRequest();
686 if ( $user->isLoggedIn() &&
687 $user->matchEditToken(
688 $request->getVal( 'nsRemember' ),
693 // Reset namespace preferences: namespaces are not searched
694 // when they're not mentioned in the URL parameters.
695 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
696 $user->setOption( 'searchNs' . $n, false );
698 // The request parameters include all the namespaces to be searched.
699 // Even if they're the same as an existing profile, they're not eaten.
700 foreach ( $this->namespaces
as $n ) {
701 $user->setOption( 'searchNs' . $n, true );
704 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
705 $user->saveSettings();
715 * Show whole set of results
717 * @param SearchResultSet $matches
718 * @param string $interwiki Interwiki name
722 protected function showMatches( $matches, $interwiki = null ) {
725 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
727 $result = $matches->next();
728 $pos = $this->offset
;
730 if ( $result && $interwiki ) {
731 $out .= $this->interwikiHeader( $interwiki, $matches );
734 $out .= "<ul class='mw-search-results'>\n";
735 $widget = new \MediaWiki\Widget\Search\
FullSearchResultWidget(
737 $this->getLinkRenderer()
740 $out .= $widget->render( $result, $terms, $pos++
);
741 $result = $matches->next();
745 // convert the whole thing to desired language variant
746 $out = $wgContLang->convert( $out );
752 * Extract custom captions from search-interwiki-custom message
754 protected function getCustomCaptions() {
755 if ( is_null( $this->customCaptions
) ) {
756 $this->customCaptions
= [];
757 // format per line <iwprefix>:<caption>
758 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
759 foreach ( $customLines as $line ) {
760 $parts = explode( ":", $line, 2 );
761 if ( count( $parts ) == 2 ) { // validate line
762 $this->customCaptions
[$parts[0]] = $parts[1];
769 * Show results from other wikis
771 * @param SearchResultSet|array $matches
772 * @param string $terms
776 protected function showInterwiki( $matches, $terms ) {
779 // work out custom project captions
780 $this->getCustomCaptions();
782 if ( !is_array( $matches ) ) {
783 $matches = [ $matches ];
787 foreach ( $matches as $set ) {
788 $result = $set->next();
790 if ( !$result->isBrokenTitle() ) {
791 $iwResults[$result->getTitle()->getInterwiki()][] = $result;
793 $result = $set->next();
798 $widget = new MediaWiki\Widget\Search\
SimpleSearchResultWidget(
800 $this->getLinkRenderer()
802 foreach ( $iwResults as $iwPrefix => $results ) {
803 $out .= $this->iwHeaderHtml( $iwPrefix, $terms );
804 $out .= "<ul class='mw-search-iwresults'>";
805 foreach ( $results as $result ) {
806 // This makes the bold asumption interwiki results are never paginated.
807 // That's currently true, but could change at some point?
808 $out .= $widget->render( $result, $terms, 0 );
814 "<div id='mw-search-interwiki'>" .
815 "<div id='mw-search-interwiki-caption'>" .
816 $this->msg( 'search-interwiki-caption' )->escaped() .
821 // convert the whole thing to desired language variant
822 return $wgContLang->convert( $out );
826 * @param string $iwPrefix The interwiki prefix to render a header for
827 * @param string $terms The user-provided search terms
829 protected function iwHeaderHtml( $iwPrefix, $terms ) {
830 if ( isset( $this->customCaptions
[$iwPrefix] ) ) {
831 $caption = $this->customCaptions
[$iwPrefix];
833 $iwLookup = MediaWiki\MediaWikiServices
::getInstance()->getInterwikiLookup();
834 $interwiki = $iwLookup->fetch( $iwPrefix );
835 $parsed = wfParseUrl( wfExpandUrl( $interwiki ?
$interwiki->getURL() : '/' ) );
836 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
838 $searchLink = Linker
::linkKnown(
839 Title
::newFromText( "$iwPrefix:Special:Search" ),
840 $this->msg( 'search-interwiki-more' )->text(),
848 "<div class='mw-search-interwiki-project'>" .
849 "<span class='mw-search-interwiki-more'>{$searchLink}</span>" .
855 * Generates the power search box at [[Special:Search]]
857 * @param string $term Search term
859 * @return string HTML form
861 protected function powerSearchBox( $term, $opts ) {
864 // Groups namespaces into rows according to subject
866 foreach ( $this->searchConfig
->searchableNamespaces() as $namespace => $name ) {
867 $subject = MWNamespace
::getSubject( $namespace );
868 if ( !array_key_exists( $subject, $rows ) ) {
869 $rows[$subject] = "";
872 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
874 $name = $this->msg( 'blanknamespace' )->text();
878 Xml
::openElement( 'td' ) .
882 "mw-search-ns{$namespace}",
883 in_array( $namespace, $this->namespaces
)
885 Xml
::closeElement( 'td' );
888 $rows = array_values( $rows );
889 $numRows = count( $rows );
891 // Lays out namespaces in multiple floating two-column tables so they'll
892 // be arranged nicely while still accommodating different screen widths
893 $namespaceTables = '';
894 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
895 $namespaceTables .= Xml
::openElement( 'table' );
897 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
898 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
901 $namespaceTables .= Xml
::closeElement( 'table' );
904 $showSections = [ 'namespaceTables' => $namespaceTables ];
906 Hooks
::run( 'SpecialSearchPowerBox', [ &$showSections, $term, $opts ] );
909 foreach ( $opts as $key => $value ) {
910 $hidden .= Html
::hidden( $key, $value );
913 # Stuff to feed saveNamespaces()
915 $user = $this->getUser();
916 if ( $user->isLoggedIn() ) {
917 $remember .= Xml
::checkLabel(
918 $this->msg( 'powersearch-remember' )->text(),
920 'mw-search-powersearch-remember',
922 // The token goes here rather than in a hidden field so it
923 // is only sent when necessary (not every form submission).
924 [ 'value' => $user->getEditToken(
931 // Return final output
932 return Xml
::openElement( 'fieldset', [ 'id' => 'mw-searchoptions' ] ) .
933 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
934 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
935 Xml
::element( 'div', [ 'id' => 'mw-search-togglebox' ], '', false ) .
936 Xml
::element( 'div', [ 'class' => 'divider' ], '', false ) .
937 implode( Xml
::element( 'div', [ 'class' => 'divider' ], '', false ), $showSections ) .
939 Xml
::element( 'div', [ 'class' => 'divider' ], '', false ) .
941 Xml
::closeElement( 'fieldset' );
947 protected function getSearchProfiles() {
948 // Builds list of Search Types (profiles)
949 $nsAllSet = array_keys( $this->searchConfig
->searchableNamespaces() );
950 $defaultNs = $this->searchConfig
->defaultNamespaces();
953 'message' => 'searchprofile-articles',
954 'tooltip' => 'searchprofile-articles-tooltip',
955 'namespaces' => $defaultNs,
956 'namespace-messages' => $this->searchConfig
->namespacesAsText(
961 'message' => 'searchprofile-images',
962 'tooltip' => 'searchprofile-images-tooltip',
963 'namespaces' => [ NS_FILE
],
966 'message' => 'searchprofile-everything',
967 'tooltip' => 'searchprofile-everything-tooltip',
968 'namespaces' => $nsAllSet,
971 'message' => 'searchprofile-advanced',
972 'tooltip' => 'searchprofile-advanced-tooltip',
973 'namespaces' => self
::NAMESPACES_CURRENT
,
977 Hooks
::run( 'SpecialSearchProfiles', [ &$profiles ] );
979 foreach ( $profiles as &$data ) {
980 if ( !is_array( $data['namespaces'] ) ) {
983 sort( $data['namespaces'] );
990 * @param string $term
993 protected function searchProfileTabs( $term ) {
994 $out = Html
::element( 'div', [ 'class' => 'mw-search-visualclear' ] ) .
995 Xml
::openElement( 'div', [ 'class' => 'mw-search-profile-tabs' ] );
998 if ( $this->startsWithImage( $term ) ) {
1000 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1003 $profiles = $this->getSearchProfiles();
1004 $lang = $this->getLanguage();
1006 // Outputs XML for Search Types
1007 $out .= Xml
::openElement( 'div', [ 'class' => 'search-types' ] );
1008 $out .= Xml
::openElement( 'ul' );
1009 foreach ( $profiles as $id => $profile ) {
1010 if ( !isset( $profile['parameters'] ) ) {
1011 $profile['parameters'] = [];
1013 $profile['parameters']['profile'] = $id;
1015 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1016 $lang->commaList( $profile['namespace-messages'] ) : null;
1020 'class' => $this->profile
=== $id ?
'current' : 'normal'
1022 $this->makeSearchLink(
1025 $this->msg( $profile['message'] )->text(),
1026 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1027 $profile['parameters']
1031 $out .= Xml
::closeElement( 'ul' );
1032 $out .= Xml
::closeElement( 'div' );
1033 $out .= Xml
::element( 'div', [ 'style' => 'clear:both' ], '', false );
1034 $out .= Xml
::closeElement( 'div' );
1040 * @param string $term Search term
1043 protected function searchOptions( $term ) {
1046 $opts['profile'] = $this->profile
;
1048 if ( $this->isPowerSearch() ) {
1049 $out .= $this->powerSearchBox( $term, $opts );
1052 Hooks
::run( 'SpecialSearchProfileForm', [ $this, &$form, $this->profile
, $term, $opts ] );
1060 * @param string $term
1061 * @param int $resultsShown
1062 * @param int $totalNum
1065 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1066 $searchWidget = new MediaWiki\Widget\
SearchInputWidget( [
1067 'id' => 'searchText',
1069 'autofocus' => trim( $term ) === '',
1071 'dataLocation' => 'content',
1072 'infusable' => true,
1075 $layout = new OOUI\
ActionFieldLayout( $searchWidget, new OOUI\
ButtonInputWidget( [
1077 'label' => $this->msg( 'searchbutton' )->text(),
1078 'flags' => [ 'progressive', 'primary' ],
1084 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
1085 Html
::hidden( 'profile', $this->profile
) .
1086 Html
::hidden( 'fulltext', 'Search' ) .
1090 if ( $totalNum > 0 && $this->offset
< $totalNum ) {
1091 $top = $this->msg( 'search-showingresults' )
1092 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1093 ->numParams( $resultsShown )
1095 $out .= Xml
::tags( 'div', [ 'class' => 'results-info' ], $top );
1102 * Make a search link with some target namespaces
1104 * @param string $term
1105 * @param array $namespaces Ignored
1106 * @param string $label Link's text
1107 * @param string $tooltip Link's tooltip
1108 * @param array $params Query string parameters
1109 * @return string HTML fragment
1111 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = [] ) {
1113 foreach ( $namespaces as $n ) {
1114 $opt['ns' . $n] = 1;
1117 $stParams = array_merge(
1120 'fulltext' => $this->msg( 'search' )->text()
1125 return Xml
::element(
1128 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1136 * Check if query starts with image: prefix
1138 * @param string $term The string to check
1141 protected function startsWithImage( $term ) {
1144 $parts = explode( ':', $term );
1145 if ( count( $parts ) > 1 ) {
1146 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1155 * @return SearchEngine
1157 public function getSearchEngine() {
1158 if ( $this->searchEngine
=== null ) {
1159 $this->searchEngine
= $this->searchEngineType ?
1160 MediaWikiServices
::getInstance()->getSearchEngineFactory()->create( $this->searchEngineType
) :
1161 MediaWikiServices
::getInstance()->newSearchEngine();
1164 return $this->searchEngine
;
1168 * Current search profile.
1169 * @return null|string
1171 function getProfile() {
1172 return $this->profile
;
1176 * Current namespaces.
1179 function getNamespaces() {
1180 return $this->namespaces
;
1184 * Users of hook SpecialSearchSetupEngine can use this to
1185 * add more params to links to not lose selection when
1186 * user navigates search results.
1189 * @param string $key
1190 * @param mixed $value
1192 public function setExtraParam( $key, $value ) {
1193 $this->extraParams
[$key] = $value;
1196 protected function getGroupName() {