104 protected $sort = SearchEngine::DEFAULT_SORT;
134 private const NAMESPACES_CURRENT =
'sense';
162 parent::__construct(
'Search' );
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;
186 $term = str_replace(
"\n",
" ", $request->getText(
'search' ) );
192 if ( $par !==
null && $par !==
'' && $term ===
'' ) {
193 $query = $request->getQueryValues();
194 unset( $query[
'title'] );
197 $query[
'search'] = str_replace(
'_',
' ', $par );
206 if ( $request->getCheck(
'nsRemember' ) ) {
211 $query = $request->getQueryValues();
212 unset( $query[
'title'], $query[
'nsRemember'] );
217 if ( !$request->getVal(
'fulltext' ) && !$request->getCheck(
'offset' ) ) {
219 if (
$url !==
null ) {
226 $title = Title::newFromText( $term );
227 if ( $title !==
null ) {
236 if ( $searchForwardUrl ) {
237 $url = str_replace(
'$1', urlencode( $term ), $searchForwardUrl );
240 $out->
addHTML( $this->showGoogleSearch( $term ) );
257 private function showGoogleSearch( $term ) {
258 return "<fieldset>" .
260 $this->
msg(
'search-external' )->escaped() .
262 "<p class='mw-searchdisabled'>" .
263 $this->
msg(
'searchdisabled' )->escaped() .
266 $this->
msg(
'googlesearch' )->rawParams(
267 htmlspecialchars( $term ),
269 $this->
msg(
'searchbutton' )->escaped()
280 $this->loadStatus =
new Status();
283 $this->searchEngineType = $request->getVal(
'srbackend' );
290 $this->mPrefix = $request->getVal(
'prefix',
'' );
291 if ( $this->mPrefix !==
'' ) {
295 $sort = $request->getVal(
'sort', SearchEngine::DEFAULT_SORT );
297 if ( !in_array(
$sort, $validSorts ) ) {
298 $this->loadStatus->warning(
'search-invalid-sort-order',
$sort,
299 implode(
', ', $validSorts ) );
300 } elseif (
$sort !== $this->sort ) {
307 # Extract manually requested namespaces
309 if ( $nslist === [] ) {
310 # Fallback to user preference
311 $nslist = $this->searchConfig->userNamespaces( $user );
315 if ( $nslist === [] ) {
321 if ( $profile ===
null ) {
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'];
336 $this->loadStatus->warning(
'search-unknown-profile',
$profile );
338 $this->namespaces = $profiles[
'default'][
'namespaces'];
341 $this->fulltext = $request->getVal(
'fulltext' );
342 $this->runSuggestion = (bool)$request->getVal(
'runsuggestion',
'1' );
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 ) {
370 !$this->redirectOnExactMatch()
373 && !$title->isExternal()
376 && !( $title->getNamespace() !==
NS_MAIN && strpos( $term,
':' ) > 0 )
381 return $url ?? $title->getFullUrlForRedirect();
384 private function redirectOnExactMatch() {
387 return $this->userOptionsManager->getDefaultOption(
388 'search-match-redirect',
393 return $this->userOptionsManager->getOption( $this->
getUser(),
'search-match-redirect' );
401 if ( $this->searchEngineType !==
null ) {
402 $this->
setExtraParam(
'srbackend', $this->searchEngineType );
415 $this->languageConverterFactory->getLanguageConverter( $this->getLanguage() ),
417 $this->getSearchProfiles()
420 if ( trim( $term ) ===
'' || $filePrefix === trim( $term ) ) {
422 if ( !$this->
getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
423 # Hook requested termination
430 $out->
addHTML( $formWidget->render(
431 $this->profile, $term, 0, 0,
false, $this->offset, $this->isPowerSearch(), $widgetOptions
437 $engine->setFeatureData(
'rewrite', $this->runSuggestion );
438 $engine->setLimitOffset( $this->limit, $this->offset );
439 $engine->setNamespaces( $this->namespaces );
440 $engine->setSort( $this->sort );
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() ) {
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 );
469 $titleMatches = $engine->searchTitle( $rewritten );
470 $textMatches = $engine->searchText( $rewritten );
473 if ( $textMatches instanceof
Status ) {
474 $textStatus = $textMatches;
475 $textMatches = $textStatus->getValue();
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();
490 if ( $textMatchesNum > 0 ) {
491 $engine->augmentSearchResults( $textMatches );
494 $num = $titleMatchesNum + $textMatchesNum;
495 $totalRes = $numTitleMatches + $numTextMatches;
499 $out->
addHTML( $formWidget->render(
500 $this->profile, $term, $num, $totalRes, $approxTotalRes, $this->offset, $this->isPowerSearch(),
505 if ( $textMatches ) {
507 $out->
addHTML( $dymWidget->render( $term, $textMatches ) );
510 $hasSearchErrors = $textStatus && $textStatus->getMessages() !== [];
511 $hasInlineIwResults = $textMatches &&
513 $hasSecondaryIwResults = $textMatches &&
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() ) {
536 $error->getHTML(
'search-error' )
539 if ( $warning->getMessages() ) {
540 $out->
addHTML( Html::warningBox(
541 $warning->getHTML(
'search-warning' )
547 if ( $num === 0 && !$hasSearchErrors ) {
548 $out->
wrapWikiMsg(
"<p class=\"mw-search-nonefound\">\n$1</p>", [
549 $hasInlineIwResults ?
'search-nonefound-thiswiki' :
'search-nonefound',
556 $this->
showCreateLink( $title, $num, $titleMatches, $textMatches );
558 $this->
getHookRunner()->onSpecialSearchResults( $term, $titleMatches, $textMatches );
571 $this->thumbnailProvider,
572 $this->userOptionsManager
578 $sidebarResultWidget,
580 $this->interwikiLookup,
581 $engine->getFeatureData(
'show-multimedia-search-results' )
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 );
599 $this->
getHookRunner()->onSpecialSearchResultsAppend( $this, $out, $term );
612 if ( $title ===
null || $title->getDBkey() ===
''
613 || ( $titleMatches !==
null && $titleMatches->searchContainedSyntax() )
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';
648 if ( $messageName ) {
649 $this->
getOutput()->wrapWikiMsg(
"<p class=\"$linkClass\">\n$1</p>",
$params );
652 $this->
getOutput()->addHTML(
'<p></p>' );
669 $out->
getMetadata()->setPreventClickjacking(
false );
672 if ( strval( $term ) !==
'' ) {
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 );
694 'title' => $this->
msg(
'search-filter-title-prefix-reset' )->text(),
696 $this->
msg(
'search-filter-title-prefix-reset' )->text()
703 $out->
addModules(
'mediawiki.special.search' );
705 'mediawiki.special',
'mediawiki.special.search.styles',
706 'mediawiki.widgets.SearchInputWidget.styles',
716 return $this->profile ===
'advanced';
728 foreach ( $this->searchConfig->searchableNamespaces() as $ns => $name ) {
729 if ( $request->getCheck(
'ns' . $ns ) ) {
747 foreach ( $this->namespaces as $n ) {
766 if ( $user->isRegistered() &&
767 $user->matchEditToken(
768 $request->getVal(
'nsRemember' ),
771 ) && !$this->readOnlyMode->isReadOnly()
775 foreach ( $this->nsInfo->getValidNamespaces() as $n ) {
776 $this->userOptionsManager->setOption( $user,
'searchNs' . $n,
false );
780 foreach ( $this->namespaces as $n ) {
781 $this->userOptionsManager->setOption( $user,
'searchNs' . $n,
true );
784 DeferredUpdates::addCallableUpdate(
static function () use ( $user ) {
785 $user->saveSettings();
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',
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'] );
846 if ( $this->searchEngine ===
null ) {
847 $this->searchEngine = $this->searchEngineFactory->create( $this->searchEngineType );
879 $this->extraParams[$key] = $value;
901 private function prevNextLinks(
908 if ( $totalRes > $this->limit || $this->offset ) {
911 if ( $textMatches && $textMatches->
getOffset() !==
null ) {
918 $newSearchTerm = $term;
927 $this->limit + $this->offset >= $totalRes );
928 $out->
addHTML(
"<div class='{$class}'>{$prevNext}</div>\n" );
941class_alias( SpecialSearch::class,
'SpecialSearch' );
wfEscapeWikiText( $input)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
array $params
The job parameters.
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...
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.
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 By default the message key is the canonical name of...
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
Prioritized list of file repositories.
Configuration handling class for SearchEngine.
Factory class for SearchEngine.
Contain a class for special pages.
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.
hasRewrittenQuery()
Some search modes will run an alternative query that it thinks gives a better result than the provide...
isApproximateTotalHits()
If getTotalHits() is supported determine whether this number is approximate or not.
getTotalHits()
Some search modes return a total hit count for the query in the entire article database.