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( Html::errorBox( Html::rawElement(
242 [
'class' =>
'mw-searchdisabled' ],
243 $this->
msg(
'searchdisabled', [
'mw:Special:MyLanguage/Manual:$wgSearchForwardUrl' ] )->parse()
259 $this->loadStatus =
new Status();
262 $this->searchEngineType = $request->getVal(
'srbackend' );
269 $this->mPrefix = $request->getVal(
'prefix',
'' );
270 if ( $this->mPrefix !==
'' ) {
274 $sort = $request->getVal(
'sort', SearchEngine::DEFAULT_SORT );
276 if ( !in_array(
$sort, $validSorts ) ) {
277 $this->loadStatus->warning(
'search-invalid-sort-order',
$sort,
278 implode(
', ', $validSorts ) );
279 } elseif (
$sort !== $this->sort ) {
286 # Extract manually requested namespaces
288 if ( $nslist === [] ) {
289 # Fallback to user preference
290 $nslist = $this->searchConfig->userNamespaces( $user );
294 if ( $nslist === [] ) {
300 if ( $profile ===
null ) {
303 foreach ( $profiles as $key => $data ) {
304 if ( $nslist === $data[
'namespaces'] && $key !==
'advanced' ) {
308 $this->namespaces = $nslist;
309 } elseif (
$profile ===
'advanced' ) {
310 $this->namespaces = $nslist;
311 } elseif ( isset( $profiles[
$profile][
'namespaces'] ) ) {
312 $this->namespaces = $profiles[
$profile][
'namespaces'];
315 $this->loadStatus->warning(
'search-unknown-profile',
$profile );
317 $this->namespaces = $profiles[
'default'][
'namespaces'];
320 $this->fulltext = $request->getVal(
'fulltext' );
321 $this->runSuggestion = (bool)$request->getVal(
'runsuggestion',
'1' );
332 # If the string cannot be used to create a title
333 if ( Title::newFromText( $term ) ===
null ) {
336 # If there's an exact or very near match, jump right there.
337 $title = $this->titleMatcher->getNearMatch( $term );
338 if ( $title ===
null ) {
349 !$this->redirectOnExactMatch()
352 && !$title->isExternal()
355 && !( $title->getNamespace() !==
NS_MAIN && strpos( $term,
':' ) > 0 )
360 return $url ?? $title->getFullUrlForRedirect();
363 private function redirectOnExactMatch() {
366 return $this->userOptionsManager->getDefaultOption(
367 'search-match-redirect',
372 return $this->userOptionsManager->getOption( $this->
getUser(),
'search-match-redirect' );
380 if ( $this->searchEngineType !==
null ) {
381 $this->
setExtraParam(
'srbackend', $this->searchEngineType );
394 $this->languageConverterFactory->getLanguageConverter( $this->getLanguage() ),
396 $this->getSearchProfiles()
399 if ( trim( $term ) ===
'' || $filePrefix === trim( $term ) ) {
401 if ( !$this->
getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
402 # Hook requested termination
409 $out->
addHTML( $formWidget->render(
410 $this->profile, $term, 0, 0,
false, $this->offset, $this->isPowerSearch(), $widgetOptions
416 $engine->setFeatureData(
'rewrite', $this->runSuggestion );
417 $engine->setLimitOffset( $this->limit, $this->offset );
418 $engine->setNamespaces( $this->namespaces );
419 $engine->setSort( $this->sort );
422 $this->
getHookRunner()->onSpecialSearchSetupEngine( $this, $this->profile, $engine );
423 if ( !$this->
getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
424 # Hook requested termination
428 $title = Title::newFromText( $term );
429 $languageConverter = $this->languageConverterFactory->getLanguageConverter( $this->
getContentLanguage() );
430 if ( $languageConverter->hasVariants() ) {
433 $variantTerm = $term;
434 $languageConverter->findVariantLink( $variantTerm, $title );
437 $showSuggestion = $title ===
null || !$title->isKnown();
438 $engine->setShowSuggestion( $showSuggestion );
440 $rewritten = $engine->replacePrefixes( $term );
441 if ( $rewritten !== $term ) {
442 wfDeprecatedMsg(
'SearchEngine::replacePrefixes() was overridden by ' .
443 get_class( $engine ) .
', this is deprecated since MediaWiki 1.32',
444 '1.32',
false,
false );
448 $titleMatches = $engine->searchTitle( $rewritten );
449 $textMatches = $engine->searchText( $rewritten );
452 if ( $textMatches instanceof
Status ) {
453 $textStatus = $textMatches;
454 $textMatches = $textStatus->getValue();
458 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
459 $approxTotalRes =
false;
460 if ( $titleMatches ) {
461 $titleMatchesNum = $titleMatches->
numRows();
462 $numTitleMatches = $titleMatches->getTotalHits();
463 $approxTotalRes = $titleMatches->isApproximateTotalHits();
465 if ( $textMatches ) {
466 $textMatchesNum = $textMatches->
numRows();
469 if ( $textMatchesNum > 0 ) {
470 $engine->augmentSearchResults( $textMatches );
473 $num = $titleMatchesNum + $textMatchesNum;
474 $totalRes = $numTitleMatches + $numTextMatches;
478 $out->
addHTML( $formWidget->render(
479 $this->profile, $term, $num, $totalRes, $approxTotalRes, $this->offset, $this->isPowerSearch(),
484 if ( $textMatches ) {
486 $out->
addHTML( $dymWidget->render( $term, $textMatches ) );
489 $hasSearchErrors = $textStatus && $textStatus->getMessages() !== [];
490 $hasInlineIwResults = $textMatches &&
492 $hasSecondaryIwResults = $textMatches &&
495 $classNames = [
'searchresults' ];
496 if ( $hasSecondaryIwResults ) {
497 $classNames[] =
'mw-searchresults-has-iw';
499 if ( $this->offset > 0 ) {
500 $classNames[] =
'mw-searchresults-has-offset';
502 $out->
addHTML(
'<div class="' . implode(
' ', $classNames ) .
'">' );
504 $out->
addHTML(
'<div class="mw-search-results-info">' );
506 if ( $hasSearchErrors || $this->loadStatus->getMessages() ) {
507 if ( $textStatus ===
null ) {
508 $textStatus = $this->loadStatus;
510 $textStatus->merge( $this->loadStatus );
512 [ $error, $warning ] = $textStatus->splitByErrorType();
513 if ( $error->getMessages() ) {
515 $error->getHTML(
'search-error' )
518 if ( $warning->getMessages() ) {
519 $out->
addHTML( Html::warningBox(
520 $warning->getHTML(
'search-warning' )
526 if ( $num === 0 && !$hasSearchErrors ) {
527 $out->
wrapWikiMsg(
"<p class=\"mw-search-nonefound\">\n$1</p>", [
528 $hasInlineIwResults ?
'search-nonefound-thiswiki' :
'search-nonefound',
535 $this->
showCreateLink( $title, $num, $titleMatches, $textMatches );
537 $this->
getHookRunner()->onSpecialSearchResults( $term, $titleMatches, $textMatches );
550 $this->thumbnailProvider,
551 $this->userOptionsManager
557 $sidebarResultWidget,
559 $this->interwikiLookup,
560 $engine->getFeatureData(
'show-multimedia-search-results' )
565 $out->
addHTML(
'<div class="mw-search-visualclear"></div>' );
566 $this->prevNextLinks( $totalRes, $textMatches, $term,
'mw-search-pager-top', $out );
568 $out->
addHTML( $widget->render(
569 $term, $this->offset, $titleMatches, $textMatches
572 $out->
addHTML(
'<div class="mw-search-visualclear"></div>' );
573 $this->prevNextLinks( $totalRes, $textMatches, $term,
'mw-search-pager-bottom', $out );
578 $this->
getHookRunner()->onSpecialSearchResultsAppend( $this, $out, $term );
591 if ( $title ===
null || $title->getDBkey() ===
''
592 || ( $titleMatches !==
null && $titleMatches->searchContainedSyntax() )
597 $this->
getOutput()->addHTML(
'<p></p>' );
602 $messageName =
'searchmenu-new-nocreate';
603 $linkClass =
'mw-search-createlink';
605 if ( !$title->isExternal() ) {
606 if ( $title->isKnown() ) {
607 $messageName =
'searchmenu-exists';
608 $linkClass =
'mw-search-exists';
610 $this->contentHandlerFactory->getContentHandler( $title->getContentModel() )
611 ->supportsDirectEditing()
612 && $this->getAuthority()->probablyCan(
'edit', $title )
614 $messageName =
'searchmenu-new';
617 $messageName =
'searchmenu-new-external';
629 if ( $messageName ) {
630 $this->
getOutput()->wrapWikiMsg(
"<p class=\"$linkClass\">\n$1</p>",
$params );
633 $this->
getOutput()->addHTML(
'<p></p>' );
650 $out->
getMetadata()->setPreventClickjacking(
false );
653 if ( strval( $term ) !==
'' ) {
656 ->plaintextParams( $this->
msg(
'searchresults-title' )->plaintextParams( $term )->text() )
657 ->inContentLanguage()->text()
661 if ( $this->mPrefix !==
'' ) {
662 $subtitle = $this->
msg(
'search-filter-title-prefix' )->plaintextParams( $this->mPrefix );
675 'title' => $this->
msg(
'search-filter-title-prefix-reset' )->text(),
677 $this->
msg(
'search-filter-title-prefix-reset' )->text()
684 $out->
addModules(
'mediawiki.special.search' );
686 'mediawiki.special',
'mediawiki.special.search.styles',
687 'mediawiki.widgets.SearchInputWidget.styles',
697 return $this->profile ===
'advanced';
709 foreach ( $this->searchConfig->searchableNamespaces() as $ns => $name ) {
710 if ( $request->getCheck(
'ns' . $ns ) ) {
728 foreach ( $this->namespaces as $n ) {
747 if ( $user->isRegistered() &&
748 $user->matchEditToken(
749 $request->getVal(
'nsRemember' ),
752 ) && !$this->readOnlyMode->isReadOnly()
756 foreach ( $this->nsInfo->getValidNamespaces() as $n ) {
757 $this->userOptionsManager->setOption( $user,
'searchNs' . $n,
false );
761 foreach ( $this->namespaces as $n ) {
762 $this->userOptionsManager->setOption( $user,
'searchNs' . $n,
true );
765 DeferredUpdates::addCallableUpdate(
static function () use ( $user ) {
766 $user->saveSettings();
781 $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
782 $defaultNs = $this->searchConfig->defaultNamespaces();
785 'message' =>
'searchprofile-articles',
786 'tooltip' =>
'searchprofile-articles-tooltip',
787 'namespaces' => $defaultNs,
788 'namespace-messages' => $this->searchConfig->namespacesAsText(
793 'message' =>
'searchprofile-images',
794 'tooltip' =>
'searchprofile-images-tooltip',
798 'message' =>
'searchprofile-everything',
799 'tooltip' =>
'searchprofile-everything-tooltip',
800 'namespaces' => $nsAllSet,
803 'message' =>
'searchprofile-advanced',
804 'tooltip' =>
'searchprofile-advanced-tooltip',
805 'namespaces' => self::NAMESPACES_CURRENT,
809 $this->
getHookRunner()->onSpecialSearchProfiles( $profiles );
811 foreach ( $profiles as &$data ) {
812 if ( !is_array( $data[
'namespaces'] ) ) {
815 sort( $data[
'namespaces'] );
827 if ( $this->searchEngine ===
null ) {
828 $this->searchEngine = $this->searchEngineFactory->create( $this->searchEngineType );
860 $this->extraParams[$key] = $value;
882 private function prevNextLinks(
889 if ( $totalRes > $this->limit || $this->offset ) {
892 if ( $textMatches && $textMatches->
getOffset() !==
null ) {
899 $newSearchTerm = $term;
908 $this->limit + $this->offset >= $totalRes );
909 $out->
addHTML(
"<div class='{$class}'>{$prevNext}</div>\n" );
922class_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.