MediaWiki  master
SpecialSearch.php
Go to the documentation of this file.
1 <?php
26 namespace MediaWiki\Specials;
27 
28 use DeferredUpdates;
50 use Message;
51 use RepoGroup;
52 use SearchEngine;
56 use Xml;
57 
62 class SpecialSearch extends SpecialPage {
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 
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  $defaultOptions = $this->userOptionsManager->getDefaultOptions();
390  return $defaultOptions['search-match-redirect'];
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  $this,
409  $this->searchConfig,
410  $this->getHookContainer(),
411  $this->languageConverterFactory->getLanguageConverter( $this->getLanguage() ),
412  $this->nsInfo,
413  $this->getSearchProfiles()
414  );
415  $filePrefix = $this->getContentLanguage()->getFormattedNsText( NS_FILE ) . ':';
416  if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
417  // Empty query -- straight view of search form
418  if ( !$this->getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
419  # Hook requested termination
420  return;
421  }
422  $out->enableOOUI();
423  // The form also contains the 'Showing results 0 - 20 of 1234' so we can
424  // only do the form render here for the empty $term case. Rendering
425  // the form when a search is provided is repeated below.
426  $out->addHTML( $formWidget->render(
427  $this->profile, $term, 0, 0, $this->offset, $this->isPowerSearch(), $widgetOptions
428  ) );
429  return;
430  }
431 
432  $engine = $this->getSearchEngine();
433  $engine->setFeatureData( 'rewrite', $this->runSuggestion );
434  $engine->setLimitOffset( $this->limit, $this->offset );
435  $engine->setNamespaces( $this->namespaces );
436  $engine->setSort( $this->sort );
437  $engine->prefix = $this->mPrefix;
438 
439  $this->getHookRunner()->onSpecialSearchSetupEngine( $this, $this->profile, $engine );
440  if ( !$this->getHookRunner()->onSpecialSearchResultsPrepend( $this, $out, $term ) ) {
441  # Hook requested termination
442  return;
443  }
444 
445  $title = Title::newFromText( $term );
446  $languageConverter = $this->languageConverterFactory->getLanguageConverter( $this->getContentLanguage() );
447  if ( $languageConverter->hasVariants() ) {
448  // findVariantLink will replace the link arg as well but we want to keep our original
449  // search string, use a copy in the $variantTerm var so that $term remains intact.
450  $variantTerm = $term;
451  $languageConverter->findVariantLink( $variantTerm, $title );
452  }
453 
454  $showSuggestion = $title === null || !$title->isKnown();
455  $engine->setShowSuggestion( $showSuggestion );
456 
457  $rewritten = $engine->replacePrefixes( $term );
458  if ( $rewritten !== $term ) {
459  wfDeprecatedMsg( 'SearchEngine::replacePrefixes() was overridden by ' .
460  get_class( $engine ) . ', this is deprecated since MediaWiki 1.32',
461  '1.32', false, false );
462  }
463 
464  // fetch search results
465  $titleMatches = $engine->searchTitle( $rewritten );
466  $textMatches = $engine->searchText( $rewritten );
467 
468  $textStatus = null;
469  if ( $textMatches instanceof Status ) {
470  $textStatus = $textMatches;
471  $textMatches = $textStatus->getValue();
472  }
473 
474  // Get number of results
475  $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
476  if ( $titleMatches ) {
477  $titleMatchesNum = $titleMatches->numRows();
478  $numTitleMatches = $titleMatches->getTotalHits();
479  }
480  if ( $textMatches ) {
481  $textMatchesNum = $textMatches->numRows();
482  $numTextMatches = $textMatches->getTotalHits();
483  if ( $textMatchesNum > 0 ) {
484  $engine->augmentSearchResults( $textMatches );
485  }
486  }
487  $num = $titleMatchesNum + $textMatchesNum;
488  $totalRes = $numTitleMatches + $numTextMatches;
489 
490  // start rendering the page
491  $out->enableOOUI();
492  $out->addHTML( $formWidget->render(
493  $this->profile, $term, $num, $totalRes, $this->offset, $this->isPowerSearch(), $widgetOptions
494  ) );
495 
496  // did you mean... suggestions
497  if ( $textMatches ) {
498  $dymWidget = new DidYouMeanWidget( $this );
499  $out->addHTML( $dymWidget->render( $term, $textMatches ) );
500  }
501 
502  $hasSearchErrors = $textStatus && $textStatus->getErrors() !== [];
503  $hasInlineIwResults = $textMatches &&
505  $hasSecondaryIwResults = $textMatches &&
507 
508  $classNames = [ 'searchresults' ];
509  if ( $hasSecondaryIwResults ) {
510  $classNames[] = 'mw-searchresults-has-iw';
511  }
512  if ( $this->offset > 0 ) {
513  $classNames[] = 'mw-searchresults-has-offset';
514  }
515  $out->addHTML( '<div class="' . implode( ' ', $classNames ) . '">' );
516 
517  $out->addHTML( '<div class="mw-search-results-info">' );
518 
519  if ( $hasSearchErrors || $this->loadStatus->getErrors() ) {
520  if ( $textStatus === null ) {
521  $textStatus = $this->loadStatus;
522  } else {
523  $textStatus->merge( $this->loadStatus );
524  }
525  [ $error, $warning ] = $textStatus->splitByErrorType();
526  if ( $error->getErrors() ) {
527  $out->addHTML( Html::errorBox(
528  $error->getHTML( 'search-error' )
529  ) );
530  }
531  if ( $warning->getErrors() ) {
532  $out->addHTML( Html::warningBox(
533  $warning->getHTML( 'search-warning' )
534  ) );
535  }
536  }
537 
538  // If we have no results and have not already displayed an error message
539  if ( $num === 0 && !$hasSearchErrors ) {
540  $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", [
541  $hasInlineIwResults ? 'search-nonefound-thiswiki' : 'search-nonefound',
542  wfEscapeWikiText( $term ),
543  $term
544  ] );
545  }
546 
547  // Show the create link ahead
548  $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
549 
550  $this->getHookRunner()->onSpecialSearchResults( $term, $titleMatches, $textMatches );
551 
552  // Close <div class='mw-search-results-info'>
553  $out->addHTML( '</div>' );
554 
555  // Although $num might be 0 there can still be secondary or inline
556  // results to display.
557  $linkRenderer = $this->getLinkRenderer();
558  $mainResultWidget = new FullSearchResultWidget(
559  $this,
560  $linkRenderer,
561  $this->getHookContainer(),
562  $this->repoGroup,
563  $this->thumbnailProvider,
564  $this->userOptionsManager
565  );
566 
567  $sidebarResultWidget = new InterwikiSearchResultWidget( $this, $linkRenderer );
568  $sidebarResultsWidget = new InterwikiSearchResultSetWidget(
569  $this,
570  $sidebarResultWidget,
571  $linkRenderer,
572  $this->interwikiLookup,
573  $engine->getFeatureData( 'show-multimedia-search-results' )
574  );
575 
576  $widget = new BasicSearchResultSetWidget( $this, $mainResultWidget, $sidebarResultsWidget );
577 
578  $out->addHTML( '<div class="mw-search-visualclear"></div>' );
579  $this->prevNextLinks( $totalRes, $textMatches, $term, 'mw-search-pager-top', $out );
580 
581  $out->addHTML( $widget->render(
582  $term, $this->offset, $titleMatches, $textMatches
583  ) );
584 
585  $out->addHTML( '<div class="mw-search-visualclear"></div>' );
586  $this->prevNextLinks( $totalRes, $textMatches, $term, 'mw-search-pager-bottom', $out );
587 
588  // Close <div class='searchresults'>
589  $out->addHTML( "</div>" );
590 
591  $this->getHookRunner()->onSpecialSearchResultsAppend( $this, $out, $term );
592  }
593 
600  protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
601  // show direct page/create link if applicable
602 
603  // Check DBkey !== '' in case of fragment link only.
604  if ( $title === null || $title->getDBkey() === ''
605  || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
606  || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
607  ) {
608  // invalid title
609  // preserve the paragraph for margins etc...
610  $this->getOutput()->addHTML( '<p></p>' );
611 
612  return;
613  }
614 
615  $messageName = 'searchmenu-new-nocreate';
616  $linkClass = 'mw-search-createlink';
617 
618  if ( !$title->isExternal() ) {
619  if ( $title->isKnown() ) {
620  $messageName = 'searchmenu-exists';
621  $linkClass = 'mw-search-exists';
622  } elseif (
623  $this->contentHandlerFactory->getContentHandler( $title->getContentModel() )
624  ->supportsDirectEditing()
625  && $this->getAuthority()->probablyCan( 'edit', $title )
626  ) {
627  $messageName = 'searchmenu-new';
628  }
629  }
630 
631  $params = [
632  $messageName,
633  wfEscapeWikiText( $title->getPrefixedText() ),
634  Message::numParam( $num )
635  ];
636  $this->getHookRunner()->onSpecialSearchCreateLink( $title, $params );
637 
638  // Extensions using the hook might still return an empty $messageName
639  // @phan-suppress-next-line PhanRedundantCondition Set by hook
640  if ( $messageName ) {
641  $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
642  } else {
643  // preserve the paragraph for margins etc...
644  $this->getOutput()->addHTML( '<p></p>' );
645  }
646  }
647 
654  protected function setupPage( $term ) {
655  $out = $this->getOutput();
656 
657  $this->setHeaders();
658  $this->outputHeader();
659  // TODO: Is this true? The namespace remember uses a user token
660  // on save.
661  $out->setPreventClickjacking( false );
662  $this->addHelpLink( 'Help:Searching' );
663 
664  if ( strval( $term ) !== '' ) {
665  $out->setPageTitleMsg( $this->msg( 'searchresults' ) );
666  $out->setHTMLTitle( $this->msg( 'pagetitle' )
667  ->plaintextParams( $this->msg( 'searchresults-title' )->plaintextParams( $term )->text() )
668  ->inContentLanguage()->text()
669  );
670  }
671 
672  if ( $this->mPrefix !== '' ) {
673  $subtitle = $this->msg( 'search-filter-title-prefix' )->plaintextParams( $this->mPrefix );
674  $params = $this->powerSearchOptions();
675  unset( $params['prefix'] );
676  $params += [
677  'search' => $term,
678  'fulltext' => 1,
679  ];
680 
681  $subtitle .= ' (';
682  $subtitle .= Xml::element(
683  'a',
684  [
685  'href' => $this->getPageTitle()->getLocalURL( $params ),
686  'title' => $this->msg( 'search-filter-title-prefix-reset' )->text(),
687  ],
688  $this->msg( 'search-filter-title-prefix-reset' )->text()
689  );
690  $subtitle .= ')';
691  $out->setSubtitle( $subtitle );
692  }
693 
694  $out->addJsConfigVars( [ 'searchTerm' => $term ] );
695  $out->addModules( 'mediawiki.special.search' );
696  $out->addModuleStyles( [
697  'mediawiki.special', 'mediawiki.special.search.styles',
698  'mediawiki.widgets.SearchInputWidget.styles',
699  ] );
700  }
701 
707  protected function isPowerSearch() {
708  return $this->profile === 'advanced';
709  }
710 
718  protected function powerSearch( &$request ) {
719  $arr = [];
720  foreach ( $this->searchConfig->searchableNamespaces() as $ns => $name ) {
721  if ( $request->getCheck( 'ns' . $ns ) ) {
722  $arr[] = $ns;
723  }
724  }
725 
726  return $arr;
727  }
728 
736  public function powerSearchOptions() {
737  $opt = [];
738  if ( $this->isPowerSearch() ) {
739  foreach ( $this->namespaces as $n ) {
740  $opt['ns' . $n] = 1;
741  }
742  } else {
743  $opt['profile'] = $this->profile;
744  }
745 
746  return $opt + $this->extraParams;
747  }
748 
754  protected function saveNamespaces() {
755  $user = $this->getUser();
756  $request = $this->getRequest();
757 
758  if ( $user->isRegistered() &&
759  $user->matchEditToken(
760  $request->getVal( 'nsRemember' ),
761  'searchnamespace',
762  $request
763  ) && !$this->readOnlyMode->isReadOnly()
764  ) {
765  // Reset namespace preferences: namespaces are not searched
766  // when they're not mentioned in the URL parameters.
767  foreach ( $this->nsInfo->getValidNamespaces() as $n ) {
768  $this->userOptionsManager->setOption( $user, 'searchNs' . $n, false );
769  }
770  // The request parameters include all the namespaces to be searched.
771  // Even if they're the same as an existing profile, they're not eaten.
772  foreach ( $this->namespaces as $n ) {
773  $this->userOptionsManager->setOption( $user, 'searchNs' . $n, true );
774  }
775 
776  DeferredUpdates::addCallableUpdate( static function () use ( $user ) {
777  $user->saveSettings();
778  } );
779 
780  return true;
781  }
782 
783  return false;
784  }
785 
790  protected function getSearchProfiles() {
791  // Builds list of Search Types (profiles)
792  $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
793  $defaultNs = $this->searchConfig->defaultNamespaces();
794  $profiles = [
795  'default' => [
796  'message' => 'searchprofile-articles',
797  'tooltip' => 'searchprofile-articles-tooltip',
798  'namespaces' => $defaultNs,
799  'namespace-messages' => $this->searchConfig->namespacesAsText(
800  $defaultNs
801  ),
802  ],
803  'images' => [
804  'message' => 'searchprofile-images',
805  'tooltip' => 'searchprofile-images-tooltip',
806  'namespaces' => [ NS_FILE ],
807  ],
808  'all' => [
809  'message' => 'searchprofile-everything',
810  'tooltip' => 'searchprofile-everything-tooltip',
811  'namespaces' => $nsAllSet,
812  ],
813  'advanced' => [
814  'message' => 'searchprofile-advanced',
815  'tooltip' => 'searchprofile-advanced-tooltip',
816  'namespaces' => self::NAMESPACES_CURRENT,
817  ]
818  ];
819 
820  $this->getHookRunner()->onSpecialSearchProfiles( $profiles );
821 
822  foreach ( $profiles as &$data ) {
823  if ( !is_array( $data['namespaces'] ) ) {
824  continue;
825  }
826  sort( $data['namespaces'] );
827  }
828 
829  return $profiles;
830  }
831 
837  public function getSearchEngine() {
838  if ( $this->searchEngine === null ) {
839  $this->searchEngine = $this->searchEngineFactory->create( $this->searchEngineType );
840  }
841 
842  return $this->searchEngine;
843  }
844 
849  public function getProfile() {
850  return $this->profile;
851  }
852 
857  public function getNamespaces() {
858  return $this->namespaces;
859  }
860 
870  public function setExtraParam( $key, $value ) {
871  $this->extraParams[$key] = $value;
872  }
873 
882  public function getPrefix() {
883  return $this->mPrefix;
884  }
885 
893  private function prevNextLinks(
894  ?int $totalRes,
895  ?ISearchResultSet $textMatches,
896  string $term,
897  string $class,
898  OutputPage $out
899  ) {
900  if ( $totalRes > $this->limit || $this->offset ) {
901  // Allow matches to define the correct offset, as interleaved
902  // AB testing may require a different next page offset.
903  if ( $textMatches && $textMatches->getOffset() !== null ) {
904  $offset = $textMatches->getOffset();
905  } else {
907  }
908 
909  // use the rewritten search term for subsequent page searches
910  $newSearchTerm = $term;
911  if ( $textMatches && $textMatches->hasRewrittenQuery() ) {
912  $newSearchTerm = $textMatches->getQueryAfterRewrite();
913  }
914 
915  $prevNext =
916  // @phan-suppress-next-line PhanTypeMismatchArgumentNullable offset is not null
917  $this->buildPrevNextNavigation( $offset, $this->limit,
918  $this->powerSearchOptions() + [ 'search' => $newSearchTerm ],
919  $this->limit + $this->offset >= $totalRes );
920  $out->addHTML( "<div class='{$class}'>{$prevNext}</div>\n" );
921  }
922  }
923 
924  protected function getGroupName() {
925  return 'pages';
926  }
927 }
928 
933 class_alias( SpecialSearch::class, 'SpecialSearch' );
const NS_FILE
Definition: Defines.php:70
const NS_MAIN
Definition: Defines.php:64
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Defer callable updates to run later in the PHP process.
static addCallableUpdate( $callable, $stage=self::POSTSEND, $dbw=null)
Add an update to the pending update queue that invokes the specified callback when run.
This class is a collection of static functions that serve two purposes:
Definition: Html.php:57
static warningBox( $html, $className='')
Return a warning box.
Definition: Html.php:823
static errorBox( $html, $heading='', $className='')
Return an error box.
Definition: Html.php:838
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()
This is one of the Core classes and should be read at least once by any new developers.
Definition: OutputPage.php:93
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.
Definition: OutputPage.php:662
redirect( $url, $responsecode='302')
Redirect to $url rather than displaying the normal page.
Definition: OutputPage.php:465
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.
Definition: OutputPage.php:688
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:50
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.
Definition: SpecialPage.php:65
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:58
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:76
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:400
A service class to control user options.
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition: Message.php:144
static numParam( $num)
Definition: Message.php:1154
Prioritized list of file repositories.
Definition: RepoGroup.php:30
Configuration handling class for SearchEngine.
Factory class for SearchEngine.
Contain a class for special pages.
const DEFAULT_SORT
Determine whether a site is currently in read-only mode.
Module of static functions for generating XML.
Definition: Xml.php:33
static element( $element, $attribs=null, $contents='', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition: Xml.php:50
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.
const INLINE_RESULTS
Identifier for interwiki results that can be displayed even if no existing main wiki results exist.
const SECONDARY_RESULTS
Identifier for interwiki results that are displayed only together with existing main wiki results.
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.