3 * Copyright © 2004 Brooke Vibber <bvibber@wikimedia.org>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 namespace MediaWiki\Specials
;
26 use MediaWiki\Config\ServiceOptions
;
27 use MediaWiki\Content\IContentHandlerFactory
;
28 use MediaWiki\Deferred\DeferredUpdates
;
29 use MediaWiki\Html\Html
;
30 use MediaWiki\Interwiki\InterwikiLookup
;
31 use MediaWiki\Languages\LanguageConverterFactory
;
32 use MediaWiki\MainConfigNames
;
33 use MediaWiki\Message\Message
;
34 use MediaWiki\Output\OutputPage
;
35 use MediaWiki\Request\WebRequest
;
36 use MediaWiki\Search\SearchResultThumbnailProvider
;
37 use MediaWiki\Search\SearchWidgets\BasicSearchResultSetWidget
;
38 use MediaWiki\Search\SearchWidgets\DidYouMeanWidget
;
39 use MediaWiki\Search\SearchWidgets\FullSearchResultWidget
;
40 use MediaWiki\Search\SearchWidgets\InterwikiSearchResultSetWidget
;
41 use MediaWiki\Search\SearchWidgets\InterwikiSearchResultWidget
;
42 use MediaWiki\Search\SearchWidgets\SearchFormWidget
;
43 use MediaWiki\Search\TitleMatcher
;
44 use MediaWiki\SpecialPage\SpecialPage
;
45 use MediaWiki\Status\Status
;
46 use MediaWiki\Title\NamespaceInfo
;
47 use MediaWiki\Title\Title
;
48 use MediaWiki\User\Options\UserOptionsManager
;
49 use MediaWiki\Xml\Xml
;
52 use SearchEngineConfig
;
53 use SearchEngineFactory
;
54 use Wikimedia\Rdbms\ReadOnlyMode
;
57 * Run text & title search and display the output
59 * @ingroup SpecialPage
62 class SpecialSearch
extends SpecialPage
{
64 * Current search profile. Search profile is just a name that identifies
65 * the active search tab on the search page (content, discussions...)
66 * For users tt replaces the set of enabled namespaces from the query
67 * string when applicable. Extensions can add new profiles with hooks
68 * with custom search options just for that profile.
73 /** @var SearchEngine Search engine */
74 protected $searchEngine;
76 /** @var string|null Search engine type, if not default */
77 protected $searchEngineType = null;
79 /** @var array For links */
80 protected $extraParams = [];
83 * @var string The prefix url parameter. Set on the searcher and the
84 * is expected to treat it as prefix filter on titles.
89 protected int $offset;
94 protected $namespaces;
104 protected $sort = SearchEngine
::DEFAULT_SORT
;
109 protected $runSuggestion = true;
112 * Search engine configurations.
113 * @var SearchEngineConfig
115 protected $searchConfig;
117 private SearchEngineFactory
$searchEngineFactory;
118 private NamespaceInfo
$nsInfo;
119 private IContentHandlerFactory
$contentHandlerFactory;
120 private InterwikiLookup
$interwikiLookup;
121 private ReadOnlyMode
$readOnlyMode;
122 private UserOptionsManager
$userOptionsManager;
123 private LanguageConverterFactory
$languageConverterFactory;
124 private RepoGroup
$repoGroup;
125 private SearchResultThumbnailProvider
$thumbnailProvider;
126 private TitleMatcher
$titleMatcher;
129 * @var Status Holds any parameter validation errors that should
130 * be displayed back to the user.
134 private const NAMESPACES_CURRENT
= 'sense';
137 * @param SearchEngineConfig $searchConfig
138 * @param SearchEngineFactory $searchEngineFactory
139 * @param NamespaceInfo $nsInfo
140 * @param IContentHandlerFactory $contentHandlerFactory
141 * @param InterwikiLookup $interwikiLookup
142 * @param ReadOnlyMode $readOnlyMode
143 * @param UserOptionsManager $userOptionsManager
144 * @param LanguageConverterFactory $languageConverterFactory
145 * @param RepoGroup $repoGroup
146 * @param SearchResultThumbnailProvider $thumbnailProvider
147 * @param TitleMatcher $titleMatcher
149 public function __construct(
150 SearchEngineConfig
$searchConfig,
151 SearchEngineFactory
$searchEngineFactory,
152 NamespaceInfo
$nsInfo,
153 IContentHandlerFactory
$contentHandlerFactory,
154 InterwikiLookup
$interwikiLookup,
155 ReadOnlyMode
$readOnlyMode,
156 UserOptionsManager
$userOptionsManager,
157 LanguageConverterFactory
$languageConverterFactory,
158 RepoGroup
$repoGroup,
159 SearchResultThumbnailProvider
$thumbnailProvider,
160 TitleMatcher
$titleMatcher
162 parent
::__construct( 'Search' );
163 $this->searchConfig
= $searchConfig;
164 $this->searchEngineFactory
= $searchEngineFactory;
165 $this->nsInfo
= $nsInfo;
166 $this->contentHandlerFactory
= $contentHandlerFactory;
167 $this->interwikiLookup
= $interwikiLookup;
168 $this->readOnlyMode
= $readOnlyMode;
169 $this->userOptionsManager
= $userOptionsManager;
170 $this->languageConverterFactory
= $languageConverterFactory;
171 $this->repoGroup
= $repoGroup;
172 $this->thumbnailProvider
= $thumbnailProvider;
173 $this->titleMatcher
= $titleMatcher;
179 * @param string|null $par
181 public function execute( $par ) {
182 $request = $this->getRequest();
183 $out = $this->getOutput();
185 // Fetch the search term
186 $term = str_replace( "\n", " ", $request->getText( 'search' ) );
188 // Historically search terms have been accepted not only in the search query
189 // parameter, but also as part of the primary url. This can have PII implications
190 // in releasing page view data. As such issue a 301 redirect to the correct
192 if ( $par !== null && $par !== '' && $term === '' ) {
193 $query = $request->getQueryValues();
194 unset( $query['title'] );
195 // Strip underscores from title parameter; most of the time we'll want
196 // text form here. But don't strip underscores from actual text params!
197 $query['search'] = str_replace( '_', ' ', $par );
198 $out->redirect( $this->getPageTitle()->getFullURL( $query ), 301 );
202 // Need to load selected namespaces before handling nsRemember
204 // TODO: This performs database actions on GET request, which is going to
205 // be a problem for our multi-datacenter work.
206 if ( $request->getCheck( 'nsRemember' ) ) {
207 $this->saveNamespaces();
208 // Remove the token from the URL to prevent the user from inadvertently
209 // exposing it (e.g. by pasting it into a public wiki page) or undoing
210 // later settings changes (e.g. by reloading the page).
211 $query = $request->getQueryValues();
212 unset( $query['title'], $query['nsRemember'] );
213 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
217 if ( !$request->getVal( 'fulltext' ) && !$request->getCheck( 'offset' ) ) {
218 $url = $this->goResult( $term );
219 if ( $url !== null ) {
221 $out->redirect( $url );
224 // No match. If it could plausibly be a title
225 // run the No go match hook.
226 $title = Title
::newFromText( $term );
227 if ( $title !== null ) {
228 $this->getHookRunner()->onSpecialSearchNogomatch( $title );
232 $this->setupPage( $term );
234 if ( $this->getConfig()->get( MainConfigNames
::DisableTextSearch
) ) {
235 $searchForwardUrl = $this->getConfig()->get( MainConfigNames
::SearchForwardUrl
);
236 if ( $searchForwardUrl ) {
237 $url = str_replace( '$1', urlencode( $term ), $searchForwardUrl );
238 $out->redirect( $url );
240 $out->addHTML( $this->showGoogleSearch( $term ) );
246 $this->showResults( $term );
250 * Output a google search form if search is disabled
252 * @param string $term Search term
253 * @todo FIXME Maybe we should get rid of this raw html message at some future time
254 * @return string HTML
255 * @return-taint escaped
257 private function showGoogleSearch( $term ) {
258 return "<fieldset>" .
260 $this->msg( 'search-external' )->escaped() .
262 "<p class='mw-searchdisabled'>" .
263 $this->msg( 'searchdisabled' )->escaped() .
265 // googlesearch is part of $wgRawHtmlMessages and safe to use as is here
266 $this->msg( 'googlesearch' )->rawParams(
267 htmlspecialchars( $term ),
269 $this->msg( 'searchbutton' )->escaped()
275 * Set up basic search parameters from the request and user settings.
277 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
279 public function load() {
280 $this->loadStatus
= new Status();
282 $request = $this->getRequest();
283 $this->searchEngineType
= $request->getVal( 'srbackend' );
285 [ $this->limit
, $this->offset
] = $request->getLimitOffsetForUser(
290 $this->mPrefix
= $request->getVal( 'prefix', '' );
291 if ( $this->mPrefix
!== '' ) {
292 $this->setExtraParam( 'prefix', $this->mPrefix
);
295 $sort = $request->getVal( 'sort', SearchEngine
::DEFAULT_SORT
);
296 $validSorts = $this->getSearchEngine()->getValidSorts();
297 if ( !in_array( $sort, $validSorts ) ) {
298 $this->loadStatus
->warning( 'search-invalid-sort-order', $sort,
299 implode( ', ', $validSorts ) );
300 } elseif ( $sort !== $this->sort
) {
302 $this->setExtraParam( 'sort', $this->sort
);
305 $user = $this->getUser();
307 # Extract manually requested namespaces
308 $nslist = $this->powerSearch( $request );
309 if ( $nslist === [] ) {
310 # Fallback to user preference
311 $nslist = $this->searchConfig
->userNamespaces( $user );
315 if ( $nslist === [] ) {
316 $profile = 'default';
319 $profile = $request->getVal( 'profile', $profile );
320 $profiles = $this->getSearchProfiles();
321 if ( $profile === null ) {
322 // BC with old request format
323 $profile = 'advanced';
324 foreach ( $profiles as $key => $data ) {
325 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
329 $this->namespaces
= $nslist;
330 } elseif ( $profile === 'advanced' ) {
331 $this->namespaces
= $nslist;
332 } elseif ( isset( $profiles[$profile]['namespaces'] ) ) {
333 $this->namespaces
= $profiles[$profile]['namespaces'];
335 // Unknown profile requested
336 $this->loadStatus
->warning( 'search-unknown-profile', $profile );
337 $profile = 'default';
338 $this->namespaces
= $profiles['default']['namespaces'];
341 $this->fulltext
= $request->getVal( 'fulltext' );
342 $this->runSuggestion
= (bool)$request->getVal( 'runsuggestion', '1' );
343 $this->profile
= $profile;
347 * If an exact title match can be found, jump straight ahead to it.
349 * @param string $term
350 * @return string|null The url to redirect to, or null if no redirect.
352 public function goResult( $term ) {
353 # If the string cannot be used to create a title
354 if ( Title
::newFromText( $term ) === null ) {
357 # If there's an exact or very near match, jump right there.
358 $title = $this->titleMatcher
->getNearMatch( $term );
359 if ( $title === null ) {
363 if ( !$this->getHookRunner()->onSpecialSearchGoResult( $term, $title, $url ) ) {
368 // If there is a preference set to NOT redirect on exact page match
369 // then return null (which prevents direction)
370 !$this->redirectOnExactMatch()
372 // ... ignore no-redirect preference if the exact page match is an interwiki link
373 && !$title->isExternal()
374 // ... ignore no-redirect preference if the exact page match is NOT in the main
375 // namespace AND there's a namespace in the search string
376 && !( $title->getNamespace() !== NS_MAIN
&& strpos( $term, ':' ) > 0 )
381 return $url ??
$title->getFullUrlForRedirect();
384 private function redirectOnExactMatch() {
385 if ( !$this->getConfig()->get( MainConfigNames
::SearchMatchRedirectPreference
) ) {
386 // If the preference for whether to redirect is disabled, use the default setting
387 return $this->userOptionsManager
->getDefaultOption(
388 'search-match-redirect',
392 // Otherwise use the user's preference
393 return $this->userOptionsManager
->getOption( $this->getUser(), 'search-match-redirect' );
398 * @param string $term
400 public function showResults( $term ) {
401 if ( $this->searchEngineType
!== null ) {
402 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
405 $out = $this->getOutput();
406 $widgetOptions = $this->getConfig()->get( MainConfigNames
::SpecialSearchFormOptions
);
407 $formWidget = new SearchFormWidget(
409 SearchFormWidget
::CONSTRUCTOR_OPTIONS
,
414 $this->getHookContainer(),
415 $this->languageConverterFactory
->getLanguageConverter( $this->getLanguage() ),
417 $this->getSearchProfiles()
419 $filePrefix = $this->getContentLanguage()->getFormattedNsText( NS_FILE
) . ':';
420 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
421 // Empty query -- straight view of search form
422 if ( !$this->getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
423 # Hook requested termination
427 // The form also contains the 'Showing results 0 - 20 of 1234' so we can
428 // only do the form render here for the empty $term case. Rendering
429 // the form when a search is provided is repeated below.
430 $out->addHTML( $formWidget->render(
431 $this->profile
, $term, 0, 0, false, $this->offset
, $this->isPowerSearch(), $widgetOptions
436 $engine = $this->getSearchEngine();
437 $engine->setFeatureData( 'rewrite', $this->runSuggestion
);
438 $engine->setLimitOffset( $this->limit
, $this->offset
);
439 $engine->setNamespaces( $this->namespaces
);
440 $engine->setSort( $this->sort
);
441 $engine->prefix
= $this->mPrefix
;
443 $this->getHookRunner()->onSpecialSearchSetupEngine( $this, $this->profile
, $engine );
444 if ( !$this->getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
445 # Hook requested termination
449 $title = Title
::newFromText( $term );
450 $languageConverter = $this->languageConverterFactory
->getLanguageConverter( $this->getContentLanguage() );
451 if ( $languageConverter->hasVariants() ) {
452 // findVariantLink will replace the link arg as well but we want to keep our original
453 // search string, use a copy in the $variantTerm var so that $term remains intact.
454 $variantTerm = $term;
455 $languageConverter->findVariantLink( $variantTerm, $title );
458 $showSuggestion = $title === null ||
!$title->isKnown();
459 $engine->setShowSuggestion( $showSuggestion );
461 $rewritten = $engine->replacePrefixes( $term );
462 if ( $rewritten !== $term ) {
463 wfDeprecatedMsg( 'SearchEngine::replacePrefixes() was overridden by ' .
464 get_class( $engine ) . ', this is deprecated since MediaWiki 1.32',
465 '1.32', false, false );
468 // fetch search results
469 $titleMatches = $engine->searchTitle( $rewritten );
470 $textMatches = $engine->searchText( $rewritten );
473 if ( $textMatches instanceof Status
) {
474 $textStatus = $textMatches;
475 $textMatches = $textStatus->getValue();
478 // Get number of results
479 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
480 $approxTotalRes = false;
481 if ( $titleMatches ) {
482 $titleMatchesNum = $titleMatches->numRows();
483 $numTitleMatches = $titleMatches->getTotalHits();
484 $approxTotalRes = $titleMatches->isApproximateTotalHits();
486 if ( $textMatches ) {
487 $textMatchesNum = $textMatches->numRows();
488 $numTextMatches = $textMatches->getTotalHits();
489 $approxTotalRes = $approxTotalRes ||
$textMatches->isApproximateTotalHits();
490 if ( $textMatchesNum > 0 ) {
491 $engine->augmentSearchResults( $textMatches );
494 $num = $titleMatchesNum +
$textMatchesNum;
495 $totalRes = $numTitleMatches +
$numTextMatches;
497 // start rendering the page
499 $out->addHTML( $formWidget->render(
500 $this->profile
, $term, $num, $totalRes, $approxTotalRes, $this->offset
, $this->isPowerSearch(),
504 // did you mean... suggestions
505 if ( $textMatches ) {
506 $dymWidget = new DidYouMeanWidget( $this );
507 $out->addHTML( $dymWidget->render( $term, $textMatches ) );
510 $hasSearchErrors = $textStatus && $textStatus->getMessages() !== [];
511 $hasInlineIwResults = $textMatches &&
512 $textMatches->hasInterwikiResults( ISearchResultSet
::INLINE_RESULTS
);
513 $hasSecondaryIwResults = $textMatches &&
514 $textMatches->hasInterwikiResults( ISearchResultSet
::SECONDARY_RESULTS
);
516 $classNames = [ 'searchresults' ];
517 if ( $hasSecondaryIwResults ) {
518 $classNames[] = 'mw-searchresults-has-iw';
520 if ( $this->offset
> 0 ) {
521 $classNames[] = 'mw-searchresults-has-offset';
523 $out->addHTML( '<div class="' . implode( ' ', $classNames ) . '">' );
525 $out->addHTML( '<div class="mw-search-results-info">' );
527 if ( $hasSearchErrors ||
$this->loadStatus
->getMessages() ) {
528 if ( $textStatus === null ) {
529 $textStatus = $this->loadStatus
;
531 $textStatus->merge( $this->loadStatus
);
533 [ $error, $warning ] = $textStatus->splitByErrorType();
534 if ( $error->getMessages() ) {
535 $out->addHTML( Html
::errorBox(
536 $error->getHTML( 'search-error' )
539 if ( $warning->getMessages() ) {
540 $out->addHTML( Html
::warningBox(
541 $warning->getHTML( 'search-warning' )
546 // If we have no results and have not already displayed an error message
547 if ( $num === 0 && !$hasSearchErrors ) {
548 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", [
549 $hasInlineIwResults ?
'search-nonefound-thiswiki' : 'search-nonefound',
550 wfEscapeWikiText( $term ),
555 // Show the create link ahead
556 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
558 $this->getHookRunner()->onSpecialSearchResults( $term, $titleMatches, $textMatches );
560 // Close <div class='mw-search-results-info'>
561 $out->addHTML( '</div>' );
563 // Although $num might be 0 there can still be secondary or inline
564 // results to display.
565 $linkRenderer = $this->getLinkRenderer();
566 $mainResultWidget = new FullSearchResultWidget(
569 $this->getHookContainer(),
571 $this->thumbnailProvider
,
572 $this->userOptionsManager
575 $sidebarResultWidget = new InterwikiSearchResultWidget( $this, $linkRenderer );
576 $sidebarResultsWidget = new InterwikiSearchResultSetWidget(
578 $sidebarResultWidget,
580 $this->interwikiLookup
,
581 $engine->getFeatureData( 'show-multimedia-search-results' )
584 $widget = new BasicSearchResultSetWidget( $this, $mainResultWidget, $sidebarResultsWidget );
586 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
587 $this->prevNextLinks( $totalRes, $textMatches, $term, 'mw-search-pager-top', $out );
589 $out->addHTML( $widget->render(
590 $term, $this->offset
, $titleMatches, $textMatches
593 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
594 $this->prevNextLinks( $totalRes, $textMatches, $term, 'mw-search-pager-bottom', $out );
596 // Close <div class='searchresults'>
597 $out->addHTML( "</div>" );
599 $this->getHookRunner()->onSpecialSearchResultsAppend( $this, $out, $term );
603 * @param Title|null $title
604 * @param int $num The number of search results found
605 * @param null|ISearchResultSet $titleMatches Results from title search
606 * @param null|ISearchResultSet $textMatches Results from text search
608 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
609 // show direct page/create link if applicable
611 // Check DBkey !== '' in case of fragment link only.
612 if ( $title === null ||
$title->getDBkey() === ''
613 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
614 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
617 // preserve the paragraph for margins etc...
618 $this->getOutput()->addHTML( '<p></p>' );
623 $messageName = 'searchmenu-new-nocreate';
624 $linkClass = 'mw-search-createlink';
626 if ( !$title->isExternal() ) {
627 if ( $title->isKnown() ) {
628 $messageName = 'searchmenu-exists';
629 $linkClass = 'mw-search-exists';
631 $this->contentHandlerFactory
->getContentHandler( $title->getContentModel() )
632 ->supportsDirectEditing()
633 && $this->getAuthority()->probablyCan( 'edit', $title )
635 $messageName = 'searchmenu-new';
641 wfEscapeWikiText( $title->getPrefixedText() ),
642 Message
::numParam( $num )
644 $this->getHookRunner()->onSpecialSearchCreateLink( $title, $params );
646 // Extensions using the hook might still return an empty $messageName
647 // @phan-suppress-next-line PhanRedundantCondition Might be unset by hook
648 if ( $messageName ) {
649 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
651 // preserve the paragraph for margins etc...
652 $this->getOutput()->addHTML( '<p></p>' );
657 * Sets up everything for the HTML output page including styles, javascript,
660 * @param string $term
662 protected function setupPage( $term ) {
663 $out = $this->getOutput();
666 $this->outputHeader();
667 // TODO: Is this true? The namespace remember uses a user token
669 $out->getMetadata()->setPreventClickjacking( false );
670 $this->addHelpLink( 'Help:Searching' );
672 if ( strval( $term ) !== '' ) {
673 $out->setPageTitleMsg( $this->msg( 'searchresults' ) );
674 $out->setHTMLTitle( $this->msg( 'pagetitle' )
675 ->plaintextParams( $this->msg( 'searchresults-title' )->plaintextParams( $term )->text() )
676 ->inContentLanguage()->text()
680 if ( $this->mPrefix
!== '' ) {
681 $subtitle = $this->msg( 'search-filter-title-prefix' )->plaintextParams( $this->mPrefix
);
682 $params = $this->powerSearchOptions();
683 unset( $params['prefix'] );
690 $subtitle .= Xml
::element(
693 'href' => $this->getPageTitle()->getLocalURL( $params ),
694 'title' => $this->msg( 'search-filter-title-prefix-reset' )->text(),
696 $this->msg( 'search-filter-title-prefix-reset' )->text()
699 $out->setSubtitle( $subtitle );
702 $out->addJsConfigVars( [ 'searchTerm' => $term ] );
703 $out->addModules( 'mediawiki.special.search' );
704 $out->addModuleStyles( [
705 'mediawiki.special', 'mediawiki.special.search.styles',
706 'mediawiki.widgets.SearchInputWidget.styles',
711 * Return true if current search is a power (advanced) search
715 protected function isPowerSearch() {
716 return $this->profile
=== 'advanced';
720 * Extract "power search" namespace settings from the request object,
721 * returning a list of index numbers to search.
723 * @param WebRequest &$request
726 protected function powerSearch( &$request ) {
728 foreach ( $this->searchConfig
->searchableNamespaces() as $ns => $name ) {
729 if ( $request->getCheck( 'ns' . $ns ) ) {
738 * Reconstruct the 'power search' options for links
739 * TODO: Instead of exposing this publicly, could we instead expose
740 * a function for creating search links?
744 public function powerSearchOptions() {
746 if ( $this->isPowerSearch() ) {
747 foreach ( $this->namespaces
as $n ) {
751 $opt['profile'] = $this->profile
;
754 return $opt +
$this->extraParams
;
758 * Save namespace preferences when we're supposed to
760 * @return bool Whether we wrote something
762 protected function saveNamespaces() {
763 $user = $this->getUser();
764 $request = $this->getRequest();
766 if ( $user->isRegistered() &&
767 $user->matchEditToken(
768 $request->getVal( 'nsRemember' ),
771 ) && !$this->readOnlyMode
->isReadOnly()
773 // Reset namespace preferences: namespaces are not searched
774 // when they're not mentioned in the URL parameters.
775 foreach ( $this->nsInfo
->getValidNamespaces() as $n ) {
776 $this->userOptionsManager
->setOption( $user, 'searchNs' . $n, false );
778 // The request parameters include all the namespaces to be searched.
779 // Even if they're the same as an existing profile, they're not eaten.
780 foreach ( $this->namespaces
as $n ) {
781 $this->userOptionsManager
->setOption( $user, 'searchNs' . $n, true );
784 DeferredUpdates
::addCallableUpdate( static function () use ( $user ) {
785 $user->saveSettings();
796 * @phan-return array<string,array{message:string,tooltip:string,namespaces:int|string|(int|string)[],namespace-messages?:string[]}>
798 protected function getSearchProfiles() {
799 // Builds list of Search Types (profiles)
800 $nsAllSet = array_keys( $this->searchConfig
->searchableNamespaces() );
801 $defaultNs = $this->searchConfig
->defaultNamespaces();
804 'message' => 'searchprofile-articles',
805 'tooltip' => 'searchprofile-articles-tooltip',
806 'namespaces' => $defaultNs,
807 'namespace-messages' => $this->searchConfig
->namespacesAsText(
812 'message' => 'searchprofile-images',
813 'tooltip' => 'searchprofile-images-tooltip',
814 'namespaces' => [ NS_FILE
],
817 'message' => 'searchprofile-everything',
818 'tooltip' => 'searchprofile-everything-tooltip',
819 'namespaces' => $nsAllSet,
822 'message' => 'searchprofile-advanced',
823 'tooltip' => 'searchprofile-advanced-tooltip',
824 'namespaces' => self
::NAMESPACES_CURRENT
,
828 $this->getHookRunner()->onSpecialSearchProfiles( $profiles );
830 foreach ( $profiles as &$data ) {
831 if ( !is_array( $data['namespaces'] ) ) {
834 sort( $data['namespaces'] );
843 * @return SearchEngine
845 public function getSearchEngine() {
846 if ( $this->searchEngine
=== null ) {
847 $this->searchEngine
= $this->searchEngineFactory
->create( $this->searchEngineType
);
850 return $this->searchEngine
;
854 * Current search profile.
855 * @return null|string
857 public function getProfile() {
858 return $this->profile
;
862 * Current namespaces.
865 public function getNamespaces() {
866 return $this->namespaces
;
870 * Users of hook SpecialSearchSetupEngine can use this to
871 * add more params to links to not lose selection when
872 * user navigates search results.
876 * @param mixed $value
878 public function setExtraParam( $key, $value ) {
879 $this->extraParams
[$key] = $value;
883 * The prefix value send to Special:Search using the 'prefix' URI param
884 * It means that the user is willing to search for pages whose titles start with
886 * (Used by the InputBox extension)
890 public function getPrefix() {
891 return $this->mPrefix
;
895 * @param null|int $totalRes
896 * @param null|ISearchResultSet $textMatches
897 * @param string $term
898 * @param string $class
899 * @param OutputPage $out
901 private function prevNextLinks(
903 ?ISearchResultSet
$textMatches,
908 if ( $totalRes > $this->limit ||
$this->offset
) {
909 // Allow matches to define the correct offset, as interleaved
910 // AB testing may require a different next page offset.
911 if ( $textMatches && $textMatches->getOffset() !== null ) {
912 $offset = $textMatches->getOffset();
914 $offset = $this->offset
;
917 // use the rewritten search term for subsequent page searches
918 $newSearchTerm = $term;
919 if ( $textMatches && $textMatches->hasRewrittenQuery() ) {
920 $newSearchTerm = $textMatches->getQueryAfterRewrite();
924 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable offset is not null
925 $this->buildPrevNextNavigation( $offset, $this->limit
,
926 $this->powerSearchOptions() +
[ 'search' => $newSearchTerm ],
927 $this->limit +
$this->offset
>= $totalRes );
928 $out->addHTML( "<div class='{$class}'>{$prevNext}</div>\n" );
932 protected function getGroupName() {
938 * Retain the old class name for backwards compatibility.
939 * @deprecated since 1.41
941 class_alias( SpecialSearch
::class, 'SpecialSearch' );