9namespace MediaWiki\Specials;
11use MediaWiki\Content\IContentHandlerFactory;
12use MediaWiki\Deferred\DeferredUpdates;
13use MediaWiki\FileRepo\RepoGroup;
14use MediaWiki\Html\Html;
15use MediaWiki\Interwiki\InterwikiLookup;
16use MediaWiki\Language\LanguageConverterFactory;
17use MediaWiki\MainConfigNames;
18use MediaWiki\Message\Message;
19use MediaWiki\Navigation\CodexPagerNavigationBuilder;
20use MediaWiki\Output\OutputPage;
21use MediaWiki\Request\WebRequest;
22use MediaWiki\Search\ISearchResultSet;
23use MediaWiki\Search\SearchEngine;
24use MediaWiki\Search\SearchEngineConfig;
25use MediaWiki\Search\SearchEngineFactory;
26use MediaWiki\Search\SearchResultThumbnailProvider;
27use MediaWiki\Search\SearchWidgets\BasicSearchResultSetWidget;
28use MediaWiki\Search\SearchWidgets\DidYouMeanWidget;
29use MediaWiki\Search\SearchWidgets\FullSearchResultWidget;
30use MediaWiki\Search\SearchWidgets\InterwikiSearchResultSetWidget;
31use MediaWiki\Search\SearchWidgets\InterwikiSearchResultWidget;
32use MediaWiki\Search\SearchWidgets\SearchFormWidget;
33use MediaWiki\Search\TitleMatcher;
34use MediaWiki\SpecialPage\SpecialPage;
35use MediaWiki\Status\Status;
36use MediaWiki\Title\NamespaceInfo;
37use MediaWiki\Title\Title;
38use MediaWiki\User\Options\UserOptionsManager;
40use Wikimedia\Rdbms\ReadOnlyMode;
90 protected $sort = SearchEngine::DEFAULT_SORT;
103 private const NAMESPACES_CURRENT =
'sense';
118 parent::__construct(
'Search' );
131 $term = str_replace(
"\n",
" ",
$request->getText(
'search' ) );
137 if ( $par !==
null && $par !==
'' && $term ===
'' ) {
138 $query =
$request->getQueryValues();
139 unset( $query[
'title'] );
142 $query[
'search'] = str_replace(
'_',
' ', $par );
151 if (
$request->getCheck(
'nsRemember' ) ) {
156 $query =
$request->getQueryValues();
157 unset( $query[
'title'], $query[
'nsRemember'] );
164 if (
$url !==
null ) {
171 $title = Title::newFromText( $term );
172 if ( $title !==
null ) {
181 if ( $searchForwardUrl ) {
182 $url = str_replace(
'$1', urlencode( $term ), $searchForwardUrl );
185 $out->
addHTML( Html::errorBox( Html::rawElement(
187 [
'class' =>
'mw-searchdisabled' ],
188 $this->
msg(
'searchdisabled', [
'mw:Special:MyLanguage/Manual:$wgSearchForwardUrl' ] )->parse()
190 $titleNs = count( $this->namespaces ) === 1 ? reset( $this->namespaces ) :
null;
191 $title = Title::newFromText( $term, $titleNs );
207 $this->loadStatus =
new StatusValue();
210 $this->searchEngineType =
$request->getVal(
'srbackend' );
217 $this->mPrefix =
$request->getVal(
'prefix',
'' );
218 if ( $this->mPrefix !==
'' ) {
222 $sort =
$request->getVal(
'sort', SearchEngine::DEFAULT_SORT );
224 if ( !in_array(
$sort, $validSorts ) ) {
225 $this->loadStatus->warning(
'search-invalid-sort-order',
$sort,
226 implode(
', ', $validSorts ) );
227 } elseif (
$sort !== $this->sort ) {
234 # Extract manually requested namespaces
236 if ( $nslist === [] ) {
237 # Fallback to user preference
238 $nslist = $this->searchConfig->userNamespaces( $user );
242 if ( $nslist === [] ) {
251 foreach ( $profiles as $key => $data ) {
252 if ( $nslist === $data[
'namespaces'] && $key !==
'advanced' ) {
256 $this->namespaces = $nslist;
257 } elseif (
$profile ===
'advanced' ) {
258 $this->namespaces = $nslist;
259 } elseif ( isset( $profiles[
$profile][
'namespaces'] ) ) {
260 $this->namespaces = $profiles[
$profile][
'namespaces'];
263 $this->loadStatus->warning(
'search-unknown-profile',
$profile );
265 $this->namespaces = $profiles[
'default'][
'namespaces'];
268 $this->fulltext =
$request->getVal(
'fulltext' );
269 $this->runSuggestion = (bool)
$request->getVal(
'runsuggestion',
'1' );
280 # If the string cannot be used to create a title
281 if ( Title::newFromText( $term ) ===
null ) {
284 # If there's an exact or very near match, jump right there.
285 $title = $this->titleMatcher->getNearMatch( $term );
286 if ( $title ===
null ) {
297 !$this->redirectOnExactMatch()
300 && !$title->isExternal()
303 && !( $title->getNamespace() !==
NS_MAIN && strpos( $term,
':' ) > 0 )
308 return $url ?? $title->getFullUrlForRedirect();
311 private function redirectOnExactMatch(): bool {
314 return (
bool)$this->userOptionsManager->getDefaultOption(
315 'search-match-redirect',
320 return $this->userOptionsManager->getBoolOption( $this->
getUser(),
'search-match-redirect' );
328 if ( $this->searchEngineType !==
null ) {
329 $this->
setExtraParam(
'srbackend', $this->searchEngineType );
338 $this->languageConverterFactory->getLanguageConverter( $this->getLanguage() ),
340 $this->getSearchProfiles()
343 if ( trim( $term ) ===
'' || $filePrefix === trim( $term ) ) {
345 if ( !$this->
getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
346 # Hook requested termination
353 $out->
addHTML( $formWidget->render(
354 $this->profile, $term, 0, 0,
false, $this->offset, $this->isPowerSearch(), $widgetOptions
360 $engine->setFeatureData(
'rewrite', $this->runSuggestion );
361 $engine->setLimitOffset( $this->limit, $this->offset );
362 $engine->setNamespaces( $this->namespaces );
363 $engine->setSort( $this->sort );
364 $engine->prefix = $this->mPrefix;
366 $this->
getHookRunner()->onSpecialSearchSetupEngine( $this, $this->profile, $engine );
367 if ( !$this->
getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
368 # Hook requested termination
372 $titleNs = count( $this->namespaces ) === 1 ? reset( $this->namespaces ) :
null;
373 $title = Title::newFromText( $term, $titleNs );
374 $languageConverter = $this->languageConverterFactory->getLanguageConverter( $this->
getContentLanguage() );
375 if ( $languageConverter->hasVariants() ) {
378 $variantTerm = $term;
379 $languageConverter->findVariantLink( $variantTerm, $title );
382 $showSuggestion = $title ===
null || !$title->isKnown();
383 $engine->setShowSuggestion( $showSuggestion );
386 $titleMatches = $engine->searchTitle( $term );
387 $textMatches = $engine->searchText( $term );
390 if ( $textMatches instanceof StatusValue ) {
391 $textStatus = $textMatches;
392 $textMatches = $textStatus->getValue();
395 if ( $textMatches && $textMatches->
numRows() ) {
396 $engine->augmentSearchResults( $textMatches );
399 $this->
getHookRunner()->onSpecialSearchResults( $term, $titleMatches, $textMatches );
402 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
403 $approxTotalRes =
false;
404 if ( $titleMatches ) {
405 $titleMatchesNum = $titleMatches->numRows();
406 $numTitleMatches = $titleMatches->getTotalHits();
407 $approxTotalRes = $titleMatches->isApproximateTotalHits();
409 if ( $textMatches ) {
410 $textMatchesNum = $textMatches->
numRows();
414 $num = $titleMatchesNum + $textMatchesNum;
415 $totalRes = $numTitleMatches + $numTextMatches;
419 $out->
addHTML( $formWidget->render(
420 $this->profile, $term, $num, $totalRes, $approxTotalRes, $this->offset, $this->isPowerSearch(),
425 if ( $textMatches ) {
427 $out->
addHTML( $dymWidget->render( $term, $textMatches ) );
430 $hasSearchErrors = $textStatus && $textStatus->getMessages() !== [];
431 $hasInlineIwResults = $textMatches &&
433 $hasSecondaryIwResults = $textMatches &&
436 $classNames = [
'searchresults' ];
437 if ( $hasSecondaryIwResults ) {
438 $classNames[] =
'mw-searchresults-has-iw';
440 if ( $this->offset > 0 ) {
441 $classNames[] =
'mw-searchresults-has-offset';
443 $out->
addHTML( Html::openElement(
'div', [
'class' => $classNames ] ) );
445 $out->
addHTML(
'<div class="mw-search-results-info">' );
447 if ( $hasSearchErrors || $this->loadStatus->getMessages() ) {
448 if ( $textStatus ===
null ) {
449 $textStatus = $this->loadStatus;
451 $textStatus->merge( $this->loadStatus );
453 [ $error, $warning ] = $textStatus->splitByErrorType();
454 if ( $error->getMessages() ) {
456 Status::wrap( $error )->getHTML(
'search-error' )
459 if ( $warning->getMessages() ) {
460 $out->
addHTML( Html::warningBox(
461 Status::wrap( $warning )->getHTML(
'search-warning' )
467 if ( $num === 0 && !$hasSearchErrors ) {
468 $out->
wrapWikiMsg(
"<p class=\"mw-search-nonefound\">\n$1</p>", [
469 $hasInlineIwResults ?
'search-nonefound-thiswiki' :
'search-nonefound',
476 $this->
showCreateLink( $title, $num, $titleMatches, $textMatches );
489 $this->thumbnailProvider,
490 $this->userOptionsManager
496 $sidebarResultWidget,
498 $this->interwikiLookup,
499 $engine->getFeatureData(
'show-multimedia-search-results' ) ??
false
504 $out->
addHTML(
'<div class="mw-search-visualclear"></div>' );
505 $this->prevNextLinks( $totalRes, $textMatches, $term,
'mw-search-pager-top', $out );
507 $out->
addHTML( $widget->render(
508 $term, $this->offset, $titleMatches, $textMatches
511 $out->
addHTML(
'<div class="mw-search-visualclear"></div>' );
512 $this->prevNextLinks( $totalRes, $textMatches, $term,
'mw-search-pager-bottom', $out );
517 $this->
getHookRunner()->onSpecialSearchResultsAppend( $this, $out, $term );
530 if ( $title ===
null || $title->getDBkey() ===
''
531 || ( $titleMatches !==
null && $titleMatches->searchContainedSyntax() )
536 $this->
getOutput()->addHTML(
'<p></p>' );
541 $messageName =
'searchmenu-new-nocreate';
542 $linkClass =
'mw-search-createlink';
544 if ( !$title->isExternal() ) {
545 if ( $title->isKnown() ) {
547 if ( $titleMatches && $titleMatches->numRows() > 0 ) {
548 $firstTitle = $titleMatches->extractTitles()[0] ??
null;
549 } elseif ( $textMatches && $textMatches->
numRows() > 0 ) {
553 if ( $firstTitle && $title->isSamePageAs( $firstTitle ) ) {
556 $messageName =
'searchmenu-exists';
557 $linkClass =
'mw-search-exists';
560 $this->contentHandlerFactory->getContentHandler( $title->getContentModel() )
561 ->supportsDirectEditing()
562 && $this->getAuthority()->probablyCan(
'edit', $title )
564 $messageName =
'searchmenu-new';
567 $messageName =
'searchmenu-new-external';
575 $this->
getHookRunner()->onSpecialSearchCreateLink( $title, $params );
578 if ( $messageName ) {
579 $this->
getOutput()->wrapWikiMsg(
"<p class=\"$linkClass\">\n$1</p>", $params );
596 $out->
getMetadata()->setPreventClickjacking(
false );
599 if ( strval( $term ) !==
'' ) {
602 ->plaintextParams( $this->
msg(
'searchresults-title' )->plaintextParams( $term )->text() )
603 ->inContentLanguage()->text()
607 if ( $this->mPrefix !==
'' ) {
608 $subtitle = $this->
msg(
'search-filter-title-prefix' )->plaintextParams( $this->mPrefix );
610 unset( $params[
'prefix'] );
620 'href' => $this->
getPageTitle()->getLocalURL( $params ),
621 'title' => $this->
msg(
'search-filter-title-prefix-reset' )->text(),
623 $this->
msg(
'search-filter-title-prefix-reset' )->text()
630 $out->
addModules(
'mediawiki.special.search' );
632 'mediawiki.special',
'mediawiki.special.search.styles',
633 'mediawiki.widgets.SearchInputWidget.styles',
635 'mediawiki.codex.messagebox.styles',
645 return $this->profile ===
'advanced';
657 foreach ( $this->searchConfig->searchableNamespaces() as $ns => $_ ) {
658 if (
$request->getCheck(
'ns' . $ns ) ) {
676 foreach ( $this->namespaces as $n ) {
680 $opt[
'profile'] = $this->profile;
683 return $opt + $this->extraParams;
695 if ( $user->isRegistered() &&
696 $user->matchEditToken(
700 ) && !$this->readOnlyMode->isReadOnly()
704 foreach ( $this->nsInfo->getValidNamespaces() as $n ) {
705 $this->userOptionsManager->setOption( $user,
'searchNs' . $n,
false );
709 foreach ( $this->namespaces as $n ) {
710 $this->userOptionsManager->setOption( $user,
'searchNs' . $n,
true );
713 DeferredUpdates::addCallableUpdate(
static function () use ( $user ) {
714 $user->saveSettings();
729 $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
730 $defaultNs = $this->searchConfig->defaultNamespaces();
733 'message' =>
'searchprofile-articles',
734 'tooltip' =>
'searchprofile-articles-tooltip',
735 'namespaces' => $defaultNs,
736 'namespace-messages' => $this->searchConfig->namespacesAsText(
741 'message' =>
'searchprofile-images',
742 'tooltip' =>
'searchprofile-images-tooltip',
746 'message' =>
'searchprofile-everything',
747 'tooltip' =>
'searchprofile-everything-tooltip',
748 'namespaces' => $nsAllSet,
751 'message' =>
'searchprofile-advanced',
752 'tooltip' =>
'searchprofile-advanced-tooltip',
753 'namespaces' => self::NAMESPACES_CURRENT,
757 $this->
getHookRunner()->onSpecialSearchProfiles( $profiles );
759 foreach ( $profiles as &$data ) {
760 if ( !is_array( $data[
'namespaces'] ) ) {
763 sort( $data[
'namespaces'] );
773 $this->searchEngine ??= $this->searchEngineFactory->create( $this->searchEngineType );
774 return $this->searchEngine;
782 return $this->profile;
790 return $this->namespaces;
803 $this->extraParams[$key] = $value;
815 return $this->mPrefix;
825 private function prevNextLinks(
832 if ( $totalRes > $this->limit || $this->offset ) {
835 if ( $textMatches && $textMatches->
getOffset() !==
null ) {
838 $offset = $this->offset;
842 $newSearchTerm = $term;
849 $this->buildPrevNextNavigation( $offset, $this->limit,
850 $this->powerSearchOptions() + [
'search' => $newSearchTerm ],
851 $this->limit + $this->offset >= $totalRes );
852 $out->
addHTML(
"<div class='{$class}'>{$prevNext}</div>\n" );
878 ->setLinkQuery( [
'limit' =>
$limit,
'offset' =>
$offset ] + $query )
879 ->setLimitLinkQueryParam(
'limit' )
880 ->setCurrentLimit(
$limit )
881 ->setPrevTooltipMsg(
'prevn-title' )
882 ->setNextTooltipMsg(
'nextn-title' )
883 ->setLimitTooltipMsg(
'shown-title' )
884 ->setHideLast(
true );
887 $navBuilder->setFirstLinkQuery( [
'offset' => 0 ] );
888 $navBuilder->setPrevLinkQuery( [
'offset' => (
string)max(
$offset -
$limit, 0 ) ] );
891 $navBuilder->setNextLinkQuery( [
'offset' => (
string)(
$offset +
$limit ) ] );
894 return $navBuilder->getHtml();
908class_alias( SpecialSearch::class,
'SpecialSearch' );
wfEscapeWikiText( $input)
Escapes the given text so that it may be output using addWikiText() without any linking,...
if(!defined('MW_SETUP_CALLBACK'))
A class containing constants representing the names of configuration variables.
const SearchForwardUrl
Name constant for the SearchForwardUrl setting, for use with Config\get().
const DisableTextSearch
Name constant for the DisableTextSearch setting, for use with Config\get().
const SpecialSearchFormOptions
Name constant for the SpecialSearchFormOptions setting, for use with Config\get().
This is one of the Core classes and should be read at least once by any new developers.
setSubtitle( $str)
Replace the subtitle with $str.
addJsConfigVars( $keys, $value=null)
Add one or more variables to be set in mw.config in JavaScript.
wrapWikiMsg( $wrap,... $msgSpecs)
This function takes a number of message/argument specifications, wraps them in some overall structure...
setPageTitleMsg(Message $msg)
"Page title" means the contents of <h1>.
addModules( $modules)
Load one or more ResourceLoader modules on this page.
redirect( $url, $responsecode='302')
Redirect to $url rather than displaying the normal page.
setHTMLTitle( $name)
"HTML title" means the contents of "<title>".
enableOOUI()
Add ResourceLoader module styles for OOUI and set up the PHP implementation of it for use with MediaW...
addHTML( $text)
Append $text to the body HTML.
addModuleStyles( $modules)
Load the styles of one or more style-only ResourceLoader modules on this page.
getMetadata()
Return a ParserOutput that can be used to set metadata properties for the current page.
Parent class for all special pages.
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes!
getUser()
Shortcut to get the User executing this instance.
getPageTitle( $subpage=false)
Get a self-referential title object.
getConfig()
Shortcut to get main config object.
getContext()
Gets the context this SpecialPage is executed in.
getRequest()
Get the WebRequest being used for this instance.
msg( $key,... $params)
Wrapper around wfMessage that sets the current context.
getOutput()
Get the OutputPage being used for this instance.
getContentLanguage()
Shortcut to get content language.
outputHeader( $summaryMessageKey='')
Outputs a summary message on top of special pages By default the message key is the canonical name of...
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.