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