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( $this->showGoogleSearch( $term ) );
241 }
242
243 return;
244 }
245
246 $this->showResults( $term );
247 }
248
257 private function showGoogleSearch( $term ) {
258 return "<fieldset>" .
259 "<legend>" .
260 $this->msg( 'search-external' )->escaped() .
261 "</legend>" .
262 "<p class='mw-searchdisabled'>" .
263 $this->msg( 'searchdisabled' )->escaped() .
264 "</p>" .
265 // googlesearch is part of $wgRawHtmlMessages and safe to use as is here
266 $this->msg( 'googlesearch' )->rawParams(
267 htmlspecialchars( $term ),
268 'UTF-8',
269 $this->msg( 'searchbutton' )->escaped()
270 )->text() .
271 "</fieldset>";
272 }
273
279 public function load() {
280 $this->loadStatus = new Status();
281
282 $request = $this->getRequest();
283 $this->searchEngineType = $request->getVal( 'srbackend' );
284
285 [ $this->limit, $this->offset ] = $request->getLimitOffsetForUser(
286 $this->getUser(),
287 20,
288 'searchlimit'
289 );
290 $this->mPrefix = $request->getVal( 'prefix', '' );
291 if ( $this->mPrefix !== '' ) {
292 $this->setExtraParam( 'prefix', $this->mPrefix );
293 }
294
295 $sort = $request->getVal( 'sort', SearchEngine::DEFAULT_SORT );
296 $validSorts = $this->getSearchEngine()->getValidSorts();
297 if ( !in_array( $sort, $validSorts ) ) {
298 $this->loadStatus->warning( 'search-invalid-sort-order', $sort,
299 implode( ', ', $validSorts ) );
300 } elseif ( $sort !== $this->sort ) {
301 $this->sort = $sort;
302 $this->setExtraParam( 'sort', $this->sort );
303 }
304
305 $user = $this->getUser();
306
307 # Extract manually requested namespaces
308 $nslist = $this->powerSearch( $request );
309 if ( $nslist === [] ) {
310 # Fallback to user preference
311 $nslist = $this->searchConfig->userNamespaces( $user );
312 }
313
314 $profile = null;
315 if ( $nslist === [] ) {
316 $profile = 'default';
317 }
318
319 $profile = $request->getVal( 'profile', $profile );
320 $profiles = $this->getSearchProfiles();
321 if ( $profile === null ) {
322 // BC with old request format
323 $profile = 'advanced';
324 foreach ( $profiles as $key => $data ) {
325 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
326 $profile = $key;
327 }
328 }
329 $this->namespaces = $nslist;
330 } elseif ( $profile === 'advanced' ) {
331 $this->namespaces = $nslist;
332 } elseif ( isset( $profiles[$profile]['namespaces'] ) ) {
333 $this->namespaces = $profiles[$profile]['namespaces'];
334 } else {
335 // Unknown profile requested
336 $this->loadStatus->warning( 'search-unknown-profile', $profile );
337 $profile = 'default';
338 $this->namespaces = $profiles['default']['namespaces'];
339 }
340
341 $this->fulltext = $request->getVal( 'fulltext' );
342 $this->runSuggestion = (bool)$request->getVal( 'runsuggestion', '1' );
343 $this->profile = $profile;
344 }
345
352 public function goResult( $term ) {
353 # If the string cannot be used to create a title
354 if ( Title::newFromText( $term ) === null ) {
355 return null;
356 }
357 # If there's an exact or very near match, jump right there.
358 $title = $this->titleMatcher->getNearMatch( $term );
359 if ( $title === null ) {
360 return null;
361 }
362 $url = null;
363 if ( !$this->getHookRunner()->onSpecialSearchGoResult( $term, $title, $url ) ) {
364 return null;
365 }
366
367 if (
368 // If there is a preference set to NOT redirect on exact page match
369 // then return null (which prevents direction)
370 !$this->redirectOnExactMatch()
371 // BUT ...
372 // ... ignore no-redirect preference if the exact page match is an interwiki link
373 && !$title->isExternal()
374 // ... ignore no-redirect preference if the exact page match is NOT in the main
375 // namespace AND there's a namespace in the search string
376 && !( $title->getNamespace() !== NS_MAIN && strpos( $term, ':' ) > 0 )
377 ) {
378 return null;
379 }
380
381 return $url ?? $title->getFullUrlForRedirect();
382 }
383
384 private function redirectOnExactMatch() {
386 // If the preference for whether to redirect is disabled, use the default setting
387 return $this->userOptionsManager->getDefaultOption(
388 'search-match-redirect',
389 $this->getUser()
390 );
391 } else {
392 // Otherwise use the user's preference
393 return $this->userOptionsManager->getOption( $this->getUser(), 'search-match-redirect' );
394 }
395 }
396
400 public function showResults( $term ) {
401 if ( $this->searchEngineType !== null ) {
402 $this->setExtraParam( 'srbackend', $this->searchEngineType );
403 }
404
405 $out = $this->getOutput();
406 $widgetOptions = $this->getConfig()->get( MainConfigNames::SpecialSearchFormOptions );
407 $formWidget = new SearchFormWidget(
408 new ServiceOptions(
410 $this->getConfig()
411 ),
412 $this,
413 $this->searchConfig,
414 $this->getHookContainer(),
415 $this->languageConverterFactory->getLanguageConverter( $this->getLanguage() ),
416 $this->nsInfo,
417 $this->getSearchProfiles()
418 );
419 $filePrefix = $this->getContentLanguage()->getFormattedNsText( NS_FILE ) . ':';
420 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
421 // Empty query -- straight view of search form
422 if ( !$this->getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
423 # Hook requested termination
424 return;
425 }
426 $out->enableOOUI();
427 // The form also contains the 'Showing results 0 - 20 of 1234' so we can
428 // only do the form render here for the empty $term case. Rendering
429 // the form when a search is provided is repeated below.
430 $out->addHTML( $formWidget->render(
431 $this->profile, $term, 0, 0, false, $this->offset, $this->isPowerSearch(), $widgetOptions
432 ) );
433 return;
434 }
435
436 $engine = $this->getSearchEngine();
437 $engine->setFeatureData( 'rewrite', $this->runSuggestion );
438 $engine->setLimitOffset( $this->limit, $this->offset );
439 $engine->setNamespaces( $this->namespaces );
440 $engine->setSort( $this->sort );
441 $engine->prefix = $this->mPrefix;
442
443 $this->getHookRunner()->onSpecialSearchSetupEngine( $this, $this->profile, $engine );
444 if ( !$this->getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
445 # Hook requested termination
446 return;
447 }
448
449 $title = Title::newFromText( $term );
450 $languageConverter = $this->languageConverterFactory->getLanguageConverter( $this->getContentLanguage() );
451 if ( $languageConverter->hasVariants() ) {
452 // findVariantLink will replace the link arg as well but we want to keep our original
453 // search string, use a copy in the $variantTerm var so that $term remains intact.
454 $variantTerm = $term;
455 $languageConverter->findVariantLink( $variantTerm, $title );
456 }
457
458 $showSuggestion = $title === null || !$title->isKnown();
459 $engine->setShowSuggestion( $showSuggestion );
460
461 $rewritten = $engine->replacePrefixes( $term );
462 if ( $rewritten !== $term ) {
463 wfDeprecatedMsg( 'SearchEngine::replacePrefixes() was overridden by ' .
464 get_class( $engine ) . ', this is deprecated since MediaWiki 1.32',
465 '1.32', false, false );
466 }
467
468 // fetch search results
469 $titleMatches = $engine->searchTitle( $rewritten );
470 $textMatches = $engine->searchText( $rewritten );
471
472 $textStatus = null;
473 if ( $textMatches instanceof Status ) {
474 $textStatus = $textMatches;
475 $textMatches = $textStatus->getValue();
476 }
477
478 // Get number of results
479 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
480 $approxTotalRes = false;
481 if ( $titleMatches ) {
482 $titleMatchesNum = $titleMatches->numRows();
483 $numTitleMatches = $titleMatches->getTotalHits();
484 $approxTotalRes = $titleMatches->isApproximateTotalHits();
485 }
486 if ( $textMatches ) {
487 $textMatchesNum = $textMatches->numRows();
488 $numTextMatches = $textMatches->getTotalHits();
489 $approxTotalRes = $approxTotalRes || $textMatches->isApproximateTotalHits();
490 if ( $textMatchesNum > 0 ) {
491 $engine->augmentSearchResults( $textMatches );
492 }
493 }
494 $num = $titleMatchesNum + $textMatchesNum;
495 $totalRes = $numTitleMatches + $numTextMatches;
496
497 // start rendering the page
498 $out->enableOOUI();
499 $out->addHTML( $formWidget->render(
500 $this->profile, $term, $num, $totalRes, $approxTotalRes, $this->offset, $this->isPowerSearch(),
501 $widgetOptions
502 ) );
503
504 // did you mean... suggestions
505 if ( $textMatches ) {
506 $dymWidget = new DidYouMeanWidget( $this );
507 $out->addHTML( $dymWidget->render( $term, $textMatches ) );
508 }
509
510 $hasSearchErrors = $textStatus && $textStatus->getMessages() !== [];
511 $hasInlineIwResults = $textMatches &&
512 $textMatches->hasInterwikiResults( ISearchResultSet::INLINE_RESULTS );
513 $hasSecondaryIwResults = $textMatches &&
514 $textMatches->hasInterwikiResults( ISearchResultSet::SECONDARY_RESULTS );
515
516 $classNames = [ 'searchresults' ];
517 if ( $hasSecondaryIwResults ) {
518 $classNames[] = 'mw-searchresults-has-iw';
519 }
520 if ( $this->offset > 0 ) {
521 $classNames[] = 'mw-searchresults-has-offset';
522 }
523 $out->addHTML( '<div class="' . implode( ' ', $classNames ) . '">' );
524
525 $out->addHTML( '<div class="mw-search-results-info">' );
526
527 if ( $hasSearchErrors || $this->loadStatus->getMessages() ) {
528 if ( $textStatus === null ) {
529 $textStatus = $this->loadStatus;
530 } else {
531 $textStatus->merge( $this->loadStatus );
532 }
533 [ $error, $warning ] = $textStatus->splitByErrorType();
534 if ( $error->getMessages() ) {
535 $out->addHTML( Html::errorBox(
536 $error->getHTML( 'search-error' )
537 ) );
538 }
539 if ( $warning->getMessages() ) {
540 $out->addHTML( Html::warningBox(
541 $warning->getHTML( 'search-warning' )
542 ) );
543 }
544 }
545
546 // If we have no results and have not already displayed an error message
547 if ( $num === 0 && !$hasSearchErrors ) {
548 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", [
549 $hasInlineIwResults ? 'search-nonefound-thiswiki' : 'search-nonefound',
550 wfEscapeWikiText( $term ),
551 $term
552 ] );
553 }
554
555 // Show the create link ahead
556 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
557
558 $this->getHookRunner()->onSpecialSearchResults( $term, $titleMatches, $textMatches );
559
560 // Close <div class='mw-search-results-info'>
561 $out->addHTML( '</div>' );
562
563 // Although $num might be 0 there can still be secondary or inline
564 // results to display.
565 $linkRenderer = $this->getLinkRenderer();
566 $mainResultWidget = new FullSearchResultWidget(
567 $this,
568 $linkRenderer,
569 $this->getHookContainer(),
570 $this->repoGroup,
571 $this->thumbnailProvider,
572 $this->userOptionsManager
573 );
574
575 $sidebarResultWidget = new InterwikiSearchResultWidget( $this, $linkRenderer );
576 $sidebarResultsWidget = new InterwikiSearchResultSetWidget(
577 $this,
578 $sidebarResultWidget,
579 $linkRenderer,
580 $this->interwikiLookup,
581 $engine->getFeatureData( 'show-multimedia-search-results' )
582 );
583
584 $widget = new BasicSearchResultSetWidget( $this, $mainResultWidget, $sidebarResultsWidget );
585
586 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
587 $this->prevNextLinks( $totalRes, $textMatches, $term, 'mw-search-pager-top', $out );
588
589 $out->addHTML( $widget->render(
590 $term, $this->offset, $titleMatches, $textMatches
591 ) );
592
593 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
594 $this->prevNextLinks( $totalRes, $textMatches, $term, 'mw-search-pager-bottom', $out );
595
596 // Close <div class='searchresults'>
597 $out->addHTML( "</div>" );
598
599 $this->getHookRunner()->onSpecialSearchResultsAppend( $this, $out, $term );
600 }
601
608 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
609 // show direct page/create link if applicable
610
611 // Check DBkey !== '' in case of fragment link only.
612 if ( $title === null || $title->getDBkey() === ''
613 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
614 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
615 ) {
616 // invalid title
617 // preserve the paragraph for margins etc...
618 $this->getOutput()->addHTML( '<p></p>' );
619
620 return;
621 }
622
623 $messageName = 'searchmenu-new-nocreate';
624 $linkClass = 'mw-search-createlink';
625
626 if ( !$title->isExternal() ) {
627 if ( $title->isKnown() ) {
628 $messageName = 'searchmenu-exists';
629 $linkClass = 'mw-search-exists';
630 } elseif (
631 $this->contentHandlerFactory->getContentHandler( $title->getContentModel() )
632 ->supportsDirectEditing()
633 && $this->getAuthority()->probablyCan( 'edit', $title )
634 ) {
635 $messageName = 'searchmenu-new';
636 }
637 }
638
639 $params = [
640 $messageName,
641 wfEscapeWikiText( $title->getPrefixedText() ),
642 Message::numParam( $num )
643 ];
644 $this->getHookRunner()->onSpecialSearchCreateLink( $title, $params );
645
646 // Extensions using the hook might still return an empty $messageName
647 // @phan-suppress-next-line PhanRedundantCondition Set by hook
648 if ( $messageName ) {
649 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
650 } else {
651 // preserve the paragraph for margins etc...
652 $this->getOutput()->addHTML( '<p></p>' );
653 }
654 }
655
662 protected function setupPage( $term ) {
663 $out = $this->getOutput();
664
665 $this->setHeaders();
666 $this->outputHeader();
667 // TODO: Is this true? The namespace remember uses a user token
668 // on save.
669 $out->getMetadata()->setPreventClickjacking( false );
670 $this->addHelpLink( 'Help:Searching' );
671
672 if ( strval( $term ) !== '' ) {
673 $out->setPageTitleMsg( $this->msg( 'searchresults' ) );
674 $out->setHTMLTitle( $this->msg( 'pagetitle' )
675 ->plaintextParams( $this->msg( 'searchresults-title' )->plaintextParams( $term )->text() )
676 ->inContentLanguage()->text()
677 );
678 }
679
680 if ( $this->mPrefix !== '' ) {
681 $subtitle = $this->msg( 'search-filter-title-prefix' )->plaintextParams( $this->mPrefix );
682 $params = $this->powerSearchOptions();
683 unset( $params['prefix'] );
684 $params += [
685 'search' => $term,
686 'fulltext' => 1,
687 ];
688
689 $subtitle .= ' (';
690 $subtitle .= Xml::element(
691 'a',
692 [
693 'href' => $this->getPageTitle()->getLocalURL( $params ),
694 'title' => $this->msg( 'search-filter-title-prefix-reset' )->text(),
695 ],
696 $this->msg( 'search-filter-title-prefix-reset' )->text()
697 );
698 $subtitle .= ')';
699 $out->setSubtitle( $subtitle );
700 }
701
702 $out->addJsConfigVars( [ 'searchTerm' => $term ] );
703 $out->addModules( 'mediawiki.special.search' );
704 $out->addModuleStyles( [
705 'mediawiki.special', 'mediawiki.special.search.styles',
706 'mediawiki.widgets.SearchInputWidget.styles',
707 ] );
708 }
709
715 protected function isPowerSearch() {
716 return $this->profile === 'advanced';
717 }
718
726 protected function powerSearch( &$request ) {
727 $arr = [];
728 foreach ( $this->searchConfig->searchableNamespaces() as $ns => $name ) {
729 if ( $request->getCheck( 'ns' . $ns ) ) {
730 $arr[] = $ns;
731 }
732 }
733
734 return $arr;
735 }
736
744 public function powerSearchOptions() {
745 $opt = [];
746 if ( $this->isPowerSearch() ) {
747 foreach ( $this->namespaces as $n ) {
748 $opt['ns' . $n] = 1;
749 }
750 } else {
751 $opt['profile'] = $this->profile;
752 }
753
754 return $opt + $this->extraParams;
755 }
756
762 protected function saveNamespaces() {
763 $user = $this->getUser();
764 $request = $this->getRequest();
765
766 if ( $user->isRegistered() &&
767 $user->matchEditToken(
768 $request->getVal( 'nsRemember' ),
769 'searchnamespace',
770 $request
771 ) && !$this->readOnlyMode->isReadOnly()
772 ) {
773 // Reset namespace preferences: namespaces are not searched
774 // when they're not mentioned in the URL parameters.
775 foreach ( $this->nsInfo->getValidNamespaces() as $n ) {
776 $this->userOptionsManager->setOption( $user, 'searchNs' . $n, false );
777 }
778 // The request parameters include all the namespaces to be searched.
779 // Even if they're the same as an existing profile, they're not eaten.
780 foreach ( $this->namespaces as $n ) {
781 $this->userOptionsManager->setOption( $user, 'searchNs' . $n, true );
782 }
783
784 DeferredUpdates::addCallableUpdate( static function () use ( $user ) {
785 $user->saveSettings();
786 } );
787
788 return true;
789 }
790
791 return false;
792 }
793
798 protected function getSearchProfiles() {
799 // Builds list of Search Types (profiles)
800 $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
801 $defaultNs = $this->searchConfig->defaultNamespaces();
802 $profiles = [
803 'default' => [
804 'message' => 'searchprofile-articles',
805 'tooltip' => 'searchprofile-articles-tooltip',
806 'namespaces' => $defaultNs,
807 'namespace-messages' => $this->searchConfig->namespacesAsText(
808 $defaultNs
809 ),
810 ],
811 'images' => [
812 'message' => 'searchprofile-images',
813 'tooltip' => 'searchprofile-images-tooltip',
814 'namespaces' => [ NS_FILE ],
815 ],
816 'all' => [
817 'message' => 'searchprofile-everything',
818 'tooltip' => 'searchprofile-everything-tooltip',
819 'namespaces' => $nsAllSet,
820 ],
821 'advanced' => [
822 'message' => 'searchprofile-advanced',
823 'tooltip' => 'searchprofile-advanced-tooltip',
824 'namespaces' => self::NAMESPACES_CURRENT,
825 ]
826 ];
827
828 $this->getHookRunner()->onSpecialSearchProfiles( $profiles );
829
830 foreach ( $profiles as &$data ) {
831 if ( !is_array( $data['namespaces'] ) ) {
832 continue;
833 }
834 sort( $data['namespaces'] );
835 }
836
837 return $profiles;
838 }
839
845 public function getSearchEngine() {
846 if ( $this->searchEngine === null ) {
847 $this->searchEngine = $this->searchEngineFactory->create( $this->searchEngineType );
848 }
849
850 return $this->searchEngine;
851 }
852
857 public function getProfile() {
858 return $this->profile;
859 }
860
865 public function getNamespaces() {
866 return $this->namespaces;
867 }
868
878 public function setExtraParam( $key, $value ) {
879 $this->extraParams[$key] = $value;
880 }
881
890 public function getPrefix() {
891 return $this->mPrefix;
892 }
893
901 private function prevNextLinks(
902 ?int $totalRes,
903 ?ISearchResultSet $textMatches,
904 string $term,
905 string $class,
906 OutputPage $out
907 ) {
908 if ( $totalRes > $this->limit || $this->offset ) {
909 // Allow matches to define the correct offset, as interleaved
910 // AB testing may require a different next page offset.
911 if ( $textMatches && $textMatches->getOffset() !== null ) {
912 $offset = $textMatches->getOffset();
913 } else {
915 }
916
917 // use the rewritten search term for subsequent page searches
918 $newSearchTerm = $term;
919 if ( $textMatches && $textMatches->hasRewrittenQuery() ) {
920 $newSearchTerm = $textMatches->getQueryAfterRewrite();
921 }
922
923 $prevNext =
924 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable offset is not null
925 $this->buildPrevNextNavigation( $offset, $this->limit,
926 $this->powerSearchOptions() + [ 'search' => $newSearchTerm ],
927 $this->limit + $this->offset >= $totalRes );
928 $out->addHTML( "<div class='{$class}'>{$prevNext}</div>\n" );
929 }
930 }
931
932 protected function getGroupName() {
933 return 'pages';
934 }
935}
936
941class_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.