MediaWiki  1.28.1
SpecialSearch.php
Go to the documentation of this file.
1 <?php
27 
32 class SpecialSearch extends SpecialPage {
41  protected $profile;
42 
44  protected $searchEngine;
45 
47  protected $searchEngineType;
48 
50  protected $extraParams = [];
51 
56  protected $mPrefix;
57 
61  protected $limit, $offset;
62 
66  protected $namespaces;
67 
71  protected $fulltext;
72 
76  protected $runSuggestion = true;
77 
82  protected $customCaptions;
83 
88  protected $searchConfig;
89 
90  const NAMESPACES_CURRENT = 'sense';
91 
92  public function __construct() {
93  parent::__construct( 'Search' );
94  $this->searchConfig = MediaWikiServices::getInstance()->getSearchEngineConfig();
95  }
96 
102  public function execute( $par ) {
103  $request = $this->getRequest();
104 
105  // Fetch the search term
106  $search = str_replace( "\n", " ", $request->getText( 'search' ) );
107 
108  // Historically search terms have been accepted not only in the search query
109  // parameter, but also as part of the primary url. This can have PII implications
110  // in releasing page view data. As such issue a 301 redirect to the correct
111  // URL.
112  if ( strlen( $par ) && !strlen( $search ) ) {
113  $query = $request->getValues();
114  unset( $query['title'] );
115  // Strip underscores from title parameter; most of the time we'll want
116  // text form here. But don't strip underscores from actual text params!
117  $query['search'] = str_replace( '_', ' ', $par );
118  $this->getOutput()->redirect( $this->getPageTitle()->getFullURL( $query ), 301 );
119  return;
120  }
121 
122  $this->setHeaders();
123  $this->outputHeader();
124  $out = $this->getOutput();
125  $out->allowClickjacking();
126  $out->addModuleStyles( [
127  'mediawiki.special', 'mediawiki.special.search.styles', 'mediawiki.ui', 'mediawiki.ui.button',
128  'mediawiki.ui.input', 'mediawiki.widgets.SearchInputWidget.styles',
129  ] );
130  $this->addHelpLink( 'Help:Searching' );
131 
132  $this->load();
133  if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
134  $this->saveNamespaces();
135  // Remove the token from the URL to prevent the user from inadvertently
136  // exposing it (e.g. by pasting it into a public wiki page) or undoing
137  // later settings changes (e.g. by reloading the page).
138  $query = $request->getValues();
139  unset( $query['title'], $query['nsRemember'] );
140  $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
141  return;
142  }
143 
144  $out->addJsConfigVars( [ 'searchTerm' => $search ] );
145  $this->searchEngineType = $request->getVal( 'srbackend' );
146 
147  if ( $request->getVal( 'fulltext' )
148  || !is_null( $request->getVal( 'offset' ) )
149  ) {
150  $this->showResults( $search );
151  } else {
152  $this->goResult( $search );
153  }
154  }
155 
161  public function load() {
162  $request = $this->getRequest();
163  list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, '' );
164  $this->mPrefix = $request->getVal( 'prefix', '' );
165 
166  $user = $this->getUser();
167 
168  # Extract manually requested namespaces
169  $nslist = $this->powerSearch( $request );
170  if ( !count( $nslist ) ) {
171  # Fallback to user preference
172  $nslist = $this->searchConfig->userNamespaces( $user );
173  }
174 
175  $profile = null;
176  if ( !count( $nslist ) ) {
177  $profile = 'default';
178  }
179 
180  $profile = $request->getVal( 'profile', $profile );
181  $profiles = $this->getSearchProfiles();
182  if ( $profile === null ) {
183  // BC with old request format
184  $profile = 'advanced';
185  foreach ( $profiles as $key => $data ) {
186  if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
187  $profile = $key;
188  }
189  }
190  $this->namespaces = $nslist;
191  } elseif ( $profile === 'advanced' ) {
192  $this->namespaces = $nslist;
193  } else {
194  if ( isset( $profiles[$profile]['namespaces'] ) ) {
195  $this->namespaces = $profiles[$profile]['namespaces'];
196  } else {
197  // Unknown profile requested
198  $profile = 'default';
199  $this->namespaces = $profiles['default']['namespaces'];
200  }
201  }
202 
203  $this->fulltext = $request->getVal( 'fulltext' );
204  $this->runSuggestion = (bool)$request->getVal( 'runsuggestion', true );
205  $this->profile = $profile;
206  }
207 
213  public function goResult( $term ) {
214  $this->setupPage( $term );
215  # Try to go to page as entered.
217  # If the string cannot be used to create a title
218  if ( is_null( $title ) ) {
219  $this->showResults( $term );
220 
221  return;
222  }
223  # If there's an exact or very near match, jump right there.
224  $title = $this->getSearchEngine()
225  ->getNearMatcher( $this->getConfig() )->getNearMatch( $term );
226 
227  if ( !is_null( $title ) &&
228  Hooks::run( 'SpecialSearchGoResult', [ $term, $title, &$url ] )
229  ) {
230  if ( $url === null ) {
231  $url = $title->getFullUrlForRedirect();
232  }
233  $this->getOutput()->redirect( $url );
234 
235  return;
236  }
237  # No match, generate an edit URL
239  if ( !is_null( $title ) ) {
240  Hooks::run( 'SpecialSearchNogomatch', [ &$title ] );
241  }
242  $this->showResults( $term );
243  }
244 
248  public function showResults( $term ) {
250 
251  $search = $this->getSearchEngine();
252  $search->setFeatureData( 'rewrite', $this->runSuggestion );
253  $search->setLimitOffset( $this->limit, $this->offset );
254  $search->setNamespaces( $this->namespaces );
255  $search->prefix = $this->mPrefix;
256  $term = $search->transformSearchTerm( $term );
257 
258  Hooks::run( 'SpecialSearchSetupEngine', [ $this, $this->profile, $search ] );
259 
260  $this->setupPage( $term );
261 
262  $out = $this->getOutput();
263 
264  if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
265  $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
266  if ( $searchFowardUrl ) {
267  $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
268  $out->redirect( $url );
269  } else {
270  $out->addHTML(
271  Xml::openElement( 'fieldset' ) .
272  Xml::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
273  Xml::element(
274  'p',
275  [ 'class' => 'mw-searchdisabled' ],
276  $this->msg( 'searchdisabled' )->text()
277  ) .
278  $this->msg( 'googlesearch' )->rawParams(
279  htmlspecialchars( $term ),
280  'UTF-8',
281  $this->msg( 'searchbutton' )->escaped()
282  )->text() .
283  Xml::closeElement( 'fieldset' )
284  );
285  }
286 
287  return;
288  }
289 
291  $showSuggestion = $title === null || !$title->isKnown();
292  $search->setShowSuggestion( $showSuggestion );
293 
294  // fetch search results
295  $rewritten = $search->replacePrefixes( $term );
296 
297  $titleMatches = $search->searchTitle( $rewritten );
298  $textMatches = $search->searchText( $rewritten );
299 
300  $textStatus = null;
301  if ( $textMatches instanceof Status ) {
302  $textStatus = $textMatches;
303  $textMatches = null;
304  }
305 
306  // did you mean... suggestions
307  $didYouMeanHtml = '';
308  if ( $showSuggestion && $textMatches && !$textStatus ) {
309  if ( $textMatches->hasRewrittenQuery() ) {
310  $didYouMeanHtml = $this->getDidYouMeanRewrittenHtml( $term, $textMatches );
311  } elseif ( $textMatches->hasSuggestion() ) {
312  $didYouMeanHtml = $this->getDidYouMeanHtml( $textMatches );
313  }
314  }
315 
316  if ( !Hooks::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
317  # Hook requested termination
318  return;
319  }
320 
321  // start rendering the page
322  $out->addHTML(
324  'form',
325  [
326  'id' => ( $this->isPowerSearch() ? 'powersearch' : 'search' ),
327  'method' => 'get',
328  'action' => wfScript(),
329  ]
330  )
331  );
332 
333  // Get number of results
334  $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
335  if ( $titleMatches ) {
336  $titleMatchesNum = $titleMatches->numRows();
337  $numTitleMatches = $titleMatches->getTotalHits();
338  }
339  if ( $textMatches ) {
340  $textMatchesNum = $textMatches->numRows();
341  $numTextMatches = $textMatches->getTotalHits();
342  }
343  $num = $titleMatchesNum + $textMatchesNum;
344  $totalRes = $numTitleMatches + $numTextMatches;
345 
346  $out->enableOOUI();
347  $out->addHTML(
348  # This is an awful awful ID name. It's not a table, but we
349  # named it poorly from when this was a table so now we're
350  # stuck with it
351  Xml::openElement( 'div', [ 'id' => 'mw-search-top-table' ] ) .
352  $this->shortDialog( $term, $num, $totalRes ) .
353  Xml::closeElement( 'div' ) .
354  $this->searchProfileTabs( $term ) .
355  $this->searchOptions( $term ) .
356  Xml::closeElement( 'form' ) .
357  $didYouMeanHtml
358  );
359 
360  $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
361  if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
362  // Empty query -- straight view of search form
363  return;
364  }
365 
366  $out->addHTML( "<div class='searchresults'>" );
367 
368  // prev/next links
369  $prevnext = null;
370  if ( $num || $this->offset ) {
371  // Show the create link ahead
372  $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
373  if ( $totalRes > $this->limit || $this->offset ) {
374  if ( $this->searchEngineType !== null ) {
375  $this->setExtraParam( 'srbackend', $this->searchEngineType );
376  }
377  $prevnext = $this->getLanguage()->viewPrevNext(
378  $this->getPageTitle(),
379  $this->offset,
380  $this->limit,
381  $this->powerSearchOptions() + [ 'search' => $term ],
382  $this->limit + $this->offset >= $totalRes
383  );
384  }
385  }
386  Hooks::run( 'SpecialSearchResults', [ $term, &$titleMatches, &$textMatches ] );
387 
388  $out->parserOptions()->setEditSection( false );
389  if ( $titleMatches ) {
390  if ( $numTitleMatches > 0 ) {
391  $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
392  $out->addHTML( $this->showMatches( $titleMatches ) );
393  }
394  $titleMatches->free();
395  }
396  if ( $textMatches && !$textStatus ) {
397  // output appropriate heading
398  if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
399  $out->addHTML( '<div class="mw-search-visualclear"></div>' );
400  // if no title matches the heading is redundant
401  $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
402  }
403 
404  // show results
405  if ( $numTextMatches > 0 ) {
406  $search->augmentSearchResults( $textMatches );
407  $out->addHTML( $this->showMatches( $textMatches ) );
408  }
409 
410  // show secondary interwiki results if any
411  if ( $textMatches->hasInterwikiResults( SearchResultSet::SECONDARY_RESULTS ) ) {
412  $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(
413  SearchResultSet::SECONDARY_RESULTS ), $term ) );
414  }
415  }
416 
417  $hasOtherResults = $textMatches &&
418  $textMatches->hasInterwikiResults( SearchResultSet::INLINE_RESULTS );
419 
420  if ( $num === 0 ) {
421  if ( $textStatus ) {
422  $out->addHTML( '<div class="error">' .
423  $textStatus->getMessage( 'search-error' ) . '</div>' );
424  } else {
425  $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
426  $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
427  [ $hasOtherResults ? 'search-nonefound-thiswiki' : 'search-nonefound',
429  ] );
430  }
431  }
432 
433  if ( $hasOtherResults ) {
434  foreach ( $textMatches->getInterwikiResults( SearchResultSet::INLINE_RESULTS )
435  as $interwiki => $interwikiResult ) {
436  if ( $interwikiResult instanceof Status || $interwikiResult->numRows() == 0 ) {
437  // ignore bad interwikis for now
438  continue;
439  }
440  // TODO: wiki header
441  $out->addHTML( $this->showMatches( $interwikiResult, $interwiki ) );
442  }
443  }
444 
445  if ( $textMatches ) {
446  $textMatches->free();
447  }
448 
449  $out->addHTML( '<div class="mw-search-visualclear"></div>' );
450 
451  if ( $prevnext ) {
452  $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
453  }
454 
455  $out->addHTML( "</div>" );
456 
457  Hooks::run( 'SpecialSearchResultsAppend', [ $this, $out, $term ] );
458 
459  }
460 
467  protected function interwikiHeader( $interwiki, $interwikiResult ) {
468  // TODO: we need to figure out how to name wikis correctly
469  $wikiMsg = $this->msg( 'search-interwiki-results-' . $interwiki )->parse();
470  return "<p class=\"mw-search-interwiki-header mw-search-visualclear\">\n$wikiMsg</p>";
471  }
472 
480  protected function shouldRunSuggestedQuery( SearchResultSet $textMatches ) {
481  if ( !$this->runSuggestion ||
482  !$textMatches->hasSuggestion() ||
483  $textMatches->numRows() > 0 ||
484  $textMatches->searchContainedSyntax()
485  ) {
486  return false;
487  }
488 
489  return $this->getConfig()->get( 'SearchRunSuggestedQuery' );
490  }
491 
496  protected function getDidYouMeanHtml( SearchResultSet $textMatches ) {
497  # mirror Go/Search behavior of original request ..
498  $params = [ 'search' => $textMatches->getSuggestionQuery() ];
499  if ( $this->fulltext === null ) {
500  $params['fulltext'] = 'Search';
501  } else {
502  $params['fulltext'] = $this->fulltext;
503  }
504  $stParams = array_merge( $params, $this->powerSearchOptions() );
505 
506  $suggest = Linker::linkKnown(
507  $this->getPageTitle(),
508  $textMatches->getSuggestionSnippet() ?: null,
509  [ 'id' => 'mw-search-DYM-suggestion' ],
510  $stParams
511  );
512 
513  # HTML of did you mean... search suggestion link
514  return Html::rawElement(
515  'div',
516  [ 'class' => 'searchdidyoumean' ],
517  $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
518  );
519  }
520 
530  protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet $textMatches ) {
531  // Showing results for '$rewritten'
532  // Search instead for '$orig'
533 
534  $params = [ 'search' => $textMatches->getQueryAfterRewrite() ];
535  if ( $this->fulltext === null ) {
536  $params['fulltext'] = 'Search';
537  } else {
538  $params['fulltext'] = $this->fulltext;
539  }
540  $stParams = array_merge( $params, $this->powerSearchOptions() );
541 
542  $rewritten = Linker::linkKnown(
543  $this->getPageTitle(),
544  $textMatches->getQueryAfterRewriteSnippet() ?: null,
545  [ 'id' => 'mw-search-DYM-rewritten' ],
546  $stParams
547  );
548 
549  $stParams['search'] = $term;
550  $stParams['runsuggestion'] = 0;
551  $original = Linker::linkKnown(
552  $this->getPageTitle(),
553  htmlspecialchars( $term ),
554  [ 'id' => 'mw-search-DYM-original' ],
555  $stParams
556  );
557 
558  return Html::rawElement(
559  'div',
560  [ 'class' => 'searchdidyoumean' ],
561  $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
562  );
563  }
564 
571  protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
572  // show direct page/create link if applicable
573 
574  // Check DBkey !== '' in case of fragment link only.
575  if ( is_null( $title ) || $title->getDBkey() === ''
576  || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
577  || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
578  ) {
579  // invalid title
580  // preserve the paragraph for margins etc...
581  $this->getOutput()->addHTML( '<p></p>' );
582 
583  return;
584  }
585 
586  $messageName = 'searchmenu-new-nocreate';
587  $linkClass = 'mw-search-createlink';
588 
589  if ( !$title->isExternal() ) {
590  if ( $title->isKnown() ) {
591  $messageName = 'searchmenu-exists';
592  $linkClass = 'mw-search-exists';
593  } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
594  $messageName = 'searchmenu-new';
595  }
596  }
597 
598  $params = [
599  $messageName,
600  wfEscapeWikiText( $title->getPrefixedText() ),
601  Message::numParam( $num )
602  ];
603  Hooks::run( 'SpecialSearchCreateLink', [ $title, &$params ] );
604 
605  // Extensions using the hook might still return an empty $messageName
606  if ( $messageName ) {
607  $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
608  } else {
609  // preserve the paragraph for margins etc...
610  $this->getOutput()->addHTML( '<p></p>' );
611  }
612  }
613 
617  protected function setupPage( $term ) {
618  $out = $this->getOutput();
619  if ( strval( $term ) !== '' ) {
620  $out->setPageTitle( $this->msg( 'searchresults' ) );
621  $out->setHTMLTitle( $this->msg( 'pagetitle' )
622  ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
623  ->inContentLanguage()->text()
624  );
625  }
626  // add javascript specific to special:search
627  $out->addModules( 'mediawiki.special.search' );
628  }
629 
635  protected function isPowerSearch() {
636  return $this->profile === 'advanced';
637  }
638 
646  protected function powerSearch( &$request ) {
647  $arr = [];
648  foreach ( $this->searchConfig->searchableNamespaces() as $ns => $name ) {
649  if ( $request->getCheck( 'ns' . $ns ) ) {
650  $arr[] = $ns;
651  }
652  }
653 
654  return $arr;
655  }
656 
662  protected function powerSearchOptions() {
663  $opt = [];
664  if ( !$this->isPowerSearch() ) {
665  $opt['profile'] = $this->profile;
666  } else {
667  foreach ( $this->namespaces as $n ) {
668  $opt['ns' . $n] = 1;
669  }
670  }
671 
672  return $opt + $this->extraParams;
673  }
674 
680  protected function saveNamespaces() {
681  $user = $this->getUser();
682  $request = $this->getRequest();
683 
684  if ( $user->isLoggedIn() &&
685  $user->matchEditToken(
686  $request->getVal( 'nsRemember' ),
687  'searchnamespace',
688  $request
689  ) && !wfReadOnly()
690  ) {
691  // Reset namespace preferences: namespaces are not searched
692  // when they're not mentioned in the URL parameters.
693  foreach ( MWNamespace::getValidNamespaces() as $n ) {
694  $user->setOption( 'searchNs' . $n, false );
695  }
696  // The request parameters include all the namespaces to be searched.
697  // Even if they're the same as an existing profile, they're not eaten.
698  foreach ( $this->namespaces as $n ) {
699  $user->setOption( 'searchNs' . $n, true );
700  }
701 
702  DeferredUpdates::addCallableUpdate( function () use ( $user ) {
703  $user->saveSettings();
704  } );
705 
706  return true;
707  }
708 
709  return false;
710  }
711 
720  protected function showMatches( $matches, $interwiki = null ) {
722 
723  $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
724  $out = '';
725  $result = $matches->next();
726  $pos = $this->offset;
727 
728  if ( $result && $interwiki ) {
729  $out .= $this->interwikiHeader( $interwiki, $matches );
730  }
731 
732  $out .= "<ul class='mw-search-results'>\n";
733  while ( $result ) {
734  $out .= $this->showHit( $result, $terms, $pos++ );
735  $result = $matches->next();
736  }
737  $out .= "</ul>\n";
738 
739  // convert the whole thing to desired language variant
740  $out = $wgContLang->convert( $out );
741 
742  return $out;
743  }
744 
754  protected function showHit( SearchResult $result, $terms, $position ) {
755 
756  if ( $result->isBrokenTitle() ) {
757  return '';
758  }
759 
760  $title = $result->getTitle();
761 
762  $titleSnippet = $result->getTitleSnippet();
763 
764  if ( $titleSnippet == '' ) {
765  $titleSnippet = null;
766  }
767 
768  $link_t = clone $title;
769  $query = [];
770 
771  Hooks::run( 'ShowSearchHitTitle',
772  [ &$link_t, &$titleSnippet, $result, $terms, $this, &$query ] );
773 
775  $link_t,
776  $titleSnippet,
777  [ 'data-serp-pos' => $position ], // HTML attributes
778  $query
779  );
780 
781  // If page content is not readable, just return the title.
782  // This is not quite safe, but better than showing excerpts from non-readable pages
783  // Note that hiding the entry entirely would screw up paging.
784  if ( !$title->userCan( 'read', $this->getUser() ) ) {
785  return "<li>{$link}</li>\n";
786  }
787 
788  // If the page doesn't *exist*... our search index is out of date.
789  // The least confusing at this point is to drop the result.
790  // You may get less results, but... oh well. :P
791  if ( $result->isMissingRevision() ) {
792  return '';
793  }
794 
795  // format redirects / relevant sections
796  $redirectTitle = $result->getRedirectTitle();
797  $redirectText = $result->getRedirectSnippet();
798  $sectionTitle = $result->getSectionTitle();
799  $sectionText = $result->getSectionSnippet();
800  $categorySnippet = $result->getCategorySnippet();
801 
802  $redirect = '';
803  if ( !is_null( $redirectTitle ) ) {
804  if ( $redirectText == '' ) {
805  $redirectText = null;
806  }
807 
808  $redirect = "<span class='searchalttitle'>" .
809  $this->msg( 'search-redirect' )->rawParams(
810  Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
811  "</span>";
812  }
813 
814  $section = '';
815  if ( !is_null( $sectionTitle ) ) {
816  if ( $sectionText == '' ) {
817  $sectionText = null;
818  }
819 
820  $section = "<span class='searchalttitle'>" .
821  $this->msg( 'search-section' )->rawParams(
822  Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
823  "</span>";
824  }
825 
826  $category = '';
827  if ( $categorySnippet ) {
828  $category = "<span class='searchalttitle'>" .
829  $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
830  "</span>";
831  }
832 
833  // format text extract
834  $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
835 
836  $lang = $this->getLanguage();
837 
838  // format description
839  $byteSize = $result->getByteSize();
840  $wordCount = $result->getWordCount();
841  $timestamp = $result->getTimestamp();
842  $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
843  ->numParams( $wordCount )->escaped();
844 
845  if ( $title->getNamespace() == NS_CATEGORY ) {
846  $cat = Category::newFromTitle( $title );
847  $size = $this->msg( 'search-result-category-size' )
848  ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
849  ->escaped();
850  }
851 
852  $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
853 
854  $fileMatch = '';
855  // Include a thumbnail for media files...
856  if ( $title->getNamespace() == NS_FILE ) {
857  $img = $result->getFile();
858  $img = $img ?: wfFindFile( $title );
859  if ( $result->isFileMatch() ) {
860  $fileMatch = "<span class='searchalttitle'>" .
861  $this->msg( 'search-file-match' )->escaped() . "</span>";
862  }
863  if ( $img ) {
864  $thumb = $img->transform( [ 'width' => 120, 'height' => 120 ] );
865  if ( $thumb ) {
866  $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
867  // Float doesn't seem to interact well with the bullets.
868  // Table messes up vertical alignment of the bullets.
869  // Bullets are therefore disabled (didn't look great anyway).
870  return "<li>" .
871  '<table class="searchResultImage">' .
872  '<tr>' .
873  '<td style="width: 120px; text-align: center; vertical-align: top;">' .
874  $thumb->toHtml( [ 'desc-link' => true ] ) .
875  '</td>' .
876  '<td style="vertical-align: top;">' .
877  "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
878  $extract .
879  "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
880  '</td>' .
881  '</tr>' .
882  '</table>' .
883  "</li>\n";
884  }
885  }
886  }
887 
888  $html = null;
889 
890  $score = '';
891  $related = '';
892  if ( Hooks::run( 'ShowSearchHit', [
893  $this, $result, $terms,
894  &$link, &$redirect, &$section, &$extract,
895  &$score, &$size, &$date, &$related,
896  &$html
897  ] ) ) {
898  $html = "<li><div class='mw-search-result-heading'>" .
899  "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
900  "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
901  "</li>\n";
902  }
903 
904  return $html;
905  }
906 
910  protected function getCustomCaptions() {
911  if ( is_null( $this->customCaptions ) ) {
912  $this->customCaptions = [];
913  // format per line <iwprefix>:<caption>
914  $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
915  foreach ( $customLines as $line ) {
916  $parts = explode( ":", $line, 2 );
917  if ( count( $parts ) == 2 ) { // validate line
918  $this->customCaptions[$parts[0]] = $parts[1];
919  }
920  }
921  }
922  }
923 
932  protected function showInterwiki( $matches, $query ) {
934 
935  $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
936  $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
937  $out .= "<ul class='mw-search-iwresults'>\n";
938 
939  // work out custom project captions
940  $this->getCustomCaptions();
941 
942  if ( !is_array( $matches ) ) {
943  $matches = [ $matches ];
944  }
945 
946  foreach ( $matches as $set ) {
947  $prev = null;
948  $result = $set->next();
949  while ( $result ) {
950  $out .= $this->showInterwikiHit( $result, $prev, $query );
951  $prev = $result->getInterwikiPrefix();
952  $result = $set->next();
953  }
954  }
955 
956  // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
957  $out .= "</ul></div>\n";
958 
959  // convert the whole thing to desired language variant
960  $out = $wgContLang->convert( $out );
961 
962  return $out;
963  }
964 
974  protected function showInterwikiHit( $result, $lastInterwiki, $query ) {
975 
976  if ( $result->isBrokenTitle() ) {
977  return '';
978  }
979 
980  $title = $result->getTitle();
981 
982  $titleSnippet = $result->getTitleSnippet();
983 
984  if ( $titleSnippet == '' ) {
985  $titleSnippet = null;
986  }
987 
989  $title,
990  $titleSnippet
991  );
992 
993  // format redirect if any
994  $redirectTitle = $result->getRedirectTitle();
995  $redirectText = $result->getRedirectSnippet();
996  $redirect = '';
997  if ( !is_null( $redirectTitle ) ) {
998  if ( $redirectText == '' ) {
999  $redirectText = null;
1000  }
1001 
1002  $redirect = "<span class='searchalttitle'>" .
1003  $this->msg( 'search-redirect' )->rawParams(
1004  Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
1005  "</span>";
1006  }
1007 
1008  $out = "";
1009  // display project name
1010  if ( is_null( $lastInterwiki ) || $lastInterwiki != $title->getInterwiki() ) {
1011  if ( array_key_exists( $title->getInterwiki(), $this->customCaptions ) ) {
1012  // captions from 'search-interwiki-custom'
1013  $caption = $this->customCaptions[$title->getInterwiki()];
1014  } else {
1015  // default is to show the hostname of the other wiki which might suck
1016  // if there are many wikis on one hostname
1017  $parsed = wfParseUrl( $title->getFullURL() );
1018  $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
1019  }
1020  // "more results" link (special page stuff could be localized, but we might not know target lang)
1021  $searchTitle = Title::newFromText( $title->getInterwiki() . ":Special:Search" );
1022  $searchLink = Linker::linkKnown(
1023  $searchTitle,
1024  $this->msg( 'search-interwiki-more' )->text(),
1025  [],
1026  [
1027  'search' => $query,
1028  'fulltext' => 'Search'
1029  ]
1030  );
1031  $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
1032  {$searchLink}</span>{$caption}</div>\n<ul>";
1033  }
1034 
1035  $out .= "<li>{$link} {$redirect}</li>\n";
1036 
1037  return $out;
1038  }
1039 
1047  protected function powerSearchBox( $term, $opts ) {
1049 
1050  // Groups namespaces into rows according to subject
1051  $rows = [];
1052  foreach ( $this->searchConfig->searchableNamespaces() as $namespace => $name ) {
1053  $subject = MWNamespace::getSubject( $namespace );
1054  if ( !array_key_exists( $subject, $rows ) ) {
1055  $rows[$subject] = "";
1056  }
1057 
1058  $name = $wgContLang->getConverter()->convertNamespace( $namespace );
1059  if ( $name == '' ) {
1060  $name = $this->msg( 'blanknamespace' )->text();
1061  }
1062 
1063  $rows[$subject] .=
1064  Xml::openElement( 'td' ) .
1066  $name,
1067  "ns{$namespace}",
1068  "mw-search-ns{$namespace}",
1069  in_array( $namespace, $this->namespaces )
1070  ) .
1071  Xml::closeElement( 'td' );
1072  }
1073 
1074  $rows = array_values( $rows );
1075  $numRows = count( $rows );
1076 
1077  // Lays out namespaces in multiple floating two-column tables so they'll
1078  // be arranged nicely while still accommodating different screen widths
1079  $namespaceTables = '';
1080  for ( $i = 0; $i < $numRows; $i += 4 ) {
1081  $namespaceTables .= Xml::openElement( 'table' );
1082 
1083  for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
1084  $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
1085  }
1086 
1087  $namespaceTables .= Xml::closeElement( 'table' );
1088  }
1089 
1090  $showSections = [ 'namespaceTables' => $namespaceTables ];
1091 
1092  Hooks::run( 'SpecialSearchPowerBox', [ &$showSections, $term, $opts ] );
1093 
1094  $hidden = '';
1095  foreach ( $opts as $key => $value ) {
1096  $hidden .= Html::hidden( $key, $value );
1097  }
1098 
1099  # Stuff to feed saveNamespaces()
1100  $remember = '';
1101  $user = $this->getUser();
1102  if ( $user->isLoggedIn() ) {
1103  $remember .= Xml::checkLabel(
1104  $this->msg( 'powersearch-remember' )->text(),
1105  'nsRemember',
1106  'mw-search-powersearch-remember',
1107  false,
1108  // The token goes here rather than in a hidden field so it
1109  // is only sent when necessary (not every form submission).
1110  [ 'value' => $user->getEditToken(
1111  'searchnamespace',
1112  $this->getRequest()
1113  ) ]
1114  );
1115  }
1116 
1117  // Return final output
1118  return Xml::openElement( 'fieldset', [ 'id' => 'mw-searchoptions' ] ) .
1119  Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1120  Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1121  Xml::element( 'div', [ 'id' => 'mw-search-togglebox' ], '', false ) .
1122  Xml::element( 'div', [ 'class' => 'divider' ], '', false ) .
1123  implode( Xml::element( 'div', [ 'class' => 'divider' ], '', false ), $showSections ) .
1124  $hidden .
1125  Xml::element( 'div', [ 'class' => 'divider' ], '', false ) .
1126  $remember .
1127  Xml::closeElement( 'fieldset' );
1128  }
1129 
1133  protected function getSearchProfiles() {
1134  // Builds list of Search Types (profiles)
1135  $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
1136  $defaultNs = $this->searchConfig->defaultNamespaces();
1137  $profiles = [
1138  'default' => [
1139  'message' => 'searchprofile-articles',
1140  'tooltip' => 'searchprofile-articles-tooltip',
1141  'namespaces' => $defaultNs,
1142  'namespace-messages' => $this->searchConfig->namespacesAsText(
1143  $defaultNs
1144  ),
1145  ],
1146  'images' => [
1147  'message' => 'searchprofile-images',
1148  'tooltip' => 'searchprofile-images-tooltip',
1149  'namespaces' => [ NS_FILE ],
1150  ],
1151  'all' => [
1152  'message' => 'searchprofile-everything',
1153  'tooltip' => 'searchprofile-everything-tooltip',
1154  'namespaces' => $nsAllSet,
1155  ],
1156  'advanced' => [
1157  'message' => 'searchprofile-advanced',
1158  'tooltip' => 'searchprofile-advanced-tooltip',
1159  'namespaces' => self::NAMESPACES_CURRENT,
1160  ]
1161  ];
1162 
1163  Hooks::run( 'SpecialSearchProfiles', [ &$profiles ] );
1164 
1165  foreach ( $profiles as &$data ) {
1166  if ( !is_array( $data['namespaces'] ) ) {
1167  continue;
1168  }
1169  sort( $data['namespaces'] );
1170  }
1171 
1172  return $profiles;
1173  }
1174 
1179  protected function searchProfileTabs( $term ) {
1180  $out = Html::element( 'div', [ 'class' => 'mw-search-visualclear' ] ) .
1181  Xml::openElement( 'div', [ 'class' => 'mw-search-profile-tabs' ] );
1182 
1183  $bareterm = $term;
1184  if ( $this->startsWithImage( $term ) ) {
1185  // Deletes prefixes
1186  $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1187  }
1188 
1189  $profiles = $this->getSearchProfiles();
1190  $lang = $this->getLanguage();
1191 
1192  // Outputs XML for Search Types
1193  $out .= Xml::openElement( 'div', [ 'class' => 'search-types' ] );
1194  $out .= Xml::openElement( 'ul' );
1195  foreach ( $profiles as $id => $profile ) {
1196  if ( !isset( $profile['parameters'] ) ) {
1197  $profile['parameters'] = [];
1198  }
1199  $profile['parameters']['profile'] = $id;
1200 
1201  $tooltipParam = isset( $profile['namespace-messages'] ) ?
1202  $lang->commaList( $profile['namespace-messages'] ) : null;
1203  $out .= Xml::tags(
1204  'li',
1205  [
1206  'class' => $this->profile === $id ? 'current' : 'normal'
1207  ],
1208  $this->makeSearchLink(
1209  $bareterm,
1210  [],
1211  $this->msg( $profile['message'] )->text(),
1212  $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1213  $profile['parameters']
1214  )
1215  );
1216  }
1217  $out .= Xml::closeElement( 'ul' );
1218  $out .= Xml::closeElement( 'div' );
1219  $out .= Xml::element( 'div', [ 'style' => 'clear:both' ], '', false );
1220  $out .= Xml::closeElement( 'div' );
1221 
1222  return $out;
1223  }
1224 
1229  protected function searchOptions( $term ) {
1230  $out = '';
1231  $opts = [];
1232  $opts['profile'] = $this->profile;
1233 
1234  if ( $this->isPowerSearch() ) {
1235  $out .= $this->powerSearchBox( $term, $opts );
1236  } else {
1237  $form = '';
1238  Hooks::run( 'SpecialSearchProfileForm', [ $this, &$form, $this->profile, $term, $opts ] );
1239  $out .= $form;
1240  }
1241 
1242  return $out;
1243  }
1244 
1251  protected function shortDialog( $term, $resultsShown, $totalNum ) {
1252  $searchWidget = new MediaWiki\Widget\SearchInputWidget( [
1253  'id' => 'searchText',
1254  'name' => 'search',
1255  'autofocus' => trim( $term ) === '',
1256  'value' => $term,
1257  'dataLocation' => 'content',
1258  'infusable' => true,
1259  ] );
1260 
1261  $layout = new OOUI\ActionFieldLayout( $searchWidget, new OOUI\ButtonInputWidget( [
1262  'type' => 'submit',
1263  'label' => $this->msg( 'searchbutton' )->text(),
1264  'flags' => [ 'progressive', 'primary' ],
1265  ] ), [
1266  'align' => 'top',
1267  ] );
1268 
1269  $out =
1270  Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
1271  Html::hidden( 'profile', $this->profile ) .
1272  Html::hidden( 'fulltext', 'Search' ) .
1273  $layout;
1274 
1275  // Results-info
1276  if ( $totalNum > 0 && $this->offset < $totalNum ) {
1277  $top = $this->msg( 'search-showingresults' )
1278  ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1279  ->numParams( $resultsShown )
1280  ->parse();
1281  $out .= Xml::tags( 'div', [ 'class' => 'results-info' ], $top );
1282  }
1283 
1284  return $out;
1285  }
1286 
1297  protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = [] ) {
1298  $opt = $params;
1299  foreach ( $namespaces as $n ) {
1300  $opt['ns' . $n] = 1;
1301  }
1302 
1303  $stParams = array_merge(
1304  [
1305  'search' => $term,
1306  'fulltext' => $this->msg( 'search' )->text()
1307  ],
1308  $opt
1309  );
1310 
1311  return Xml::element(
1312  'a',
1313  [
1314  'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1315  'title' => $tooltip
1316  ],
1317  $label
1318  );
1319  }
1320 
1327  protected function startsWithImage( $term ) {
1329 
1330  $parts = explode( ':', $term );
1331  if ( count( $parts ) > 1 ) {
1332  return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1333  }
1334 
1335  return false;
1336  }
1337 
1344  protected function startsWithAll( $term ) {
1345 
1346  $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1347 
1348  $parts = explode( ':', $term );
1349  if ( count( $parts ) > 1 ) {
1350  return $parts[0] == $allkeyword;
1351  }
1352 
1353  return false;
1354  }
1355 
1361  public function getSearchEngine() {
1362  if ( $this->searchEngine === null ) {
1363  $this->searchEngine = $this->searchEngineType ?
1364  MediaWikiServices::getInstance()->getSearchEngineFactory()->create( $this->searchEngineType ) :
1365  MediaWikiServices::getInstance()->newSearchEngine();
1366  }
1367 
1368  return $this->searchEngine;
1369  }
1370 
1375  function getProfile() {
1376  return $this->profile;
1377  }
1378 
1383  function getNamespaces() {
1384  return $this->namespaces;
1385  }
1386 
1396  public function setExtraParam( $key, $value ) {
1397  $this->extraParams[$key] = $value;
1398  }
1399 
1400  protected function getGroupName() {
1401  return 'pages';
1402  }
1403 }
getDidYouMeanHtml(SearchResultSet $textMatches)
Generates HTML shown to the user when we have a suggestion about a query that might give more results...
external whereas SearchGetNearMatch runs after $term
Definition: hooks.txt:2713
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition: hooks.txt:1936
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
getDidYouMeanRewrittenHtml($term, SearchResultSet $textMatches)
Generates HTML shown to user when their query has been internally rewritten, and the results of the r...
shortDialog($term, $resultsShown, $totalNum)
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:802
startsWithImage($term)
Check if query starts with image: prefix.
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1555
wfScript($script= 'index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
SearchEngineConfig $searchConfig
Search engine configurations.
static element($element, $attribs=null, $contents= '', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition: Xml.php:39
to move a page</td >< td > &*You are moving the page across namespaces
getCustomCaptions()
Extract custom captions from search-interwiki-custom message.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
hasSuggestion()
Some search modes return a suggested alternate term if there are no exact hits.
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for except in special pages derived from QueryPage It s a common pitfall for new developers to submit code containing SQL queries which examine huge numbers of rows Remember that COUNT * is(N), counting rows in atable is like counting beans in a bucket.------------------------------------------------------------------------Replication------------------------------------------------------------------------The largest installation of MediaWiki, Wikimedia, uses a large set ofslave MySQL servers replicating writes made to a master MySQL server.Itis important to understand the issues associated with this setup if youwant to write code destined for Wikipedia.It's often the case that the best algorithm to use for a given taskdepends on whether or not replication is in use.Due to our unabashedWikipedia-centrism, we often just use the replication-friendly version, but if you like, you can use wfGetLB() ->getServerCount() > 1 tocheck to see if replication is in use.===Lag===Lag primarily occurs when large write queries are sent to the master.Writes on the master are executed in parallel, but they are executed inserial when they are replicated to the slaves.The master writes thequery to the binlog when the transaction is committed.The slaves pollthe binlog and start executing the query as soon as it appears.They canservice reads while they are performing a write query, but will not readanything more from the binlog and thus will perform no more writes.Thismeans that if the write query runs for a long time, the slaves will lagbehind the master for the time it takes for the write query to complete.Lag can be exacerbated by high read load.MediaWiki's load balancer willstop sending reads to a slave when it is lagged by more than 30 seconds.If the load ratios are set incorrectly, or if there is too much loadgenerally, this may lead to a slave permanently hovering around 30seconds lag.If all slaves are lagged by more than 30 seconds, MediaWiki will stopwriting to the database.All edits and other write operations will berefused, with an error returned to the user.This gives the slaves achance to catch up.Before we had this mechanism, the slaves wouldregularly lag by several minutes, making review of recent editsdifficult.In addition to this, MediaWiki attempts to ensure that the user seesevents occurring on the wiki in chronological order.A few seconds of lagcan be tolerated, as long as the user sees a consistent picture fromsubsequent requests.This is done by saving the master binlog positionin the session, and then at the start of each request, waiting for theslave to catch up to that position before doing any reads from it.Ifthis wait times out, reads are allowed anyway, but the request isconsidered to be in"lagged slave mode".Lagged slave mode can bechecked by calling wfGetLB() ->getLaggedSlaveMode().The onlypractical consequence at present is a warning displayed in the pagefooter.===Lag avoidance===To avoid excessive lag, queries which write large numbers of rows shouldbe split up, generally to write one row at a time.Multi-row INSERT...SELECT queries are the worst offenders should be avoided altogether.Instead do the select first and then the insert.===Working with lag===Despite our best efforts, it's not practical to guarantee a low-lagenvironment.Lag will usually be less than one second, but mayoccasionally be up to 30 seconds.For scalability, it's very importantto keep load on the master low, so simply sending all your queries tothe master is not the answer.So when you have a genuine need forup-to-date data, the following approach is advised:1) Do a quick query to the master for a sequence number or timestamp 2) Run the full query on the slave and check if it matches the data you gotfrom the master 3) If it doesn't, run the full query on the masterTo avoid swamping the master every time the slaves lag, use of thisapproach should be kept to a minimum.In most cases you should just readfrom the slave and let the user deal with the delay.------------------------------------------------------------------------Lock contention------------------------------------------------------------------------Due to the high write rate on Wikipedia(and some other wikis), MediaWiki developers need to be very careful to structure their writesto avoid long-lasting locks.By default, MediaWiki opens a transactionat the first query, and commits it before the output is sent.Locks willbe held from the time when the query is done until the commit.So youcan reduce lock time by doing as much processing as possible before youdo your write queries.Often this approach is not good enough, and it becomes necessary toenclose small groups of queries in their own transaction.Use thefollowing syntax:$dbw=wfGetDB(DB_MASTER
static rawElement($element, $attribs=[], $contents= '')
Returns an HTML element in a string.
Definition: Html.php:209
getNamespaces()
Current namespaces.
if(!isset($args[0])) $lang
implements Special:Search - Run text & title search and display the output
string $searchEngineType
Search engine type, if not default.
static hidden($name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition: Html.php:758
execute($par)
Entry point.
getFile()
Get the file for this page, if one exists.
$value
searchContainedSyntax()
Did the search contain search syntax? If so, Special:Search won't offer the user a link to a create a...
showInterwiki($matches, $query)
Show results from other wikis.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
saveNamespaces()
Save namespace preferences when we're supposed to.
msg()
Wrapper around wfMessage that sets the current context.
showHit(SearchResult $result, $terms, $position)
Format a single hit result.
getOutput()
Get the OutputPage being used for this instance.
setExtraParam($key, $value)
Users of hook SpecialSearchSetupEngine can use this to add more params to links to not lose selection...
startsWithAll($term)
Check if query starts with all: prefix.
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:262
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
addHelpLink($to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
showInterwikiHit($result, $lastInterwiki, $query)
Show single interwiki link.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message.Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item.Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page.Return false to stop further processing of the tag $reader:XMLReader object &$pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision.Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag.Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload.Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports.&$fullInterwikiPrefix:Interwiki prefix, may contain colons.&$pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable.Can be used to lazy-load the import sources list.&$importSources:The value of $wgImportSources.Modify as necessary.See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page.$context:IContextSource object &$pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect.&$title:Title object for the current page &$request:WebRequest &$ignoreRedirect:boolean to skip redirect check &$target:Title/string of redirect target &$article:Article object 'InternalParseBeforeLinks':during Parser's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InternalParseBeforeSanitize':during Parser's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings.Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments.&$parser:Parser object &$text:string containing partially parsed text &$stripState:Parser's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not.Return true without providing an interwiki to continue interwiki search.$prefix:interwiki prefix we are looking for.&$iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user's email has been invalidated successfully.$user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification.Callee may modify $url and $query, URL will be constructed as $url.$query &$url:URL to index.php &$query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) &$article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() &$ip:IP being check &$result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from &$allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn't match your organization.$addr:The e-mail address entered by the user &$result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user &$result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we're looking for a messages file for &$file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces.Do not use this hook to add namespaces.Use CanonicalNamespaces for that.&$namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names.&$names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page's language links.This is called in various places to allow extensions to define the effective language links for a page.$title:The page's Title.&$links:Associative array mapping language codes to prefixed links of the form"language:title".&$linkFlags:Associative array mapping prefixed links to arrays of flags.Currently unused, but planned to provide support for marking individual language links in the UI, e.g.for featured articles. 'LanguageSelector':Hook to change the language selector available on a page.$out:The output page.$cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED!Use HtmlPageLinkRendererBegin instead.Used when generating internal and interwiki links in Linker::link(), before processing starts.Return false to skip default processing and return $ret.See documentation for Linker::link() for details on the expected meanings of parameters.$skin:the Skin object $target:the Title that the link is pointing to &$html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1934
outputHeader($summaryMessageKey= '')
Outputs a summary message on top of special pages Per default the message key is the canonical name o...
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:2889
static closeElement($element)
Shortcut to close an XML element.
Definition: Xml.php:118
Parent class for all special pages.
Definition: SpecialPage.php:36
isPowerSearch()
Return true if current search is a power (advanced) search.
wfEscapeWikiText($text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
getProfile()
Current search profile.
wfReadOnly()
Check whether the wiki is in read-only mode.
array $extraParams
For links.
const NAMESPACES_CURRENT
if($limit) $timestamp
goResult($term)
If an exact title match can be found, jump straight ahead to it.
static openElement($element, $attribs=null)
This opens an XML element.
Definition: Xml.php:109
load()
Set up basic search parameters from the request and user settings.
static newFromTitle($title)
Factory function.
Definition: Category.php:140
getTextSnippet($terms)
$params
string $mPrefix
The prefix url parameter.
const NS_CATEGORY
Definition: Defines.php:70
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes! ...
isBrokenTitle()
Check if this is result points to an invalid title.
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:953
static linkKnown($target, $html=null, $customAttribs=[], $query=[], $options=[ 'known'])
Identical to link(), except $options defaults to 'known'.
Definition: Linker.php:255
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
shouldRunSuggestedQuery(SearchResultSet $textMatches)
Decide if the suggested query should be run, and it's results returned instead of the provided $textM...
const NS_FILE
Definition: Defines.php:62
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
isFileMatch()
Did this match file contents (eg: PDF/DJVU)?
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
Definition: hooks.txt:2889
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
powerSearchOptions()
Reconstruct the 'power search' options for links.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
static tags($element, $attribs=null, $contents)
Same as Xml::element(), but does not escape contents.
Definition: Xml.php:131
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2573
powerSearchBox($term, $opts)
Generates the power search box at [[Special:Search]].
getUser()
Shortcut to get the User executing this instance.
static numParam($num)
Definition: Message.php:996
$line
Definition: cdb.php:59
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at name
Definition: design.txt:12
getConfig()
Shortcut to get main config object.
getLanguage()
Shortcut to get user's language.
showCreateLink($title, $num, $titleMatches, $textMatches)
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition: design.txt:56
null string $profile
Current search profile.
static checkLabel($label, $name, $id, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox with a label.
Definition: Xml.php:420
static addCallableUpdate($callable, $stage=self::POSTSEND, IDatabase $dbw=null)
Add a callable update.
getRequest()
Get the WebRequest being used for this instance.
makeSearchLink($term, $namespaces, $label, $tooltip, $params=[])
Make a search link with some target namespaces.
=Architecture==Two class hierarchies are used to provide the functionality associated with the different content models:*Content interface(and AbstractContent base class) define functionality that acts on the concrete content of a page, and *ContentHandler base class provides functionality specific to a content model, but not acting on concrete content.The most important function of ContentHandler is to act as a factory for the appropriate implementation of Content.These Content objects are to be used by MediaWiki everywhere, instead of passing page content around as text.All manipulation and analysis of page content must be done via the appropriate methods of the Content object.For each content model, a subclass of ContentHandler has to be registered with $wgContentHandlers.The ContentHandler object for a given content model can be obtained using ContentHandler::getForModelID($id).Also Title, WikiPage and Revision now have getContentHandler() methods for convenience.ContentHandler objects are singletons that provide functionality specific to the content type, but not directly acting on the content of some page.ContentHandler::makeEmptyContent() and ContentHandler::unserializeContent() can be used to create a Content object of the appropriate type.However, it is recommended to instead use WikiPage::getContent() resp.Revision::getContent() to get a page's content as a Content object.These two methods should be the ONLY way in which page content is accessed.Another important function of ContentHandler objects is to define custom action handlers for a content model, see ContentHandler::getActionOverrides().This is similar to what WikiPage::getActionOverrides() was already doing.==Serialization==With the ContentHandler facility, page content no longer has to be text based.Objects implementing the Content interface are used to represent and handle the content internally.For storage and data exchange, each content model supports at least one serialization format via ContentHandler::serializeContent($content).The list of supported formats for a given content model can be accessed using ContentHandler::getSupportedFormats().Content serialization formats are identified using MIME type like strings.The following formats are built in:*text/x-wiki-wikitext *text/javascript-for js pages *text/css-for css pages *text/plain-for future use, e.g.with plain text messages.*text/html-for future use, e.g.with plain html messages.*application/vnd.php.serialized-for future use with the api and for extensions *application/json-for future use with the api, and for use by extensions *application/xml-for future use with the api, and for use by extensions In PHP, use the corresponding CONTENT_FORMAT_XXX constant.Note that when using the API to access page content, especially action=edit, action=parse and action=query &prop=revisions, the model and format of the content should always be handled explicitly.Without that information, interpretation of the provided content is not reliable.The same applies to XML dumps generated via maintenance/dumpBackup.php or Special:Export.Also note that the API will provide encapsulated, serialized content-so if the API was called with format=json, and contentformat is also json(or rather, application/json), the page content is represented as a string containing an escaped json structure.Extensions that use JSON to serialize some types of page content may provide specialized API modules that allow access to that content in a more natural form.==Compatibility==The ContentHandler facility is introduced in a way that should allow all existing code to keep functioning at least for pages that contain wikitext or other text based content.However, a number of functions and hooks have been deprecated in favor of new versions that are aware of the page's content model, and will now generate warnings when used.Most importantly, the following functions have been deprecated:*Revisions::getText() is deprecated in favor Revisions::getContent()*WikiPage::getText() is deprecated in favor WikiPage::getContent() Also, the old Article::getContent()(which returns text) is superceded by Article::getContentObject().However, both methods should be avoided since they do not provide clean access to the page's actual content.For instance, they may return a system message for non-existing pages.Use WikiPage::getContent() instead.Code that relies on a textual representation of the page content should eventually be rewritten.However, ContentHandler::getContentText() provides a stop-gap that can be used to get text for a page.Its behavior is controlled by $wgContentHandlerTextFallback it
wfParseUrl($url)
parse_url() work-alike, but non-broken.
SearchEngine $searchEngine
Search engine.
static getValidNamespaces()
Returns an array of the namespaces (by integer id) that exist on the wiki.
static getSubject($index)
Get the subject namespace index for a given namespace Special namespaces (NS_MEDIA, NS_SPECIAL) are always the subject.
static element($element, $attribs=[], $contents= '')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:229
showMatches($matches, $interwiki=null)
Show whole set of results.
wfFindFile($title, $options=[])
Find a file.
interwikiHeader($interwiki, $interwikiResult)
Produce wiki header for interwiki results.
powerSearch(&$request)
Extract "power search" namespace settings from the request object, returning a list of index numbers ...
array $customCaptions
Names of the wikis, in format: Interwiki prefix -> caption.
isMissingRevision()
Check if target page is missing, happens when index is out of date.
getPageTitle($subpage=false)
Get a self-referential title object.
searchProfileTabs($term)
$matches
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:300