106 protected $sort = SearchEngine::DEFAULT_SORT;
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 ) {
228 $title = Title::newFromText( $term );
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 !==
'' ) {
297 $sort = $request->getVal(
'sort', SearchEngine::DEFAULT_SORT );
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
356 if ( Title::newFromText( $term ) ===
null ) {
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 return $this->userOptionsManager->getDefaultOption(
390 'search-match-redirect',
395 return $this->userOptionsManager->getOption( $this->
getUser(),
'search-match-redirect' );
403 if ( $this->searchEngineType !==
null ) {
404 $this->
setExtraParam(
'srbackend', $this->searchEngineType );
413 $this->languageConverterFactory->getLanguageConverter( $this->getLanguage() ),
415 $this->getSearchProfiles()
418 if ( trim( $term ) ===
'' || $filePrefix === trim( $term ) ) {
420 if ( !$this->
getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
421 # Hook requested termination
428 $out->
addHTML( $formWidget->render(
429 $this->profile, $term, 0, 0, $this->offset, $this->isPowerSearch(), $widgetOptions
435 $engine->setFeatureData(
'rewrite', $this->runSuggestion );
436 $engine->setLimitOffset( $this->limit, $this->offset );
437 $engine->setNamespaces( $this->namespaces );
438 $engine->setSort( $this->sort );
441 $this->
getHookRunner()->onSpecialSearchSetupEngine( $this, $this->profile, $engine );
442 if ( !$this->
getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
443 # Hook requested termination
447 $title = Title::newFromText( $term );
448 $languageConverter = $this->languageConverterFactory->getLanguageConverter( $this->
getContentLanguage() );
449 if ( $languageConverter->hasVariants() ) {
452 $variantTerm = $term;
453 $languageConverter->findVariantLink( $variantTerm, $title );
456 $showSuggestion = $title ===
null || !$title->isKnown();
457 $engine->setShowSuggestion( $showSuggestion );
459 $rewritten = $engine->replacePrefixes( $term );
460 if ( $rewritten !== $term ) {
461 wfDeprecatedMsg(
'SearchEngine::replacePrefixes() was overridden by ' .
462 get_class( $engine ) .
', this is deprecated since MediaWiki 1.32',
463 '1.32',
false,
false );
467 $titleMatches = $engine->searchTitle( $rewritten );
468 $textMatches = $engine->searchText( $rewritten );
471 if ( $textMatches instanceof
Status ) {
472 $textStatus = $textMatches;
473 $textMatches = $textStatus->getValue();
477 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
478 if ( $titleMatches ) {
479 $titleMatchesNum = $titleMatches->
numRows();
480 $numTitleMatches = $titleMatches->getTotalHits();
482 if ( $textMatches ) {
483 $textMatchesNum = $textMatches->
numRows();
485 if ( $textMatchesNum > 0 ) {
486 $engine->augmentSearchResults( $textMatches );
489 $num = $titleMatchesNum + $textMatchesNum;
490 $totalRes = $numTitleMatches + $numTextMatches;
494 $out->
addHTML( $formWidget->render(
495 $this->profile, $term, $num, $totalRes, $this->offset, $this->isPowerSearch(), $widgetOptions
499 if ( $textMatches ) {
501 $out->
addHTML( $dymWidget->render( $term, $textMatches ) );
504 $hasSearchErrors = $textStatus && $textStatus->getErrors() !== [];
505 $hasInlineIwResults = $textMatches &&
507 $hasSecondaryIwResults = $textMatches &&
510 $classNames = [
'searchresults' ];
511 if ( $hasSecondaryIwResults ) {
512 $classNames[] =
'mw-searchresults-has-iw';
514 if ( $this->offset > 0 ) {
515 $classNames[] =
'mw-searchresults-has-offset';
517 $out->
addHTML(
'<div class="' . implode(
' ', $classNames ) .
'">' );
519 $out->
addHTML(
'<div class="mw-search-results-info">' );
521 if ( $hasSearchErrors || $this->loadStatus->getErrors() ) {
522 if ( $textStatus ===
null ) {
523 $textStatus = $this->loadStatus;
525 $textStatus->merge( $this->loadStatus );
527 [ $error, $warning ] = $textStatus->splitByErrorType();
528 if ( $error->getErrors() ) {
530 $error->getHTML(
'search-error' )
533 if ( $warning->getErrors() ) {
534 $out->
addHTML( Html::warningBox(
535 $warning->getHTML(
'search-warning' )
541 if ( $num === 0 && !$hasSearchErrors ) {
542 $out->
wrapWikiMsg(
"<p class=\"mw-search-nonefound\">\n$1</p>", [
543 $hasInlineIwResults ?
'search-nonefound-thiswiki' :
'search-nonefound',
550 $this->
showCreateLink( $title, $num, $titleMatches, $textMatches );
552 $this->
getHookRunner()->onSpecialSearchResults( $term, $titleMatches, $textMatches );
565 $this->thumbnailProvider,
566 $this->userOptionsManager
572 $sidebarResultWidget,
574 $this->interwikiLookup,
575 $engine->getFeatureData(
'show-multimedia-search-results' )
580 $out->
addHTML(
'<div class="mw-search-visualclear"></div>' );
581 $this->prevNextLinks( $totalRes, $textMatches, $term,
'mw-search-pager-top', $out );
583 $out->
addHTML( $widget->render(
584 $term, $this->offset, $titleMatches, $textMatches
587 $out->
addHTML(
'<div class="mw-search-visualclear"></div>' );
588 $this->prevNextLinks( $totalRes, $textMatches, $term,
'mw-search-pager-bottom', $out );
593 $this->
getHookRunner()->onSpecialSearchResultsAppend( $this, $out, $term );
606 if ( $title ===
null || $title->getDBkey() ===
''
607 || ( $titleMatches !==
null && $titleMatches->searchContainedSyntax() )
612 $this->
getOutput()->addHTML(
'<p></p>' );
617 $messageName =
'searchmenu-new-nocreate';
618 $linkClass =
'mw-search-createlink';
620 if ( !$title->isExternal() ) {
621 if ( $title->isKnown() ) {
622 $messageName =
'searchmenu-exists';
623 $linkClass =
'mw-search-exists';
625 $this->contentHandlerFactory->getContentHandler( $title->getContentModel() )
626 ->supportsDirectEditing()
627 && $this->getAuthority()->probablyCan(
'edit', $title )
629 $messageName =
'searchmenu-new';
642 if ( $messageName ) {
643 $this->
getOutput()->wrapWikiMsg(
"<p class=\"$linkClass\">\n$1</p>",
$params );
646 $this->
getOutput()->addHTML(
'<p></p>' );
666 if ( strval( $term ) !==
'' ) {
669 ->plaintextParams( $this->
msg(
'searchresults-title' )->plaintextParams( $term )->text() )
670 ->inContentLanguage()->text()
674 if ( $this->mPrefix !==
'' ) {
675 $subtitle = $this->
msg(
'search-filter-title-prefix' )->plaintextParams( $this->mPrefix );
684 $subtitle .= Xml::element(
688 'title' => $this->
msg(
'search-filter-title-prefix-reset' )->text(),
690 $this->
msg(
'search-filter-title-prefix-reset' )->text()
697 $out->
addModules(
'mediawiki.special.search' );
699 'mediawiki.special',
'mediawiki.special.search.styles',
700 'mediawiki.widgets.SearchInputWidget.styles',
710 return $this->profile ===
'advanced';
722 foreach ( $this->searchConfig->searchableNamespaces() as $ns => $name ) {
723 if ( $request->getCheck(
'ns' . $ns ) ) {
741 foreach ( $this->namespaces as $n ) {
760 if ( $user->isRegistered() &&
761 $user->matchEditToken(
762 $request->getVal(
'nsRemember' ),
765 ) && !$this->readOnlyMode->isReadOnly()
769 foreach ( $this->nsInfo->getValidNamespaces() as $n ) {
770 $this->userOptionsManager->setOption( $user,
'searchNs' . $n,
false );
774 foreach ( $this->namespaces as $n ) {
775 $this->userOptionsManager->setOption( $user,
'searchNs' . $n,
true );
778 DeferredUpdates::addCallableUpdate(
static function () use ( $user ) {
779 $user->saveSettings();
794 $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
795 $defaultNs = $this->searchConfig->defaultNamespaces();
798 'message' =>
'searchprofile-articles',
799 'tooltip' =>
'searchprofile-articles-tooltip',
800 'namespaces' => $defaultNs,
801 'namespace-messages' => $this->searchConfig->namespacesAsText(
806 'message' =>
'searchprofile-images',
807 'tooltip' =>
'searchprofile-images-tooltip',
811 'message' =>
'searchprofile-everything',
812 'tooltip' =>
'searchprofile-everything-tooltip',
813 'namespaces' => $nsAllSet,
816 'message' =>
'searchprofile-advanced',
817 'tooltip' =>
'searchprofile-advanced-tooltip',
818 'namespaces' => self::NAMESPACES_CURRENT,
822 $this->
getHookRunner()->onSpecialSearchProfiles( $profiles );
824 foreach ( $profiles as &$data ) {
825 if ( !is_array( $data[
'namespaces'] ) ) {
828 sort( $data[
'namespaces'] );
840 if ( $this->searchEngine ===
null ) {
841 $this->searchEngine = $this->searchEngineFactory->create( $this->searchEngineType );
873 $this->extraParams[$key] = $value;
895 private function prevNextLinks(
902 if ( $totalRes > $this->limit || $this->offset ) {
905 if ( $textMatches && $textMatches->
getOffset() !==
null ) {
912 $newSearchTerm = $term;
921 $this->limit + $this->offset >= $totalRes );
922 $out->
addHTML(
"<div class='{$class}'>{$prevNext}</div>\n" );
935class_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...
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.
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.
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...
getTotalHits()
Some search modes return a total hit count for the query in the entire article database.