MediaWiki master
SpecialSearch.php
Go to the documentation of this file.
1<?php
23namespace MediaWiki\Specials;
24
50use RepoGroup;
51use SearchEngine;
55
71 protected $profile;
72
74 protected $searchEngine;
75
77 protected $searchEngineType = null;
78
80 protected $extraParams = [];
81
86 protected $mPrefix;
87
88 protected int $limit;
89 protected int $offset;
90
94 protected $namespaces;
95
99 protected $fulltext;
100
104 protected $sort = SearchEngine::DEFAULT_SORT;
105
109 protected $runSuggestion = true;
110
115 protected $searchConfig;
116
117 private SearchEngineFactory $searchEngineFactory;
118 private NamespaceInfo $nsInfo;
119 private IContentHandlerFactory $contentHandlerFactory;
120 private InterwikiLookup $interwikiLookup;
121 private ReadOnlyMode $readOnlyMode;
122 private UserOptionsManager $userOptionsManager;
123 private LanguageConverterFactory $languageConverterFactory;
124 private RepoGroup $repoGroup;
125 private SearchResultThumbnailProvider $thumbnailProvider;
126 private TitleMatcher $titleMatcher;
127
132 private $loadStatus;
133
134 private const NAMESPACES_CURRENT = 'sense';
135
149 public function __construct(
151 SearchEngineFactory $searchEngineFactory,
152 NamespaceInfo $nsInfo,
153 IContentHandlerFactory $contentHandlerFactory,
154 InterwikiLookup $interwikiLookup,
155 ReadOnlyMode $readOnlyMode,
156 UserOptionsManager $userOptionsManager,
157 LanguageConverterFactory $languageConverterFactory,
158 RepoGroup $repoGroup,
159 SearchResultThumbnailProvider $thumbnailProvider,
160 TitleMatcher $titleMatcher
161 ) {
162 parent::__construct( 'Search' );
163 $this->searchConfig = $searchConfig;
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;
174 }
175
181 public function execute( $par ) {
182 $request = $this->getRequest();
183 $out = $this->getOutput();
184
185 // Fetch the search term
186 $term = str_replace( "\n", " ", $request->getText( 'search' ) );
187
188 // Historically search terms have been accepted not only in the search query
189 // parameter, but also as part of the primary url. This can have PII implications
190 // in releasing page view data. As such issue a 301 redirect to the correct
191 // URL.
192 if ( $par !== null && $par !== '' && $term === '' ) {
193 $query = $request->getQueryValues();
194 unset( $query['title'] );
195 // Strip underscores from title parameter; most of the time we'll want
196 // text form here. But don't strip underscores from actual text params!
197 $query['search'] = str_replace( '_', ' ', $par );
198 $out->redirect( $this->getPageTitle()->getFullURL( $query ), 301 );
199 return;
200 }
201
202 // Need to load selected namespaces before handling nsRemember
203 $this->load();
204 // TODO: This performs database actions on GET request, which is going to
205 // be a problem for our multi-datacenter work.
206 if ( $request->getCheck( 'nsRemember' ) ) {
207 $this->saveNamespaces();
208 // Remove the token from the URL to prevent the user from inadvertently
209 // exposing it (e.g. by pasting it into a public wiki page) or undoing
210 // later settings changes (e.g. by reloading the page).
211 $query = $request->getQueryValues();
212 unset( $query['title'], $query['nsRemember'] );
213 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
214 return;
215 }
216
217 if ( !$request->getVal( 'fulltext' ) && !$request->getCheck( 'offset' ) ) {
218 $url = $this->goResult( $term );
219 if ( $url !== null ) {
220 // successful 'go'
221 $out->redirect( $url );
222 return;
223 }
224 // No match. If it could plausibly be a title
225 // run the No go match hook.
226 $title = Title::newFromText( $term );
227 if ( $title !== null ) {
228 $this->getHookRunner()->onSpecialSearchNogomatch( $title );
229 }
230 }
231
232 $this->setupPage( $term );
233
234 if ( $this->getConfig()->get( MainConfigNames::DisableTextSearch ) ) {
235 $searchForwardUrl = $this->getConfig()->get( MainConfigNames::SearchForwardUrl );
236 if ( $searchForwardUrl ) {
237 $url = str_replace( '$1', urlencode( $term ), $searchForwardUrl );
238 $out->redirect( $url );
239 } else {
240 $out->addHTML( Html::errorBox( Html::rawElement(
241 'p',
242 [ 'class' => 'mw-searchdisabled' ],
243 $this->msg( 'searchdisabled', [ 'mw:Special:MyLanguage/Manual:$wgSearchForwardUrl' ] )->parse()
244 ) ) );
245 }
246
247 return;
248 }
249
250 $this->showResults( $term );
251 }
252
258 public function load() {
259 $this->loadStatus = new Status();
260
261 $request = $this->getRequest();
262 $this->searchEngineType = $request->getVal( 'srbackend' );
263
264 [ $this->limit, $this->offset ] = $request->getLimitOffsetForUser(
265 $this->getUser(),
266 20,
267 'searchlimit'
268 );
269 $this->mPrefix = $request->getVal( 'prefix', '' );
270 if ( $this->mPrefix !== '' ) {
271 $this->setExtraParam( 'prefix', $this->mPrefix );
272 }
273
274 $sort = $request->getVal( 'sort', SearchEngine::DEFAULT_SORT );
275 $validSorts = $this->getSearchEngine()->getValidSorts();
276 if ( !in_array( $sort, $validSorts ) ) {
277 $this->loadStatus->warning( 'search-invalid-sort-order', $sort,
278 implode( ', ', $validSorts ) );
279 } elseif ( $sort !== $this->sort ) {
280 $this->sort = $sort;
281 $this->setExtraParam( 'sort', $this->sort );
282 }
283
284 $user = $this->getUser();
285
286 # Extract manually requested namespaces
287 $nslist = $this->powerSearch( $request );
288 if ( $nslist === [] ) {
289 # Fallback to user preference
290 $nslist = $this->searchConfig->userNamespaces( $user );
291 }
292
293 $profile = null;
294 if ( $nslist === [] ) {
295 $profile = 'default';
296 }
297
298 $profile = $request->getVal( 'profile', $profile );
299 $profiles = $this->getSearchProfiles();
300 if ( $profile === null ) {
301 // BC with old request format
302 $profile = 'advanced';
303 foreach ( $profiles as $key => $data ) {
304 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
305 $profile = $key;
306 }
307 }
308 $this->namespaces = $nslist;
309 } elseif ( $profile === 'advanced' ) {
310 $this->namespaces = $nslist;
311 } elseif ( isset( $profiles[$profile]['namespaces'] ) ) {
312 $this->namespaces = $profiles[$profile]['namespaces'];
313 } else {
314 // Unknown profile requested
315 $this->loadStatus->warning( 'search-unknown-profile', $profile );
316 $profile = 'default';
317 $this->namespaces = $profiles['default']['namespaces'];
318 }
319
320 $this->fulltext = $request->getVal( 'fulltext' );
321 $this->runSuggestion = (bool)$request->getVal( 'runsuggestion', '1' );
322 $this->profile = $profile;
323 }
324
331 public function goResult( $term ) {
332 # If the string cannot be used to create a title
333 if ( Title::newFromText( $term ) === null ) {
334 return null;
335 }
336 # If there's an exact or very near match, jump right there.
337 $title = $this->titleMatcher->getNearMatch( $term );
338 if ( $title === null ) {
339 return null;
340 }
341 $url = null;
342 if ( !$this->getHookRunner()->onSpecialSearchGoResult( $term, $title, $url ) ) {
343 return null;
344 }
345
346 if (
347 // If there is a preference set to NOT redirect on exact page match
348 // then return null (which prevents direction)
349 !$this->redirectOnExactMatch()
350 // BUT ...
351 // ... ignore no-redirect preference if the exact page match is an interwiki link
352 && !$title->isExternal()
353 // ... ignore no-redirect preference if the exact page match is NOT in the main
354 // namespace AND there's a namespace in the search string
355 && !( $title->getNamespace() !== NS_MAIN && strpos( $term, ':' ) > 0 )
356 ) {
357 return null;
358 }
359
360 return $url ?? $title->getFullUrlForRedirect();
361 }
362
363 private function redirectOnExactMatch() {
365 // If the preference for whether to redirect is disabled, use the default setting
366 return $this->userOptionsManager->getDefaultOption(
367 'search-match-redirect',
368 $this->getUser()
369 );
370 } else {
371 // Otherwise use the user's preference
372 return $this->userOptionsManager->getOption( $this->getUser(), 'search-match-redirect' );
373 }
374 }
375
379 public function showResults( $term ) {
380 if ( $this->searchEngineType !== null ) {
381 $this->setExtraParam( 'srbackend', $this->searchEngineType );
382 }
383
384 $out = $this->getOutput();
385 $widgetOptions = $this->getConfig()->get( MainConfigNames::SpecialSearchFormOptions );
386 $formWidget = new SearchFormWidget(
387 new ServiceOptions(
389 $this->getConfig()
390 ),
391 $this,
392 $this->searchConfig,
393 $this->getHookContainer(),
394 $this->languageConverterFactory->getLanguageConverter( $this->getLanguage() ),
395 $this->nsInfo,
396 $this->getSearchProfiles()
397 );
398 $filePrefix = $this->getContentLanguage()->getFormattedNsText( NS_FILE ) . ':';
399 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
400 // Empty query -- straight view of search form
401 if ( !$this->getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
402 # Hook requested termination
403 return;
404 }
405 $out->enableOOUI();
406 // The form also contains the 'Showing results 0 - 20 of 1234' so we can
407 // only do the form render here for the empty $term case. Rendering
408 // the form when a search is provided is repeated below.
409 $out->addHTML( $formWidget->render(
410 $this->profile, $term, 0, 0, false, $this->offset, $this->isPowerSearch(), $widgetOptions
411 ) );
412 return;
413 }
414
415 $engine = $this->getSearchEngine();
416 $engine->setFeatureData( 'rewrite', $this->runSuggestion );
417 $engine->setLimitOffset( $this->limit, $this->offset );
418 $engine->setNamespaces( $this->namespaces );
419 $engine->setSort( $this->sort );
420 $engine->prefix = $this->mPrefix;
421
422 $this->getHookRunner()->onSpecialSearchSetupEngine( $this, $this->profile, $engine );
423 if ( !$this->getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
424 # Hook requested termination
425 return;
426 }
427
428 $title = Title::newFromText( $term );
429 $languageConverter = $this->languageConverterFactory->getLanguageConverter( $this->getContentLanguage() );
430 if ( $languageConverter->hasVariants() ) {
431 // findVariantLink will replace the link arg as well but we want to keep our original
432 // search string, use a copy in the $variantTerm var so that $term remains intact.
433 $variantTerm = $term;
434 $languageConverter->findVariantLink( $variantTerm, $title );
435 }
436
437 $showSuggestion = $title === null || !$title->isKnown();
438 $engine->setShowSuggestion( $showSuggestion );
439
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 );
445 }
446
447 // fetch search results
448 $titleMatches = $engine->searchTitle( $rewritten );
449 $textMatches = $engine->searchText( $rewritten );
450
451 $textStatus = null;
452 if ( $textMatches instanceof Status ) {
453 $textStatus = $textMatches;
454 $textMatches = $textStatus->getValue();
455 }
456
457 // Get number of results
458 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
459 $approxTotalRes = false;
460 if ( $titleMatches ) {
461 $titleMatchesNum = $titleMatches->numRows();
462 $numTitleMatches = $titleMatches->getTotalHits();
463 $approxTotalRes = $titleMatches->isApproximateTotalHits();
464 }
465 if ( $textMatches ) {
466 $textMatchesNum = $textMatches->numRows();
467 $numTextMatches = $textMatches->getTotalHits();
468 $approxTotalRes = $approxTotalRes || $textMatches->isApproximateTotalHits();
469 if ( $textMatchesNum > 0 ) {
470 $engine->augmentSearchResults( $textMatches );
471 }
472 }
473 $num = $titleMatchesNum + $textMatchesNum;
474 $totalRes = $numTitleMatches + $numTextMatches;
475
476 // start rendering the page
477 $out->enableOOUI();
478 $out->addHTML( $formWidget->render(
479 $this->profile, $term, $num, $totalRes, $approxTotalRes, $this->offset, $this->isPowerSearch(),
480 $widgetOptions
481 ) );
482
483 // did you mean... suggestions
484 if ( $textMatches ) {
485 $dymWidget = new DidYouMeanWidget( $this );
486 $out->addHTML( $dymWidget->render( $term, $textMatches ) );
487 }
488
489 $hasSearchErrors = $textStatus && $textStatus->getMessages() !== [];
490 $hasInlineIwResults = $textMatches &&
491 $textMatches->hasInterwikiResults( ISearchResultSet::INLINE_RESULTS );
492 $hasSecondaryIwResults = $textMatches &&
493 $textMatches->hasInterwikiResults( ISearchResultSet::SECONDARY_RESULTS );
494
495 $classNames = [ 'searchresults' ];
496 if ( $hasSecondaryIwResults ) {
497 $classNames[] = 'mw-searchresults-has-iw';
498 }
499 if ( $this->offset > 0 ) {
500 $classNames[] = 'mw-searchresults-has-offset';
501 }
502 $out->addHTML( '<div class="' . implode( ' ', $classNames ) . '">' );
503
504 $out->addHTML( '<div class="mw-search-results-info">' );
505
506 if ( $hasSearchErrors || $this->loadStatus->getMessages() ) {
507 if ( $textStatus === null ) {
508 $textStatus = $this->loadStatus;
509 } else {
510 $textStatus->merge( $this->loadStatus );
511 }
512 [ $error, $warning ] = $textStatus->splitByErrorType();
513 if ( $error->getMessages() ) {
514 $out->addHTML( Html::errorBox(
515 $error->getHTML( 'search-error' )
516 ) );
517 }
518 if ( $warning->getMessages() ) {
519 $out->addHTML( Html::warningBox(
520 $warning->getHTML( 'search-warning' )
521 ) );
522 }
523 }
524
525 // If we have no results and have not already displayed an error message
526 if ( $num === 0 && !$hasSearchErrors ) {
527 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", [
528 $hasInlineIwResults ? 'search-nonefound-thiswiki' : 'search-nonefound',
529 wfEscapeWikiText( $term ),
530 $term
531 ] );
532 }
533
534 // Show the create link ahead
535 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
536
537 $this->getHookRunner()->onSpecialSearchResults( $term, $titleMatches, $textMatches );
538
539 // Close <div class='mw-search-results-info'>
540 $out->addHTML( '</div>' );
541
542 // Although $num might be 0 there can still be secondary or inline
543 // results to display.
544 $linkRenderer = $this->getLinkRenderer();
545 $mainResultWidget = new FullSearchResultWidget(
546 $this,
547 $linkRenderer,
548 $this->getHookContainer(),
549 $this->repoGroup,
550 $this->thumbnailProvider,
551 $this->userOptionsManager
552 );
553
554 $sidebarResultWidget = new InterwikiSearchResultWidget( $this, $linkRenderer );
555 $sidebarResultsWidget = new InterwikiSearchResultSetWidget(
556 $this,
557 $sidebarResultWidget,
558 $linkRenderer,
559 $this->interwikiLookup,
560 $engine->getFeatureData( 'show-multimedia-search-results' )
561 );
562
563 $widget = new BasicSearchResultSetWidget( $this, $mainResultWidget, $sidebarResultsWidget );
564
565 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
566 $this->prevNextLinks( $totalRes, $textMatches, $term, 'mw-search-pager-top', $out );
567
568 $out->addHTML( $widget->render(
569 $term, $this->offset, $titleMatches, $textMatches
570 ) );
571
572 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
573 $this->prevNextLinks( $totalRes, $textMatches, $term, 'mw-search-pager-bottom', $out );
574
575 // Close <div class='searchresults'>
576 $out->addHTML( "</div>" );
577
578 $this->getHookRunner()->onSpecialSearchResultsAppend( $this, $out, $term );
579 }
580
587 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
588 // show direct page/create link if applicable
589
590 // Check DBkey !== '' in case of fragment link only.
591 if ( $title === null || $title->getDBkey() === ''
592 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
593 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
594 ) {
595 // invalid title
596 // preserve the paragraph for margins etc...
597 $this->getOutput()->addHTML( '<p></p>' );
598
599 return;
600 }
601
602 $messageName = 'searchmenu-new-nocreate';
603 $linkClass = 'mw-search-createlink';
604
605 if ( !$title->isExternal() ) {
606 if ( $title->isKnown() ) {
607 $messageName = 'searchmenu-exists';
608 $linkClass = 'mw-search-exists';
609 } elseif (
610 $this->contentHandlerFactory->getContentHandler( $title->getContentModel() )
611 ->supportsDirectEditing()
612 && $this->getAuthority()->probablyCan( 'edit', $title )
613 ) {
614 $messageName = 'searchmenu-new';
615 }
616 } else {
617 $messageName = 'searchmenu-new-external';
618 }
619
620 $params = [
621 $messageName,
622 wfEscapeWikiText( $title->getPrefixedText() ),
623 Message::numParam( $num )
624 ];
625 $this->getHookRunner()->onSpecialSearchCreateLink( $title, $params );
626
627 // Extensions using the hook might still return an empty $messageName
628 // @phan-suppress-next-line PhanRedundantCondition Might be unset by hook
629 if ( $messageName ) {
630 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
631 } else {
632 // preserve the paragraph for margins etc...
633 $this->getOutput()->addHTML( '<p></p>' );
634 }
635 }
636
643 protected function setupPage( $term ) {
644 $out = $this->getOutput();
645
646 $this->setHeaders();
647 $this->outputHeader();
648 // TODO: Is this true? The namespace remember uses a user token
649 // on save.
650 $out->getMetadata()->setPreventClickjacking( false );
651 $this->addHelpLink( 'Help:Searching' );
652
653 if ( strval( $term ) !== '' ) {
654 $out->setPageTitleMsg( $this->msg( 'searchresults' ) );
655 $out->setHTMLTitle( $this->msg( 'pagetitle' )
656 ->plaintextParams( $this->msg( 'searchresults-title' )->plaintextParams( $term )->text() )
657 ->inContentLanguage()->text()
658 );
659 }
660
661 if ( $this->mPrefix !== '' ) {
662 $subtitle = $this->msg( 'search-filter-title-prefix' )->plaintextParams( $this->mPrefix );
663 $params = $this->powerSearchOptions();
664 unset( $params['prefix'] );
665 $params += [
666 'search' => $term,
667 'fulltext' => 1,
668 ];
669
670 $subtitle .= ' (';
671 $subtitle .= Xml::element(
672 'a',
673 [
674 'href' => $this->getPageTitle()->getLocalURL( $params ),
675 'title' => $this->msg( 'search-filter-title-prefix-reset' )->text(),
676 ],
677 $this->msg( 'search-filter-title-prefix-reset' )->text()
678 );
679 $subtitle .= ')';
680 $out->setSubtitle( $subtitle );
681 }
682
683 $out->addJsConfigVars( [ 'searchTerm' => $term ] );
684 $out->addModules( 'mediawiki.special.search' );
685 $out->addModuleStyles( [
686 'mediawiki.special', 'mediawiki.special.search.styles',
687 'mediawiki.widgets.SearchInputWidget.styles',
688 ] );
689 }
690
696 protected function isPowerSearch() {
697 return $this->profile === 'advanced';
698 }
699
707 protected function powerSearch( &$request ) {
708 $arr = [];
709 foreach ( $this->searchConfig->searchableNamespaces() as $ns => $name ) {
710 if ( $request->getCheck( 'ns' . $ns ) ) {
711 $arr[] = $ns;
712 }
713 }
714
715 return $arr;
716 }
717
725 public function powerSearchOptions() {
726 $opt = [];
727 if ( $this->isPowerSearch() ) {
728 foreach ( $this->namespaces as $n ) {
729 $opt['ns' . $n] = 1;
730 }
731 } else {
732 $opt['profile'] = $this->profile;
733 }
734
735 return $opt + $this->extraParams;
736 }
737
743 protected function saveNamespaces() {
744 $user = $this->getUser();
745 $request = $this->getRequest();
746
747 if ( $user->isRegistered() &&
748 $user->matchEditToken(
749 $request->getVal( 'nsRemember' ),
750 'searchnamespace',
751 $request
752 ) && !$this->readOnlyMode->isReadOnly()
753 ) {
754 // Reset namespace preferences: namespaces are not searched
755 // when they're not mentioned in the URL parameters.
756 foreach ( $this->nsInfo->getValidNamespaces() as $n ) {
757 $this->userOptionsManager->setOption( $user, 'searchNs' . $n, false );
758 }
759 // The request parameters include all the namespaces to be searched.
760 // Even if they're the same as an existing profile, they're not eaten.
761 foreach ( $this->namespaces as $n ) {
762 $this->userOptionsManager->setOption( $user, 'searchNs' . $n, true );
763 }
764
765 DeferredUpdates::addCallableUpdate( static function () use ( $user ) {
766 $user->saveSettings();
767 } );
768
769 return true;
770 }
771
772 return false;
773 }
774
779 protected function getSearchProfiles() {
780 // Builds list of Search Types (profiles)
781 $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
782 $defaultNs = $this->searchConfig->defaultNamespaces();
783 $profiles = [
784 'default' => [
785 'message' => 'searchprofile-articles',
786 'tooltip' => 'searchprofile-articles-tooltip',
787 'namespaces' => $defaultNs,
788 'namespace-messages' => $this->searchConfig->namespacesAsText(
789 $defaultNs
790 ),
791 ],
792 'images' => [
793 'message' => 'searchprofile-images',
794 'tooltip' => 'searchprofile-images-tooltip',
795 'namespaces' => [ NS_FILE ],
796 ],
797 'all' => [
798 'message' => 'searchprofile-everything',
799 'tooltip' => 'searchprofile-everything-tooltip',
800 'namespaces' => $nsAllSet,
801 ],
802 'advanced' => [
803 'message' => 'searchprofile-advanced',
804 'tooltip' => 'searchprofile-advanced-tooltip',
805 'namespaces' => self::NAMESPACES_CURRENT,
806 ]
807 ];
808
809 $this->getHookRunner()->onSpecialSearchProfiles( $profiles );
810
811 foreach ( $profiles as &$data ) {
812 if ( !is_array( $data['namespaces'] ) ) {
813 continue;
814 }
815 sort( $data['namespaces'] );
816 }
817
818 return $profiles;
819 }
820
826 public function getSearchEngine() {
827 if ( $this->searchEngine === null ) {
828 $this->searchEngine = $this->searchEngineFactory->create( $this->searchEngineType );
829 }
830
831 return $this->searchEngine;
832 }
833
838 public function getProfile() {
839 return $this->profile;
840 }
841
846 public function getNamespaces() {
847 return $this->namespaces;
848 }
849
859 public function setExtraParam( $key, $value ) {
860 $this->extraParams[$key] = $value;
861 }
862
871 public function getPrefix() {
872 return $this->mPrefix;
873 }
874
882 private function prevNextLinks(
883 ?int $totalRes,
884 ?ISearchResultSet $textMatches,
885 string $term,
886 string $class,
887 OutputPage $out
888 ) {
889 if ( $totalRes > $this->limit || $this->offset ) {
890 // Allow matches to define the correct offset, as interleaved
891 // AB testing may require a different next page offset.
892 if ( $textMatches && $textMatches->getOffset() !== null ) {
893 $offset = $textMatches->getOffset();
894 } else {
896 }
897
898 // use the rewritten search term for subsequent page searches
899 $newSearchTerm = $term;
900 if ( $textMatches && $textMatches->hasRewrittenQuery() ) {
901 $newSearchTerm = $textMatches->getQueryAfterRewrite();
902 }
903
904 $prevNext =
905 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable offset is not null
906 $this->buildPrevNextNavigation( $offset, $this->limit,
907 $this->powerSearchOptions() + [ 'search' => $newSearchTerm ],
908 $this->limit + $this->offset >= $totalRes );
909 $out->addHTML( "<div class='{$class}'>{$prevNext}</div>\n" );
910 }
911 }
912
913 protected function getGroupName() {
914 return 'pages';
915 }
916}
917
922class_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.
array $params
The job parameters.
A class for passing options to services.
Defer callable updates to run later in the PHP process.
This class is a collection of static functions that serve two purposes:
Definition Html.php:56
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition Html.php:216
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 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()
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:155
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.
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.
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.
Module of static functions for generating XML.
Definition Xml.php:37
Prioritized list of file repositories.
Definition RepoGroup.php:32
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.