MediaWiki master
SpecialSearch.php
Go to the documentation of this file.
1<?php
23namespace MediaWiki\Specials;
24
50use SearchEngine;
54
70 protected $profile;
71
73 protected $searchEngine;
74
76 protected $searchEngineType = null;
77
79 protected $extraParams = [];
80
85 protected $mPrefix;
86
87 protected int $limit;
88 protected int $offset;
89
93 protected $namespaces;
94
98 protected $fulltext;
99
103 protected $sort = SearchEngine::DEFAULT_SORT;
104
108 protected $runSuggestion = true;
109
114 protected $searchConfig;
115
116 private SearchEngineFactory $searchEngineFactory;
117 private NamespaceInfo $nsInfo;
118 private IContentHandlerFactory $contentHandlerFactory;
119 private InterwikiLookup $interwikiLookup;
120 private ReadOnlyMode $readOnlyMode;
121 private UserOptionsManager $userOptionsManager;
122 private LanguageConverterFactory $languageConverterFactory;
123 private RepoGroup $repoGroup;
124 private SearchResultThumbnailProvider $thumbnailProvider;
125 private TitleMatcher $titleMatcher;
126
131 private $loadStatus;
132
133 private const NAMESPACES_CURRENT = 'sense';
134
135 public function __construct(
137 SearchEngineFactory $searchEngineFactory,
138 NamespaceInfo $nsInfo,
139 IContentHandlerFactory $contentHandlerFactory,
140 InterwikiLookup $interwikiLookup,
141 ReadOnlyMode $readOnlyMode,
142 UserOptionsManager $userOptionsManager,
143 LanguageConverterFactory $languageConverterFactory,
144 RepoGroup $repoGroup,
145 SearchResultThumbnailProvider $thumbnailProvider,
146 TitleMatcher $titleMatcher
147 ) {
148 parent::__construct( 'Search' );
149 $this->searchConfig = $searchConfig;
150 $this->searchEngineFactory = $searchEngineFactory;
151 $this->nsInfo = $nsInfo;
152 $this->contentHandlerFactory = $contentHandlerFactory;
153 $this->interwikiLookup = $interwikiLookup;
154 $this->readOnlyMode = $readOnlyMode;
155 $this->userOptionsManager = $userOptionsManager;
156 $this->languageConverterFactory = $languageConverterFactory;
157 $this->repoGroup = $repoGroup;
158 $this->thumbnailProvider = $thumbnailProvider;
159 $this->titleMatcher = $titleMatcher;
160 }
161
167 public function execute( $par ) {
168 $request = $this->getRequest();
169 $out = $this->getOutput();
170
171 // Fetch the search term
172 $term = str_replace( "\n", " ", $request->getText( 'search' ) );
173
174 // Historically search terms have been accepted not only in the search query
175 // parameter, but also as part of the primary url. This can have PII implications
176 // in releasing page view data. As such issue a 301 redirect to the correct
177 // URL.
178 if ( $par !== null && $par !== '' && $term === '' ) {
179 $query = $request->getQueryValues();
180 unset( $query['title'] );
181 // Strip underscores from title parameter; most of the time we'll want
182 // text form here. But don't strip underscores from actual text params!
183 $query['search'] = str_replace( '_', ' ', $par );
184 $out->redirect( $this->getPageTitle()->getFullURL( $query ), 301 );
185 return;
186 }
187
188 // Need to load selected namespaces before handling nsRemember
189 $this->load();
190 // TODO: This performs database actions on GET request, which is going to
191 // be a problem for our multi-datacenter work.
192 if ( $request->getCheck( 'nsRemember' ) ) {
193 $this->saveNamespaces();
194 // Remove the token from the URL to prevent the user from inadvertently
195 // exposing it (e.g. by pasting it into a public wiki page) or undoing
196 // later settings changes (e.g. by reloading the page).
197 $query = $request->getQueryValues();
198 unset( $query['title'], $query['nsRemember'] );
199 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
200 return;
201 }
202
203 if ( !$request->getVal( 'fulltext' ) && !$request->getCheck( 'offset' ) ) {
204 $url = $this->goResult( $term );
205 if ( $url !== null ) {
206 // successful 'go'
207 $out->redirect( $url );
208 return;
209 }
210 // No match. If it could plausibly be a title
211 // run the No go match hook.
212 $title = Title::newFromText( $term );
213 if ( $title !== null ) {
214 $this->getHookRunner()->onSpecialSearchNogomatch( $title );
215 }
216 }
217
218 $this->setupPage( $term );
219
220 if ( $this->getConfig()->get( MainConfigNames::DisableTextSearch ) ) {
221 $searchForwardUrl = $this->getConfig()->get( MainConfigNames::SearchForwardUrl );
222 if ( $searchForwardUrl ) {
223 $url = str_replace( '$1', urlencode( $term ), $searchForwardUrl );
224 $out->redirect( $url );
225 } else {
226 $out->addHTML( Html::errorBox( Html::rawElement(
227 'p',
228 [ 'class' => 'mw-searchdisabled' ],
229 $this->msg( 'searchdisabled', [ 'mw:Special:MyLanguage/Manual:$wgSearchForwardUrl' ] )->parse()
230 ) ) );
231 }
232
233 return;
234 }
235
236 $this->showResults( $term );
237 }
238
244 public function load() {
245 $this->loadStatus = new Status();
246
247 $request = $this->getRequest();
248 $this->searchEngineType = $request->getVal( 'srbackend' );
249
250 [ $this->limit, $this->offset ] = $request->getLimitOffsetForUser(
251 $this->getUser(),
252 20,
253 'searchlimit'
254 );
255 $this->mPrefix = $request->getVal( 'prefix', '' );
256 if ( $this->mPrefix !== '' ) {
257 $this->setExtraParam( 'prefix', $this->mPrefix );
258 }
259
260 $sort = $request->getVal( 'sort', SearchEngine::DEFAULT_SORT );
261 $validSorts = $this->getSearchEngine()->getValidSorts();
262 if ( !in_array( $sort, $validSorts ) ) {
263 $this->loadStatus->warning( 'search-invalid-sort-order', $sort,
264 implode( ', ', $validSorts ) );
265 } elseif ( $sort !== $this->sort ) {
266 $this->sort = $sort;
267 $this->setExtraParam( 'sort', $this->sort );
268 }
269
270 $user = $this->getUser();
271
272 # Extract manually requested namespaces
273 $nslist = $this->powerSearch( $request );
274 if ( $nslist === [] ) {
275 # Fallback to user preference
276 $nslist = $this->searchConfig->userNamespaces( $user );
277 }
278
279 $profile = null;
280 if ( $nslist === [] ) {
281 $profile = 'default';
282 }
283
284 $profile = $request->getVal( 'profile', $profile );
285 $profiles = $this->getSearchProfiles();
286 if ( $profile === null ) {
287 // BC with old request format
288 $profile = 'advanced';
289 foreach ( $profiles as $key => $data ) {
290 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
291 $profile = $key;
292 }
293 }
294 $this->namespaces = $nslist;
295 } elseif ( $profile === 'advanced' ) {
296 $this->namespaces = $nslist;
297 } elseif ( isset( $profiles[$profile]['namespaces'] ) ) {
298 $this->namespaces = $profiles[$profile]['namespaces'];
299 } else {
300 // Unknown profile requested
301 $this->loadStatus->warning( 'search-unknown-profile', $profile );
302 $profile = 'default';
303 $this->namespaces = $profiles['default']['namespaces'];
304 }
305
306 $this->fulltext = $request->getVal( 'fulltext' );
307 $this->runSuggestion = (bool)$request->getVal( 'runsuggestion', '1' );
308 $this->profile = $profile;
309 }
310
317 public function goResult( $term ) {
318 # If the string cannot be used to create a title
319 if ( Title::newFromText( $term ) === null ) {
320 return null;
321 }
322 # If there's an exact or very near match, jump right there.
323 $title = $this->titleMatcher->getNearMatch( $term );
324 if ( $title === null ) {
325 return null;
326 }
327 $url = null;
328 if ( !$this->getHookRunner()->onSpecialSearchGoResult( $term, $title, $url ) ) {
329 return null;
330 }
331
332 if (
333 // If there is a preference set to NOT redirect on exact page match
334 // then return null (which prevents direction)
335 !$this->redirectOnExactMatch()
336 // BUT ...
337 // ... ignore no-redirect preference if the exact page match is an interwiki link
338 && !$title->isExternal()
339 // ... ignore no-redirect preference if the exact page match is NOT in the main
340 // namespace AND there's a namespace in the search string
341 && !( $title->getNamespace() !== NS_MAIN && strpos( $term, ':' ) > 0 )
342 ) {
343 return null;
344 }
345
346 return $url ?? $title->getFullUrlForRedirect();
347 }
348
349 private function redirectOnExactMatch(): bool {
350 if ( !$this->getConfig()->get( MainConfigNames::SearchMatchRedirectPreference ) ) {
351 // If the preference for whether to redirect is disabled, use the default setting
352 return (bool)$this->userOptionsManager->getDefaultOption(
353 'search-match-redirect',
354 $this->getUser()
355 );
356 } else {
357 // Otherwise use the user's preference
358 return $this->userOptionsManager->getBoolOption( $this->getUser(), 'search-match-redirect' );
359 }
360 }
361
365 public function showResults( $term ) {
366 if ( $this->searchEngineType !== null ) {
367 $this->setExtraParam( 'srbackend', $this->searchEngineType );
368 }
369
370 $out = $this->getOutput();
371 $widgetOptions = $this->getConfig()->get( MainConfigNames::SpecialSearchFormOptions );
372 $formWidget = new SearchFormWidget(
373 new ServiceOptions(
375 $this->getConfig()
376 ),
377 $this,
378 $this->searchConfig,
379 $this->getHookContainer(),
380 $this->languageConverterFactory->getLanguageConverter( $this->getLanguage() ),
381 $this->nsInfo,
382 $this->getSearchProfiles()
383 );
384 $filePrefix = $this->getContentLanguage()->getFormattedNsText( NS_FILE ) . ':';
385 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
386 // Empty query -- straight view of search form
387 if ( !$this->getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
388 # Hook requested termination
389 return;
390 }
391 $out->enableOOUI();
392 // The form also contains the 'Showing results 0 - 20 of 1234' so we can
393 // only do the form render here for the empty $term case. Rendering
394 // the form when a search is provided is repeated below.
395 $out->addHTML( $formWidget->render(
396 $this->profile, $term, 0, 0, false, $this->offset, $this->isPowerSearch(), $widgetOptions
397 ) );
398 return;
399 }
400
401 $engine = $this->getSearchEngine();
402 $engine->setFeatureData( 'rewrite', $this->runSuggestion );
403 $engine->setLimitOffset( $this->limit, $this->offset );
404 $engine->setNamespaces( $this->namespaces );
405 $engine->setSort( $this->sort );
406 $engine->prefix = $this->mPrefix;
407
408 $this->getHookRunner()->onSpecialSearchSetupEngine( $this, $this->profile, $engine );
409 if ( !$this->getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
410 # Hook requested termination
411 return;
412 }
413
414 $title = Title::newFromText( $term );
415 $languageConverter = $this->languageConverterFactory->getLanguageConverter( $this->getContentLanguage() );
416 if ( $languageConverter->hasVariants() ) {
417 // findVariantLink will replace the link arg as well but we want to keep our original
418 // search string, use a copy in the $variantTerm var so that $term remains intact.
419 $variantTerm = $term;
420 $languageConverter->findVariantLink( $variantTerm, $title );
421 }
422
423 $showSuggestion = $title === null || !$title->isKnown();
424 $engine->setShowSuggestion( $showSuggestion );
425
426 $rewritten = $engine->replacePrefixes( $term );
427 if ( $rewritten !== $term ) {
428 wfDeprecatedMsg( 'SearchEngine::replacePrefixes() was overridden by ' .
429 get_class( $engine ) . ', this is deprecated since MediaWiki 1.32',
430 '1.32', false, false );
431 }
432
433 // fetch search results
434 $titleMatches = $engine->searchTitle( $rewritten );
435 $textMatches = $engine->searchText( $rewritten );
436
437 $textStatus = null;
438 if ( $textMatches instanceof Status ) {
439 $textStatus = $textMatches;
440 $textMatches = $textStatus->getValue();
441 }
442
443 // Get number of results
444 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
445 $approxTotalRes = false;
446 if ( $titleMatches ) {
447 $titleMatchesNum = $titleMatches->numRows();
448 $numTitleMatches = $titleMatches->getTotalHits();
449 $approxTotalRes = $titleMatches->isApproximateTotalHits();
450 }
451 if ( $textMatches ) {
452 $textMatchesNum = $textMatches->numRows();
453 $numTextMatches = $textMatches->getTotalHits();
454 $approxTotalRes = $approxTotalRes || $textMatches->isApproximateTotalHits();
455 if ( $textMatchesNum > 0 ) {
456 $engine->augmentSearchResults( $textMatches );
457 }
458 }
459 $num = $titleMatchesNum + $textMatchesNum;
460 $totalRes = $numTitleMatches + $numTextMatches;
461
462 // start rendering the page
463 $out->enableOOUI();
464 $out->addHTML( $formWidget->render(
465 $this->profile, $term, $num, $totalRes, $approxTotalRes, $this->offset, $this->isPowerSearch(),
466 $widgetOptions
467 ) );
468
469 // did you mean... suggestions
470 if ( $textMatches ) {
471 $dymWidget = new DidYouMeanWidget( $this );
472 $out->addHTML( $dymWidget->render( $term, $textMatches ) );
473 }
474
475 $hasSearchErrors = $textStatus && $textStatus->getMessages() !== [];
476 $hasInlineIwResults = $textMatches &&
477 $textMatches->hasInterwikiResults( ISearchResultSet::INLINE_RESULTS );
478 $hasSecondaryIwResults = $textMatches &&
479 $textMatches->hasInterwikiResults( ISearchResultSet::SECONDARY_RESULTS );
480
481 $classNames = [ 'searchresults' ];
482 if ( $hasSecondaryIwResults ) {
483 $classNames[] = 'mw-searchresults-has-iw';
484 }
485 if ( $this->offset > 0 ) {
486 $classNames[] = 'mw-searchresults-has-offset';
487 }
488 $out->addHTML( Html::openElement( 'div', [ 'class' => $classNames ] ) );
489
490 $out->addHTML( '<div class="mw-search-results-info">' );
491
492 if ( $hasSearchErrors || $this->loadStatus->getMessages() ) {
493 if ( $textStatus === null ) {
494 $textStatus = $this->loadStatus;
495 } else {
496 $textStatus->merge( $this->loadStatus );
497 }
498 [ $error, $warning ] = $textStatus->splitByErrorType();
499 if ( $error->getMessages() ) {
500 $out->addHTML( Html::errorBox(
501 $error->getHTML( 'search-error' )
502 ) );
503 }
504 if ( $warning->getMessages() ) {
505 $out->addHTML( Html::warningBox(
506 $warning->getHTML( 'search-warning' )
507 ) );
508 }
509 }
510
511 // If we have no results and have not already displayed an error message
512 if ( $num === 0 && !$hasSearchErrors ) {
513 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", [
514 $hasInlineIwResults ? 'search-nonefound-thiswiki' : 'search-nonefound',
515 wfEscapeWikiText( $term ),
516 $term
517 ] );
518 }
519
520 // Show the create link ahead
521 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
522
523 $this->getHookRunner()->onSpecialSearchResults( $term, $titleMatches, $textMatches );
524
525 // Close <div class='mw-search-results-info'>
526 $out->addHTML( '</div>' );
527
528 // Although $num might be 0 there can still be secondary or inline
529 // results to display.
530 $linkRenderer = $this->getLinkRenderer();
531 $mainResultWidget = new FullSearchResultWidget(
532 $this,
533 $linkRenderer,
534 $this->getHookContainer(),
535 $this->repoGroup,
536 $this->thumbnailProvider,
537 $this->userOptionsManager
538 );
539
540 $sidebarResultWidget = new InterwikiSearchResultWidget( $this, $linkRenderer );
541 $sidebarResultsWidget = new InterwikiSearchResultSetWidget(
542 $this,
543 $sidebarResultWidget,
544 $linkRenderer,
545 $this->interwikiLookup,
546 $engine->getFeatureData( 'show-multimedia-search-results' )
547 );
548
549 $widget = new BasicSearchResultSetWidget( $this, $mainResultWidget, $sidebarResultsWidget );
550
551 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
552 $this->prevNextLinks( $totalRes, $textMatches, $term, 'mw-search-pager-top', $out );
553
554 $out->addHTML( $widget->render(
555 $term, $this->offset, $titleMatches, $textMatches
556 ) );
557
558 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
559 $this->prevNextLinks( $totalRes, $textMatches, $term, 'mw-search-pager-bottom', $out );
560
561 // Close <div class='searchresults'>
562 $out->addHTML( "</div>" );
563
564 $this->getHookRunner()->onSpecialSearchResultsAppend( $this, $out, $term );
565 }
566
573 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
574 // show direct page/create link if applicable
575
576 // Check DBkey !== '' in case of fragment link only.
577 if ( $title === null || $title->getDBkey() === ''
578 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
579 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
580 ) {
581 // invalid title
582 // preserve the paragraph for margins etc...
583 $this->getOutput()->addHTML( '<p></p>' );
584
585 return;
586 }
587
588 $messageName = 'searchmenu-new-nocreate';
589 $linkClass = 'mw-search-createlink';
590
591 if ( !$title->isExternal() ) {
592 if ( $title->isKnown() ) {
593 $messageName = 'searchmenu-exists';
594 $linkClass = 'mw-search-exists';
595 } elseif (
596 $this->contentHandlerFactory->getContentHandler( $title->getContentModel() )
597 ->supportsDirectEditing()
598 && $this->getAuthority()->probablyCan( 'edit', $title )
599 ) {
600 $messageName = 'searchmenu-new';
601 }
602 } else {
603 $messageName = 'searchmenu-new-external';
604 }
605
606 $params = [
607 $messageName,
608 wfEscapeWikiText( $title->getPrefixedText() ),
609 Message::numParam( $num )
610 ];
611 $this->getHookRunner()->onSpecialSearchCreateLink( $title, $params );
612
613 // Extensions using the hook might still return an empty $messageName
614 // @phan-suppress-next-line PhanRedundantCondition Might be unset by hook
615 if ( $messageName ) {
616 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
617 } else {
618 // preserve the paragraph for margins etc...
619 $this->getOutput()->addHTML( '<p></p>' );
620 }
621 }
622
629 protected function setupPage( $term ) {
630 $out = $this->getOutput();
631
632 $this->setHeaders();
633 $this->outputHeader();
634 // TODO: Is this true? The namespace remember uses a user token
635 // on save.
636 $out->getMetadata()->setPreventClickjacking( false );
637 $this->addHelpLink( 'Help:Searching' );
638
639 if ( strval( $term ) !== '' ) {
640 $out->setPageTitleMsg( $this->msg( 'searchresults' ) );
641 $out->setHTMLTitle( $this->msg( 'pagetitle' )
642 ->plaintextParams( $this->msg( 'searchresults-title' )->plaintextParams( $term )->text() )
643 ->inContentLanguage()->text()
644 );
645 }
646
647 if ( $this->mPrefix !== '' ) {
648 $subtitle = $this->msg( 'search-filter-title-prefix' )->plaintextParams( $this->mPrefix );
649 $params = $this->powerSearchOptions();
650 unset( $params['prefix'] );
651 $params += [
652 'search' => $term,
653 'fulltext' => 1,
654 ];
655
656 $subtitle .= ' (';
657 $subtitle .= Html::element(
658 'a',
659 [
660 'href' => $this->getPageTitle()->getLocalURL( $params ),
661 'title' => $this->msg( 'search-filter-title-prefix-reset' )->text(),
662 ],
663 $this->msg( 'search-filter-title-prefix-reset' )->text()
664 );
665 $subtitle .= ')';
666 $out->setSubtitle( $subtitle );
667 }
668
669 $out->addJsConfigVars( [ 'searchTerm' => $term ] );
670 $out->addModules( 'mediawiki.special.search' );
671 $out->addModuleStyles( [
672 'mediawiki.special', 'mediawiki.special.search.styles',
673 'mediawiki.widgets.SearchInputWidget.styles',
674 // Special page makes use of Html::warningBox and Html::errorBox in multiple places.
675 'mediawiki.codex.messagebox.styles',
676 ] );
677 }
678
684 protected function isPowerSearch() {
685 return $this->profile === 'advanced';
686 }
687
695 protected function powerSearch( &$request ) {
696 $arr = [];
697 foreach ( $this->searchConfig->searchableNamespaces() as $ns => $name ) {
698 if ( $request->getCheck( 'ns' . $ns ) ) {
699 $arr[] = $ns;
700 }
701 }
702
703 return $arr;
704 }
705
713 public function powerSearchOptions() {
714 $opt = [];
715 if ( $this->isPowerSearch() ) {
716 foreach ( $this->namespaces as $n ) {
717 $opt['ns' . $n] = 1;
718 }
719 } else {
720 $opt['profile'] = $this->profile;
721 }
722
723 return $opt + $this->extraParams;
724 }
725
731 protected function saveNamespaces() {
732 $user = $this->getUser();
733 $request = $this->getRequest();
734
735 if ( $user->isRegistered() &&
736 $user->matchEditToken(
737 $request->getVal( 'nsRemember' ),
738 'searchnamespace',
739 $request
740 ) && !$this->readOnlyMode->isReadOnly()
741 ) {
742 // Reset namespace preferences: namespaces are not searched
743 // when they're not mentioned in the URL parameters.
744 foreach ( $this->nsInfo->getValidNamespaces() as $n ) {
745 $this->userOptionsManager->setOption( $user, 'searchNs' . $n, false );
746 }
747 // The request parameters include all the namespaces to be searched.
748 // Even if they're the same as an existing profile, they're not eaten.
749 foreach ( $this->namespaces as $n ) {
750 $this->userOptionsManager->setOption( $user, 'searchNs' . $n, true );
751 }
752
753 DeferredUpdates::addCallableUpdate( static function () use ( $user ) {
754 $user->saveSettings();
755 } );
756
757 return true;
758 }
759
760 return false;
761 }
762
767 protected function getSearchProfiles() {
768 // Builds list of Search Types (profiles)
769 $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
770 $defaultNs = $this->searchConfig->defaultNamespaces();
771 $profiles = [
772 'default' => [
773 'message' => 'searchprofile-articles',
774 'tooltip' => 'searchprofile-articles-tooltip',
775 'namespaces' => $defaultNs,
776 'namespace-messages' => $this->searchConfig->namespacesAsText(
777 $defaultNs
778 ),
779 ],
780 'images' => [
781 'message' => 'searchprofile-images',
782 'tooltip' => 'searchprofile-images-tooltip',
783 'namespaces' => [ NS_FILE ],
784 ],
785 'all' => [
786 'message' => 'searchprofile-everything',
787 'tooltip' => 'searchprofile-everything-tooltip',
788 'namespaces' => $nsAllSet,
789 ],
790 'advanced' => [
791 'message' => 'searchprofile-advanced',
792 'tooltip' => 'searchprofile-advanced-tooltip',
793 'namespaces' => self::NAMESPACES_CURRENT,
794 ]
795 ];
796
797 $this->getHookRunner()->onSpecialSearchProfiles( $profiles );
798
799 foreach ( $profiles as &$data ) {
800 if ( !is_array( $data['namespaces'] ) ) {
801 continue;
802 }
803 sort( $data['namespaces'] );
804 }
805
806 return $profiles;
807 }
808
814 public function getSearchEngine() {
815 if ( $this->searchEngine === null ) {
816 $this->searchEngine = $this->searchEngineFactory->create( $this->searchEngineType );
817 }
818
819 return $this->searchEngine;
820 }
821
826 public function getProfile() {
827 return $this->profile;
828 }
829
834 public function getNamespaces() {
835 return $this->namespaces;
836 }
837
847 public function setExtraParam( $key, $value ) {
848 $this->extraParams[$key] = $value;
849 }
850
859 public function getPrefix() {
860 return $this->mPrefix;
861 }
862
870 private function prevNextLinks(
871 ?int $totalRes,
872 ?ISearchResultSet $textMatches,
873 string $term,
874 string $class,
875 OutputPage $out
876 ) {
877 if ( $totalRes > $this->limit || $this->offset ) {
878 // Allow matches to define the correct offset, as interleaved
879 // AB testing may require a different next page offset.
880 if ( $textMatches && $textMatches->getOffset() !== null ) {
881 $offset = $textMatches->getOffset();
882 } else {
883 $offset = $this->offset;
884 }
885
886 // use the rewritten search term for subsequent page searches
887 $newSearchTerm = $term;
888 if ( $textMatches && $textMatches->hasRewrittenQuery() ) {
889 $newSearchTerm = $textMatches->getQueryAfterRewrite();
890 }
891
892 $prevNext =
893 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable offset is not null
894 $this->buildPrevNextNavigation( $offset, $this->limit,
895 $this->powerSearchOptions() + [ 'search' => $newSearchTerm ],
896 $this->limit + $this->offset >= $totalRes );
897 $out->addHTML( "<div class='{$class}'>{$prevNext}</div>\n" );
898 }
899 }
900
901 protected function getGroupName() {
902 return 'pages';
903 }
904}
905
910class_alias( SpecialSearch::class, 'SpecialSearch' );
const NS_FILE
Definition Defines.php:71
const NS_MAIN
Definition Defines.php:65
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.
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:82
A class for passing options to services.
Defer callable updates to run later in the PHP process.
Prioritized list of file repositories.
Definition RepoGroup.php:38
This class is a collection of static functions that serve two purposes:
Definition Html.php:57
An interface for creating language converters.
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()
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:157
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.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form,...
Renders a suggested search for the user, or tells the user a suggested search was run instead of the ...
Renders a 'full' multi-line search result with metadata.
Renders one or more ISearchResultSets into a sidebar grouped by interwiki prefix.
Service implementation of near match title search.
Parent class for all special pages.
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.
Run text & title search and display the output.
null string $profile
Current search profile.
showCreateLink( $title, $num, $titleMatches, $textMatches)
getProfile()
Current search profile.
setupPage( $term)
Sets up everything for the HTML output page including styles, javascript, page title,...
getPrefix()
The prefix value send to Special:Search using the 'prefix' URI param It means that the user is willin...
string null $searchEngineType
Search engine type, if not default.
isPowerSearch()
Return true if current search is a power (advanced) search.
powerSearchOptions()
Reconstruct the 'power search' options for links TODO: Instead of exposing this publicly,...
string $mPrefix
The prefix url parameter.
setExtraParam( $key, $value)
Users of hook SpecialSearchSetupEngine can use this to add more params to links to not lose selection...
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
SearchEngine $searchEngine
Search engine.
saveNamespaces()
Save namespace preferences when we're supposed to.
__construct(SearchEngineConfig $searchConfig, SearchEngineFactory $searchEngineFactory, NamespaceInfo $nsInfo, IContentHandlerFactory $contentHandlerFactory, InterwikiLookup $interwikiLookup, ReadOnlyMode $readOnlyMode, UserOptionsManager $userOptionsManager, LanguageConverterFactory $languageConverterFactory, RepoGroup $repoGroup, SearchResultThumbnailProvider $thumbnailProvider, TitleMatcher $titleMatcher)
powerSearch(&$request)
Extract "power search" namespace settings from the request object, returning a list of index numbers ...
getNamespaces()
Current namespaces.
load()
Set up basic search parameters from the request and user settings.
SearchEngineConfig $searchConfig
Search engine configurations.
goResult( $term)
If an exact title match can be found, jump straight ahead to it.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:54
This is a utility class for dealing with namespaces that encodes all the "magic" behaviors of them ba...
Represents a title within MediaWiki.
Definition Title.php:78
A service class to control user options.
Configuration handling class for SearchEngine.
Factory class for SearchEngine.
Contain a class for special pages.
Determine whether a site is currently in read-only mode.
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.
Service interface for looking up Interwiki records.
element(SerializerNode $parent, SerializerNode $node, $contents)