26 namespace MediaWiki\Specials;
136 private const NAMESPACES_CURRENT =
'sense';
164 parent::__construct(
'Search' );
166 $this->searchEngineFactory = $searchEngineFactory;
167 $this->nsInfo = $nsInfo;
168 $this->contentHandlerFactory = $contentHandlerFactory;
169 $this->interwikiLookup = $interwikiLookup;
170 $this->readOnlyMode = $readOnlyMode;
171 $this->userOptionsManager = $userOptionsManager;
172 $this->languageConverterFactory = $languageConverterFactory;
173 $this->repoGroup = $repoGroup;
174 $this->thumbnailProvider = $thumbnailProvider;
175 $this->titleMatcher = $titleMatcher;
188 $term = str_replace(
"\n",
" ", $request->getText(
'search' ) );
194 if ( $par !==
null && $par !==
'' && $term ===
'' ) {
195 $query = $request->getValues();
196 unset( $query[
'title'] );
199 $query[
'search'] = str_replace(
'_',
' ', $par );
208 if ( $request->getCheck(
'nsRemember' ) ) {
213 $query = $request->getValues();
214 unset( $query[
'title'], $query[
'nsRemember'] );
219 if ( !$request->getVal(
'fulltext' ) && !$request->getCheck(
'offset' ) ) {
221 if ( $url !==
null ) {
229 if ( $title !==
null ) {
238 if ( $searchForwardUrl ) {
239 $url = str_replace(
'$1', urlencode( $term ), $searchForwardUrl );
242 $out->
addHTML( $this->showGoogleSearch( $term ) );
259 private function showGoogleSearch( $term ) {
260 return "<fieldset>" .
262 $this->
msg(
'search-external' )->escaped() .
264 "<p class='mw-searchdisabled'>" .
265 $this->
msg(
'searchdisabled' )->escaped() .
268 $this->
msg(
'googlesearch' )->rawParams(
269 htmlspecialchars( $term ),
271 $this->
msg(
'searchbutton' )->escaped()
282 $this->loadStatus =
new Status();
285 $this->searchEngineType = $request->getVal(
'srbackend' );
292 $this->mPrefix = $request->getVal(
'prefix',
'' );
293 if ( $this->mPrefix !==
'' ) {
299 if ( !in_array(
$sort, $validSorts ) ) {
300 $this->loadStatus->warning(
'search-invalid-sort-order',
$sort,
301 implode(
', ', $validSorts ) );
302 } elseif (
$sort !== $this->sort ) {
309 # Extract manually requested namespaces
311 if ( $nslist === [] ) {
312 # Fallback to user preference
313 $nslist = $this->searchConfig->userNamespaces( $user );
317 if ( $nslist === [] ) {
323 if ( $profile ===
null ) {
326 foreach ( $profiles as $key => $data ) {
327 if ( $nslist === $data[
'namespaces'] && $key !==
'advanced' ) {
331 $this->namespaces = $nslist;
332 } elseif (
$profile ===
'advanced' ) {
333 $this->namespaces = $nslist;
334 } elseif ( isset( $profiles[
$profile][
'namespaces'] ) ) {
335 $this->namespaces = $profiles[
$profile][
'namespaces'];
338 $this->loadStatus->warning(
'search-unknown-profile',
$profile );
340 $this->namespaces = $profiles[
'default'][
'namespaces'];
343 $this->fulltext = $request->getVal(
'fulltext' );
344 $this->runSuggestion = (bool)$request->getVal(
'runsuggestion',
'1' );
355 # If the string cannot be used to create a title
359 # If there's an exact or very near match, jump right there.
360 $title = $this->titleMatcher->getNearMatch( $term );
361 if ( $title ===
null ) {
365 if ( !$this->
getHookRunner()->onSpecialSearchGoResult( $term, $title, $url ) ) {
372 !$this->redirectOnExactMatch()
375 && !$title->isExternal()
378 && !( $title->getNamespace() !==
NS_MAIN && strpos( $term,
':' ) > 0 )
383 return $url ?? $title->getFullUrlForRedirect();
386 private function redirectOnExactMatch() {
389 $defaultOptions = $this->userOptionsManager->getDefaultOptions();
390 return $defaultOptions[
'search-match-redirect'];
393 return $this->userOptionsManager->getOption( $this->
getUser(),
'search-match-redirect' );
401 if ( $this->searchEngineType !==
null ) {
402 $this->
setExtraParam(
'srbackend', $this->searchEngineType );
411 $this->languageConverterFactory->getLanguageConverter( $this->getLanguage() ),
413 $this->getSearchProfiles()
416 if ( trim( $term ) ===
'' || $filePrefix === trim( $term ) ) {
418 if ( !$this->
getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
419 # Hook requested termination
426 $out->
addHTML( $formWidget->render(
427 $this->profile, $term, 0, 0, $this->offset, $this->isPowerSearch(), $widgetOptions
433 $engine->setFeatureData(
'rewrite', $this->runSuggestion );
434 $engine->setLimitOffset( $this->limit, $this->offset );
435 $engine->setNamespaces( $this->namespaces );
436 $engine->setSort( $this->sort );
439 $this->
getHookRunner()->onSpecialSearchSetupEngine( $this, $this->profile, $engine );
440 if ( !$this->
getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
441 # Hook requested termination
446 $languageConverter = $this->languageConverterFactory->getLanguageConverter( $this->
getContentLanguage() );
447 if ( $languageConverter->hasVariants() ) {
450 $variantTerm = $term;
451 $languageConverter->findVariantLink( $variantTerm, $title );
454 $showSuggestion = $title ===
null || !$title->isKnown();
455 $engine->setShowSuggestion( $showSuggestion );
457 $rewritten = $engine->replacePrefixes( $term );
458 if ( $rewritten !== $term ) {
459 wfDeprecatedMsg(
'SearchEngine::replacePrefixes() was overridden by ' .
460 get_class( $engine ) .
', this is deprecated since MediaWiki 1.32',
461 '1.32',
false,
false );
465 $titleMatches = $engine->searchTitle( $rewritten );
466 $textMatches = $engine->searchText( $rewritten );
469 if ( $textMatches instanceof
Status ) {
470 $textStatus = $textMatches;
471 $textMatches = $textStatus->getValue();
475 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
476 if ( $titleMatches ) {
477 $titleMatchesNum = $titleMatches->
numRows();
478 $numTitleMatches = $titleMatches->getTotalHits();
480 if ( $textMatches ) {
481 $textMatchesNum = $textMatches->
numRows();
483 if ( $textMatchesNum > 0 ) {
484 $engine->augmentSearchResults( $textMatches );
487 $num = $titleMatchesNum + $textMatchesNum;
488 $totalRes = $numTitleMatches + $numTextMatches;
492 $out->
addHTML( $formWidget->render(
493 $this->profile, $term, $num, $totalRes, $this->offset, $this->isPowerSearch(), $widgetOptions
497 if ( $textMatches ) {
499 $out->
addHTML( $dymWidget->render( $term, $textMatches ) );
502 $hasSearchErrors = $textStatus && $textStatus->getErrors() !== [];
503 $hasInlineIwResults = $textMatches &&
505 $hasSecondaryIwResults = $textMatches &&
508 $classNames = [
'searchresults' ];
509 if ( $hasSecondaryIwResults ) {
510 $classNames[] =
'mw-searchresults-has-iw';
512 if ( $this->offset > 0 ) {
513 $classNames[] =
'mw-searchresults-has-offset';
515 $out->
addHTML(
'<div class="' . implode(
' ', $classNames ) .
'">' );
517 $out->
addHTML(
'<div class="mw-search-results-info">' );
519 if ( $hasSearchErrors || $this->loadStatus->getErrors() ) {
520 if ( $textStatus ===
null ) {
521 $textStatus = $this->loadStatus;
523 $textStatus->merge( $this->loadStatus );
525 [ $error, $warning ] = $textStatus->splitByErrorType();
526 if ( $error->getErrors() ) {
528 $error->getHTML(
'search-error' )
531 if ( $warning->getErrors() ) {
533 $warning->getHTML(
'search-warning' )
539 if ( $num === 0 && !$hasSearchErrors ) {
540 $out->
wrapWikiMsg(
"<p class=\"mw-search-nonefound\">\n$1</p>", [
541 $hasInlineIwResults ?
'search-nonefound-thiswiki' :
'search-nonefound',
548 $this->
showCreateLink( $title, $num, $titleMatches, $textMatches );
550 $this->
getHookRunner()->onSpecialSearchResults( $term, $titleMatches, $textMatches );
563 $this->thumbnailProvider,
564 $this->userOptionsManager
570 $sidebarResultWidget,
572 $this->interwikiLookup,
573 $engine->getFeatureData(
'show-multimedia-search-results' )
578 $out->
addHTML(
'<div class="mw-search-visualclear"></div>' );
579 $this->prevNextLinks( $totalRes, $textMatches, $term,
'mw-search-pager-top', $out );
581 $out->
addHTML( $widget->render(
582 $term, $this->offset, $titleMatches, $textMatches
585 $out->
addHTML(
'<div class="mw-search-visualclear"></div>' );
586 $this->prevNextLinks( $totalRes, $textMatches, $term,
'mw-search-pager-bottom', $out );
591 $this->
getHookRunner()->onSpecialSearchResultsAppend( $this, $out, $term );
604 if ( $title ===
null || $title->getDBkey() ===
''
605 || ( $titleMatches !==
null && $titleMatches->searchContainedSyntax() )
610 $this->
getOutput()->addHTML(
'<p></p>' );
615 $messageName =
'searchmenu-new-nocreate';
616 $linkClass =
'mw-search-createlink';
618 if ( !$title->isExternal() ) {
619 if ( $title->isKnown() ) {
620 $messageName =
'searchmenu-exists';
621 $linkClass =
'mw-search-exists';
623 $this->contentHandlerFactory->getContentHandler( $title->getContentModel() )
624 ->supportsDirectEditing()
625 && $this->getAuthority()->probablyCan(
'edit', $title )
627 $messageName =
'searchmenu-new';
636 $this->
getHookRunner()->onSpecialSearchCreateLink( $title, $params );
640 if ( $messageName ) {
641 $this->
getOutput()->wrapWikiMsg(
"<p class=\"$linkClass\">\n$1</p>", $params );
644 $this->
getOutput()->addHTML(
'<p></p>' );
664 if ( strval( $term ) !==
'' ) {
667 ->plaintextParams( $this->
msg(
'searchresults-title' )->plaintextParams( $term )->text() )
668 ->inContentLanguage()->text()
672 if ( $this->mPrefix !==
'' ) {
673 $subtitle = $this->
msg(
'search-filter-title-prefix' )->plaintextParams( $this->mPrefix );
675 unset( $params[
'prefix'] );
685 'href' => $this->
getPageTitle()->getLocalURL( $params ),
686 'title' => $this->
msg(
'search-filter-title-prefix-reset' )->text(),
688 $this->
msg(
'search-filter-title-prefix-reset' )->text()
695 $out->
addModules(
'mediawiki.special.search' );
697 'mediawiki.special',
'mediawiki.special.search.styles',
698 'mediawiki.widgets.SearchInputWidget.styles',
708 return $this->profile ===
'advanced';
720 foreach ( $this->searchConfig->searchableNamespaces() as $ns => $name ) {
721 if ( $request->getCheck(
'ns' . $ns ) ) {
739 foreach ( $this->namespaces as $n ) {
758 if ( $user->isRegistered() &&
759 $user->matchEditToken(
760 $request->getVal(
'nsRemember' ),
763 ) && !$this->readOnlyMode->isReadOnly()
767 foreach ( $this->nsInfo->getValidNamespaces() as $n ) {
768 $this->userOptionsManager->setOption( $user,
'searchNs' . $n,
false );
772 foreach ( $this->namespaces as $n ) {
773 $this->userOptionsManager->setOption( $user,
'searchNs' . $n,
true );
777 $user->saveSettings();
792 $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
793 $defaultNs = $this->searchConfig->defaultNamespaces();
796 'message' =>
'searchprofile-articles',
797 'tooltip' =>
'searchprofile-articles-tooltip',
798 'namespaces' => $defaultNs,
799 'namespace-messages' => $this->searchConfig->namespacesAsText(
804 'message' =>
'searchprofile-images',
805 'tooltip' =>
'searchprofile-images-tooltip',
809 'message' =>
'searchprofile-everything',
810 'tooltip' =>
'searchprofile-everything-tooltip',
811 'namespaces' => $nsAllSet,
814 'message' =>
'searchprofile-advanced',
815 'tooltip' =>
'searchprofile-advanced-tooltip',
816 'namespaces' => self::NAMESPACES_CURRENT,
820 $this->
getHookRunner()->onSpecialSearchProfiles( $profiles );
822 foreach ( $profiles as &$data ) {
823 if ( !is_array( $data[
'namespaces'] ) ) {
826 sort( $data[
'namespaces'] );
838 if ( $this->searchEngine ===
null ) {
839 $this->searchEngine = $this->searchEngineFactory->create( $this->searchEngineType );
871 $this->extraParams[$key] = $value;
893 private function prevNextLinks(
900 if ( $totalRes > $this->limit || $this->offset ) {
903 if ( $textMatches && $textMatches->
getOffset() !==
null ) {
910 $newSearchTerm = $term;
919 $this->limit + $this->offset >= $totalRes );
920 $out->
addHTML(
"<div class='{$class}'>{$prevNext}</div>\n" );
933 class_alias( SpecialSearch::class,
'SpecialSearch' );
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Defer callable updates to run later in the PHP process.
static addCallableUpdate( $callable, $stage=self::POSTSEND, $dbw=null)
Add an update to the pending update queue that invokes the specified callback when run.
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 SearchMatchRedirectPreference
Name constant for the SearchMatchRedirectPreference 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...
setPreventClickjacking(bool $enable)
Set the prevent-clickjacking flag.
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.
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.
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.
buildPrevNextNavigation( $offset, $limit, array $query=[], $atend=false, $subpage=false)
Generate (prev x| next x) (20|50|100...) type links for paging.
outputHeader( $summaryMessageKey='')
Outputs a summary message on top of special pages Per default the message key is the canonical name o...
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
The Message class deals with fetching and processing of interface message into a variety of formats.
Prioritized list of file repositories.
Configuration handling class for SearchEngine.
Factory class for SearchEngine.
Contain a class for special pages.
Module of static functions for generating XML.
static element( $element, $attribs=null, $contents='', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
A set of SearchEngine results.
searchContainedSyntax()
Did the search contain search syntax? If so, Special:Search won't offer the user a link to a create a...
hasInterwikiResults( $type=self::SECONDARY_RESULTS)
Check if there are results on other wikis.
const INLINE_RESULTS
Identifier for interwiki results that can be displayed even if no existing main wiki results exist.
const SECONDARY_RESULTS
Identifier for interwiki results that are displayed only together with existing main wiki results.
hasRewrittenQuery()
Some search modes will run an alternative query that it thinks gives a better result than the provide...
getTotalHits()
Some search modes return a total hit count for the query in the entire article database.