MediaWiki  master
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  $this->setHeaders();
104  $this->outputHeader();
105  $out = $this->getOutput();
106  $out->allowClickjacking();
107  $out->addModuleStyles( [
108  'mediawiki.special', 'mediawiki.special.search.styles', 'mediawiki.ui', 'mediawiki.ui.button',
109  'mediawiki.ui.input', 'mediawiki.widgets.SearchInputWidget.styles',
110  ] );
111  $this->addHelpLink( 'Help:Searching' );
112 
113  // Strip underscores from title parameter; most of the time we'll want
114  // text form here. But don't strip underscores from actual text params!
115  $titleParam = str_replace( '_', ' ', $par );
116 
117  $request = $this->getRequest();
118 
119  // Fetch the search term
120  $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
121 
122  $this->load();
123  if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
124  $this->saveNamespaces();
125  // Remove the token from the URL to prevent the user from inadvertently
126  // exposing it (e.g. by pasting it into a public wiki page) or undoing
127  // later settings changes (e.g. by reloading the page).
128  $query = $request->getValues();
129  unset( $query['title'], $query['nsRemember'] );
130  $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
131  return;
132  }
133 
134  $out->addJsConfigVars( [ 'searchTerm' => $search ] );
135  $this->searchEngineType = $request->getVal( 'srbackend' );
136 
137  if ( $request->getVal( 'fulltext' )
138  || !is_null( $request->getVal( 'offset' ) )
139  ) {
140  $this->showResults( $search );
141  } else {
142  $this->goResult( $search );
143  }
144  }
145 
151  public function load() {
152  $request = $this->getRequest();
153  list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, '' );
154  $this->mPrefix = $request->getVal( 'prefix', '' );
155 
156  $user = $this->getUser();
157 
158  # Extract manually requested namespaces
159  $nslist = $this->powerSearch( $request );
160  if ( !count( $nslist ) ) {
161  # Fallback to user preference
162  $nslist = $this->searchConfig->userNamespaces( $user );
163  }
164 
165  $profile = null;
166  if ( !count( $nslist ) ) {
167  $profile = 'default';
168  }
169 
170  $profile = $request->getVal( 'profile', $profile );
171  $profiles = $this->getSearchProfiles();
172  if ( $profile === null ) {
173  // BC with old request format
174  $profile = 'advanced';
175  foreach ( $profiles as $key => $data ) {
176  if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
177  $profile = $key;
178  }
179  }
180  $this->namespaces = $nslist;
181  } elseif ( $profile === 'advanced' ) {
182  $this->namespaces = $nslist;
183  } else {
184  if ( isset( $profiles[$profile]['namespaces'] ) ) {
185  $this->namespaces = $profiles[$profile]['namespaces'];
186  } else {
187  // Unknown profile requested
188  $profile = 'default';
189  $this->namespaces = $profiles['default']['namespaces'];
190  }
191  }
192 
193  $this->fulltext = $request->getVal( 'fulltext' );
194  $this->runSuggestion = (bool)$request->getVal( 'runsuggestion', true );
195  $this->profile = $profile;
196  }
197 
203  public function goResult( $term ) {
204  $this->setupPage( $term );
205  # Try to go to page as entered.
207  # If the string cannot be used to create a title
208  if ( is_null( $title ) ) {
209  $this->showResults( $term );
210 
211  return;
212  }
213  # If there's an exact or very near match, jump right there.
214  $title = $this->getSearchEngine()
215  ->getNearMatcher( $this->getConfig() )->getNearMatch( $term );
216 
217  if ( !is_null( $title ) &&
218  Hooks::run( 'SpecialSearchGoResult', [ $term, $title, &$url ] )
219  ) {
220  if ( $url === null ) {
221  $url = $title->getFullURL();
222  }
223  $this->getOutput()->redirect( $url );
224 
225  return;
226  }
227  # No match, generate an edit URL
229  if ( !is_null( $title ) ) {
230  Hooks::run( 'SpecialSearchNogomatch', [ &$title ] );
231  }
232  $this->showResults( $term );
233  }
234 
238  public function showResults( $term ) {
240 
241  $search = $this->getSearchEngine();
242  $search->setFeatureData( 'rewrite', $this->runSuggestion );
243  $search->setLimitOffset( $this->limit, $this->offset );
244  $search->setNamespaces( $this->namespaces );
245  $search->prefix = $this->mPrefix;
246  $term = $search->transformSearchTerm( $term );
247 
248  Hooks::run( 'SpecialSearchSetupEngine', [ $this, $this->profile, $search ] );
249 
250  $this->setupPage( $term );
251 
252  $out = $this->getOutput();
253 
254  if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
255  $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
256  if ( $searchFowardUrl ) {
257  $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
258  $out->redirect( $url );
259  } else {
260  $out->addHTML(
261  Xml::openElement( 'fieldset' ) .
262  Xml::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
263  Xml::element(
264  'p',
265  [ 'class' => 'mw-searchdisabled' ],
266  $this->msg( 'searchdisabled' )->text()
267  ) .
268  $this->msg( 'googlesearch' )->rawParams(
269  htmlspecialchars( $term ),
270  'UTF-8',
271  $this->msg( 'searchbutton' )->escaped()
272  )->text() .
273  Xml::closeElement( 'fieldset' )
274  );
275  }
276 
277  return;
278  }
279 
281  $showSuggestion = $title === null || !$title->isKnown();
282  $search->setShowSuggestion( $showSuggestion );
283 
284  // fetch search results
285  $rewritten = $search->replacePrefixes( $term );
286 
287  $titleMatches = $search->searchTitle( $rewritten );
288  $textMatches = $search->searchText( $rewritten );
289 
290  $textStatus = null;
291  if ( $textMatches instanceof Status ) {
292  $textStatus = $textMatches;
293  $textMatches = null;
294  }
295 
296  // did you mean... suggestions
297  $didYouMeanHtml = '';
298  if ( $showSuggestion && $textMatches && !$textStatus ) {
299  if ( $textMatches->hasRewrittenQuery() ) {
300  $didYouMeanHtml = $this->getDidYouMeanRewrittenHtml( $term, $textMatches );
301  } elseif ( $textMatches->hasSuggestion() ) {
302  $didYouMeanHtml = $this->getDidYouMeanHtml( $textMatches );
303  }
304  }
305 
306  if ( !Hooks::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
307  # Hook requested termination
308  return;
309  }
310 
311  // start rendering the page
312  $out->addHTML(
314  'form',
315  [
316  'id' => ( $this->isPowerSearch() ? 'powersearch' : 'search' ),
317  'method' => 'get',
318  'action' => wfScript(),
319  ]
320  )
321  );
322 
323  // Get number of results
324  $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
325  if ( $titleMatches ) {
326  $titleMatchesNum = $titleMatches->numRows();
327  $numTitleMatches = $titleMatches->getTotalHits();
328  }
329  if ( $textMatches ) {
330  $textMatchesNum = $textMatches->numRows();
331  $numTextMatches = $textMatches->getTotalHits();
332  }
333  $num = $titleMatchesNum + $textMatchesNum;
334  $totalRes = $numTitleMatches + $numTextMatches;
335 
336  $out->enableOOUI();
337  $out->addHTML(
338  # This is an awful awful ID name. It's not a table, but we
339  # named it poorly from when this was a table so now we're
340  # stuck with it
341  Xml::openElement( 'div', [ 'id' => 'mw-search-top-table' ] ) .
342  $this->shortDialog( $term, $num, $totalRes ) .
343  Xml::closeElement( 'div' ) .
344  $this->searchProfileTabs( $term ) .
345  $this->searchOptions( $term ) .
346  Xml::closeElement( 'form' ) .
347  $didYouMeanHtml
348  );
349 
350  $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
351  if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
352  // Empty query -- straight view of search form
353  return;
354  }
355 
356  $out->addHTML( "<div class='searchresults'>" );
357 
358  // prev/next links
359  $prevnext = null;
360  if ( $num || $this->offset ) {
361  // Show the create link ahead
362  $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
363  if ( $totalRes > $this->limit || $this->offset ) {
364  if ( $this->searchEngineType !== null ) {
365  $this->setExtraParam( 'srbackend', $this->searchEngineType );
366  }
367  $prevnext = $this->getLanguage()->viewPrevNext(
368  $this->getPageTitle(),
369  $this->offset,
370  $this->limit,
371  $this->powerSearchOptions() + [ 'search' => $term ],
372  $this->limit + $this->offset >= $totalRes
373  );
374  }
375  }
376  Hooks::run( 'SpecialSearchResults', [ $term, &$titleMatches, &$textMatches ] );
377 
378  $out->parserOptions()->setEditSection( false );
379  if ( $titleMatches ) {
380  if ( $numTitleMatches > 0 ) {
381  $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
382  $out->addHTML( $this->showMatches( $titleMatches ) );
383  }
384  $titleMatches->free();
385  }
386  if ( $textMatches && !$textStatus ) {
387  // output appropriate heading
388  if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
389  $out->addHTML( '<div class="mw-search-visualclear"></div>' );
390  // if no title matches the heading is redundant
391  $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
392  }
393 
394  // show results
395  if ( $numTextMatches > 0 ) {
396  $out->addHTML( $this->showMatches( $textMatches ) );
397  }
398 
399  // show secondary interwiki results if any
400  if ( $textMatches->hasInterwikiResults( SearchResultSet::SECONDARY_RESULTS ) ) {
401  $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(
402  SearchResultSet::SECONDARY_RESULTS ), $term ) );
403  }
404  }
405 
406  $hasOtherResults = $textMatches &&
407  $textMatches->hasInterwikiResults( SearchResultSet::INLINE_RESULTS );
408 
409  if ( $num === 0 ) {
410  if ( $textStatus ) {
411  $out->addHTML( '<div class="error">' .
412  $textStatus->getMessage( 'search-error' ) . '</div>' );
413  } else {
414  $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
415  $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
416  [ $hasOtherResults ? 'search-nonefound-thiswiki' : 'search-nonefound',
418  ] );
419  }
420  }
421 
422  if ( $hasOtherResults ) {
423  foreach ( $textMatches->getInterwikiResults( SearchResultSet::INLINE_RESULTS )
424  as $interwiki => $interwikiResult ) {
425  if ( $interwikiResult instanceof Status || $interwikiResult->numRows() == 0 ) {
426  // ignore bad interwikis for now
427  continue;
428  }
429  // TODO: wiki header
430  $out->addHTML( $this->showMatches( $interwikiResult, $interwiki ) );
431  }
432  }
433 
434  if ( $textMatches ) {
435  $textMatches->free();
436  }
437 
438  $out->addHTML( '<div class="mw-search-visualclear"></div>' );
439 
440  if ( $prevnext ) {
441  $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
442  }
443 
444  $out->addHTML( "</div>" );
445 
446  Hooks::run( 'SpecialSearchResultsAppend', [ $this, $out, $term ] );
447 
448  }
449 
456  protected function interwikiHeader( $interwiki, $interwikiResult ) {
457  // TODO: we need to figure out how to name wikis correctly
458  $wikiMsg = $this->msg( 'search-interwiki-results-' . $interwiki )->parse();
459  return "<p class=\"mw-search-interwiki-header mw-search-visualclear\">\n$wikiMsg</p>";
460  }
461 
469  protected function shouldRunSuggestedQuery( SearchResultSet $textMatches ) {
470  if ( !$this->runSuggestion ||
471  !$textMatches->hasSuggestion() ||
472  $textMatches->numRows() > 0 ||
473  $textMatches->searchContainedSyntax()
474  ) {
475  return false;
476  }
477 
478  return $this->getConfig()->get( 'SearchRunSuggestedQuery' );
479  }
480 
485  protected function getDidYouMeanHtml( SearchResultSet $textMatches ) {
486  # mirror Go/Search behavior of original request ..
487  $params = [ 'search' => $textMatches->getSuggestionQuery() ];
488  if ( $this->fulltext === null ) {
489  $params['fulltext'] = 'Search';
490  } else {
491  $params['fulltext'] = $this->fulltext;
492  }
493  $stParams = array_merge( $params, $this->powerSearchOptions() );
494 
495  $suggest = Linker::linkKnown(
496  $this->getPageTitle(),
497  $textMatches->getSuggestionSnippet() ?: null,
498  [ 'id' => 'mw-search-DYM-suggestion' ],
499  $stParams
500  );
501 
502  # HTML of did you mean... search suggestion link
503  return Html::rawElement(
504  'div',
505  [ 'class' => 'searchdidyoumean' ],
506  $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
507  );
508  }
509 
519  protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet $textMatches ) {
520  // Showing results for '$rewritten'
521  // Search instead for '$orig'
522 
523  $params = [ 'search' => $textMatches->getQueryAfterRewrite() ];
524  if ( $this->fulltext === null ) {
525  $params['fulltext'] = 'Search';
526  } else {
527  $params['fulltext'] = $this->fulltext;
528  }
529  $stParams = array_merge( $params, $this->powerSearchOptions() );
530 
531  $rewritten = Linker::linkKnown(
532  $this->getPageTitle(),
533  $textMatches->getQueryAfterRewriteSnippet() ?: null,
534  [ 'id' => 'mw-search-DYM-rewritten' ],
535  $stParams
536  );
537 
538  $stParams['search'] = $term;
539  $stParams['runsuggestion'] = 0;
540  $original = Linker::linkKnown(
541  $this->getPageTitle(),
542  htmlspecialchars( $term ),
543  [ 'id' => 'mw-search-DYM-original' ],
544  $stParams
545  );
546 
547  return Html::rawElement(
548  'div',
549  [ 'class' => 'searchdidyoumean' ],
550  $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
551  );
552  }
553 
560  protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
561  // show direct page/create link if applicable
562 
563  // Check DBkey !== '' in case of fragment link only.
564  if ( is_null( $title ) || $title->getDBkey() === ''
565  || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
566  || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
567  ) {
568  // invalid title
569  // preserve the paragraph for margins etc...
570  $this->getOutput()->addHTML( '<p></p>' );
571 
572  return;
573  }
574 
575  $messageName = 'searchmenu-new-nocreate';
576  $linkClass = 'mw-search-createlink';
577 
578  if ( !$title->isExternal() ) {
579  if ( $title->isKnown() ) {
580  $messageName = 'searchmenu-exists';
581  $linkClass = 'mw-search-exists';
582  } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
583  $messageName = 'searchmenu-new';
584  }
585  }
586 
587  $params = [
588  $messageName,
589  wfEscapeWikiText( $title->getPrefixedText() ),
590  Message::numParam( $num )
591  ];
592  Hooks::run( 'SpecialSearchCreateLink', [ $title, &$params ] );
593 
594  // Extensions using the hook might still return an empty $messageName
595  if ( $messageName ) {
596  $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
597  } else {
598  // preserve the paragraph for margins etc...
599  $this->getOutput()->addHTML( '<p></p>' );
600  }
601  }
602 
606  protected function setupPage( $term ) {
607  $out = $this->getOutput();
608  if ( strval( $term ) !== '' ) {
609  $out->setPageTitle( $this->msg( 'searchresults' ) );
610  $out->setHTMLTitle( $this->msg( 'pagetitle' )
611  ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
612  ->inContentLanguage()->text()
613  );
614  }
615  // add javascript specific to special:search
616  $out->addModules( 'mediawiki.special.search' );
617  }
618 
624  protected function isPowerSearch() {
625  return $this->profile === 'advanced';
626  }
627 
635  protected function powerSearch( &$request ) {
636  $arr = [];
637  foreach ( $this->searchConfig->searchableNamespaces() as $ns => $name ) {
638  if ( $request->getCheck( 'ns' . $ns ) ) {
639  $arr[] = $ns;
640  }
641  }
642 
643  return $arr;
644  }
645 
651  protected function powerSearchOptions() {
652  $opt = [];
653  if ( !$this->isPowerSearch() ) {
654  $opt['profile'] = $this->profile;
655  } else {
656  foreach ( $this->namespaces as $n ) {
657  $opt['ns' . $n] = 1;
658  }
659  }
660 
661  return $opt + $this->extraParams;
662  }
663 
669  protected function saveNamespaces() {
670  $user = $this->getUser();
671  $request = $this->getRequest();
672 
673  if ( $user->isLoggedIn() &&
674  $user->matchEditToken(
675  $request->getVal( 'nsRemember' ),
676  'searchnamespace',
677  $request
678  ) && !wfReadOnly()
679  ) {
680  // Reset namespace preferences: namespaces are not searched
681  // when they're not mentioned in the URL parameters.
682  foreach ( MWNamespace::getValidNamespaces() as $n ) {
683  $user->setOption( 'searchNs' . $n, false );
684  }
685  // The request parameters include all the namespaces to be searched.
686  // Even if they're the same as an existing profile, they're not eaten.
687  foreach ( $this->namespaces as $n ) {
688  $user->setOption( 'searchNs' . $n, true );
689  }
690 
691  DeferredUpdates::addCallableUpdate( function () use ( $user ) {
692  $user->saveSettings();
693  } );
694 
695  return true;
696  }
697 
698  return false;
699  }
700 
709  protected function showMatches( &$matches, $interwiki = null ) {
711 
712  $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
713  $out = '';
714  $result = $matches->next();
715  $pos = $this->offset;
716 
717  if ( $result && $interwiki ) {
718  $out .= $this->interwikiHeader( $interwiki, $result );
719  }
720 
721  $out .= "<ul class='mw-search-results'>\n";
722  while ( $result ) {
723  $out .= $this->showHit( $result, $terms, $pos++ );
724  $result = $matches->next();
725  }
726  $out .= "</ul>\n";
727 
728  // convert the whole thing to desired language variant
729  $out = $wgContLang->convert( $out );
730 
731  return $out;
732  }
733 
743  protected function showHit( $result, $terms, $position ) {
744 
745  if ( $result->isBrokenTitle() ) {
746  return '';
747  }
748 
749  $title = $result->getTitle();
750 
751  $titleSnippet = $result->getTitleSnippet();
752 
753  if ( $titleSnippet == '' ) {
754  $titleSnippet = null;
755  }
756 
757  $link_t = clone $title;
758  $query = [];
759 
760  Hooks::run( 'ShowSearchHitTitle',
761  [ &$link_t, &$titleSnippet, $result, $terms, $this, &$query ] );
762 
764  $link_t,
765  $titleSnippet,
766  [ 'data-serp-pos' => $position ], // HTML attributes
767  $query
768  );
769 
770  // If page content is not readable, just return the title.
771  // This is not quite safe, but better than showing excerpts from non-readable pages
772  // Note that hiding the entry entirely would screw up paging.
773  if ( !$title->userCan( 'read', $this->getUser() ) ) {
774  return "<li>{$link}</li>\n";
775  }
776 
777  // If the page doesn't *exist*... our search index is out of date.
778  // The least confusing at this point is to drop the result.
779  // You may get less results, but... oh well. :P
780  if ( $result->isMissingRevision() ) {
781  return '';
782  }
783 
784  // format redirects / relevant sections
785  $redirectTitle = $result->getRedirectTitle();
786  $redirectText = $result->getRedirectSnippet();
787  $sectionTitle = $result->getSectionTitle();
788  $sectionText = $result->getSectionSnippet();
789  $categorySnippet = $result->getCategorySnippet();
790 
791  $redirect = '';
792  if ( !is_null( $redirectTitle ) ) {
793  if ( $redirectText == '' ) {
794  $redirectText = null;
795  }
796 
797  $redirect = "<span class='searchalttitle'>" .
798  $this->msg( 'search-redirect' )->rawParams(
799  Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
800  "</span>";
801  }
802 
803  $section = '';
804  if ( !is_null( $sectionTitle ) ) {
805  if ( $sectionText == '' ) {
806  $sectionText = null;
807  }
808 
809  $section = "<span class='searchalttitle'>" .
810  $this->msg( 'search-section' )->rawParams(
811  Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
812  "</span>";
813  }
814 
815  $category = '';
816  if ( $categorySnippet ) {
817  $category = "<span class='searchalttitle'>" .
818  $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
819  "</span>";
820  }
821 
822  // format text extract
823  $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
824 
825  $lang = $this->getLanguage();
826 
827  // format description
828  $byteSize = $result->getByteSize();
829  $wordCount = $result->getWordCount();
830  $timestamp = $result->getTimestamp();
831  $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
832  ->numParams( $wordCount )->escaped();
833 
834  if ( $title->getNamespace() == NS_CATEGORY ) {
835  $cat = Category::newFromTitle( $title );
836  $size = $this->msg( 'search-result-category-size' )
837  ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
838  ->escaped();
839  }
840 
841  $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
842 
843  $fileMatch = '';
844  // Include a thumbnail for media files...
845  if ( $title->getNamespace() == NS_FILE ) {
846  $img = $result->getFile();
847  $img = $img ?: wfFindFile( $title );
848  if ( $result->isFileMatch() ) {
849  $fileMatch = "<span class='searchalttitle'>" .
850  $this->msg( 'search-file-match' )->escaped() . "</span>";
851  }
852  if ( $img ) {
853  $thumb = $img->transform( [ 'width' => 120, 'height' => 120 ] );
854  if ( $thumb ) {
855  $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
856  // Float doesn't seem to interact well with the bullets.
857  // Table messes up vertical alignment of the bullets.
858  // Bullets are therefore disabled (didn't look great anyway).
859  return "<li>" .
860  '<table class="searchResultImage">' .
861  '<tr>' .
862  '<td style="width: 120px; text-align: center; vertical-align: top;">' .
863  $thumb->toHtml( [ 'desc-link' => true ] ) .
864  '</td>' .
865  '<td style="vertical-align: top;">' .
866  "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
867  $extract .
868  "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
869  '</td>' .
870  '</tr>' .
871  '</table>' .
872  "</li>\n";
873  }
874  }
875  }
876 
877  $html = null;
878 
879  $score = '';
880  $related = '';
881  if ( Hooks::run( 'ShowSearchHit', [
882  $this, $result, $terms,
883  &$link, &$redirect, &$section, &$extract,
884  &$score, &$size, &$date, &$related,
885  &$html
886  ] ) ) {
887  $html = "<li><div class='mw-search-result-heading'>" .
888  "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
889  "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
890  "</li>\n";
891  }
892 
893  return $html;
894  }
895 
899  protected function getCustomCaptions() {
900  if ( is_null( $this->customCaptions ) ) {
901  $this->customCaptions = [];
902  // format per line <iwprefix>:<caption>
903  $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
904  foreach ( $customLines as $line ) {
905  $parts = explode( ":", $line, 2 );
906  if ( count( $parts ) == 2 ) { // validate line
907  $this->customCaptions[$parts[0]] = $parts[1];
908  }
909  }
910  }
911  }
912 
921  protected function showInterwiki( $matches, $query ) {
923 
924  $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
925  $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
926  $out .= "<ul class='mw-search-iwresults'>\n";
927 
928  // work out custom project captions
929  $this->getCustomCaptions();
930 
931  if ( !is_array( $matches ) ) {
932  $matches = [ $matches ];
933  }
934 
935  foreach ( $matches as $set ) {
936  $prev = null;
937  $result = $set->next();
938  while ( $result ) {
939  $out .= $this->showInterwikiHit( $result, $prev, $query );
940  $prev = $result->getInterwikiPrefix();
941  $result = $set->next();
942  }
943  }
944 
945  // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
946  $out .= "</ul></div>\n";
947 
948  // convert the whole thing to desired language variant
949  $out = $wgContLang->convert( $out );
950 
951  return $out;
952  }
953 
963  protected function showInterwikiHit( $result, $lastInterwiki, $query ) {
964 
965  if ( $result->isBrokenTitle() ) {
966  return '';
967  }
968 
969  $title = $result->getTitle();
970 
971  $titleSnippet = $result->getTitleSnippet();
972 
973  if ( $titleSnippet == '' ) {
974  $titleSnippet = null;
975  }
976 
978  $title,
979  $titleSnippet
980  );
981 
982  // format redirect if any
983  $redirectTitle = $result->getRedirectTitle();
984  $redirectText = $result->getRedirectSnippet();
985  $redirect = '';
986  if ( !is_null( $redirectTitle ) ) {
987  if ( $redirectText == '' ) {
988  $redirectText = null;
989  }
990 
991  $redirect = "<span class='searchalttitle'>" .
992  $this->msg( 'search-redirect' )->rawParams(
993  Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
994  "</span>";
995  }
996 
997  $out = "";
998  // display project name
999  if ( is_null( $lastInterwiki ) || $lastInterwiki != $title->getInterwiki() ) {
1000  if ( array_key_exists( $title->getInterwiki(), $this->customCaptions ) ) {
1001  // captions from 'search-interwiki-custom'
1002  $caption = $this->customCaptions[$title->getInterwiki()];
1003  } else {
1004  // default is to show the hostname of the other wiki which might suck
1005  // if there are many wikis on one hostname
1006  $parsed = wfParseUrl( $title->getFullURL() );
1007  $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
1008  }
1009  // "more results" link (special page stuff could be localized, but we might not know target lang)
1010  $searchTitle = Title::newFromText( $title->getInterwiki() . ":Special:Search" );
1011  $searchLink = Linker::linkKnown(
1012  $searchTitle,
1013  $this->msg( 'search-interwiki-more' )->text(),
1014  [],
1015  [
1016  'search' => $query,
1017  'fulltext' => 'Search'
1018  ]
1019  );
1020  $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
1021  {$searchLink}</span>{$caption}</div>\n<ul>";
1022  }
1023 
1024  $out .= "<li>{$link} {$redirect}</li>\n";
1025 
1026  return $out;
1027  }
1028 
1036  protected function powerSearchBox( $term, $opts ) {
1038 
1039  // Groups namespaces into rows according to subject
1040  $rows = [];
1041  foreach ( $this->searchConfig->searchableNamespaces() as $namespace => $name ) {
1042  $subject = MWNamespace::getSubject( $namespace );
1043  if ( !array_key_exists( $subject, $rows ) ) {
1044  $rows[$subject] = "";
1045  }
1046 
1047  $name = $wgContLang->getConverter()->convertNamespace( $namespace );
1048  if ( $name == '' ) {
1049  $name = $this->msg( 'blanknamespace' )->text();
1050  }
1051 
1052  $rows[$subject] .=
1053  Xml::openElement( 'td' ) .
1055  $name,
1056  "ns{$namespace}",
1057  "mw-search-ns{$namespace}",
1058  in_array( $namespace, $this->namespaces )
1059  ) .
1060  Xml::closeElement( 'td' );
1061  }
1062 
1063  $rows = array_values( $rows );
1064  $numRows = count( $rows );
1065 
1066  // Lays out namespaces in multiple floating two-column tables so they'll
1067  // be arranged nicely while still accommodating different screen widths
1068  $namespaceTables = '';
1069  for ( $i = 0; $i < $numRows; $i += 4 ) {
1070  $namespaceTables .= Xml::openElement( 'table' );
1071 
1072  for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
1073  $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
1074  }
1075 
1076  $namespaceTables .= Xml::closeElement( 'table' );
1077  }
1078 
1079  $showSections = [ 'namespaceTables' => $namespaceTables ];
1080 
1081  Hooks::run( 'SpecialSearchPowerBox', [ &$showSections, $term, $opts ] );
1082 
1083  $hidden = '';
1084  foreach ( $opts as $key => $value ) {
1085  $hidden .= Html::hidden( $key, $value );
1086  }
1087 
1088  # Stuff to feed saveNamespaces()
1089  $remember = '';
1090  $user = $this->getUser();
1091  if ( $user->isLoggedIn() ) {
1092  $remember .= Xml::checkLabel(
1093  $this->msg( 'powersearch-remember' )->text(),
1094  'nsRemember',
1095  'mw-search-powersearch-remember',
1096  false,
1097  // The token goes here rather than in a hidden field so it
1098  // is only sent when necessary (not every form submission).
1099  [ 'value' => $user->getEditToken(
1100  'searchnamespace',
1101  $this->getRequest()
1102  ) ]
1103  );
1104  }
1105 
1106  // Return final output
1107  return Xml::openElement( 'fieldset', [ 'id' => 'mw-searchoptions' ] ) .
1108  Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1109  Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1110  Xml::element( 'div', [ 'id' => 'mw-search-togglebox' ], '', false ) .
1111  Xml::element( 'div', [ 'class' => 'divider' ], '', false ) .
1112  implode( Xml::element( 'div', [ 'class' => 'divider' ], '', false ), $showSections ) .
1113  $hidden .
1114  Xml::element( 'div', [ 'class' => 'divider' ], '', false ) .
1115  $remember .
1116  Xml::closeElement( 'fieldset' );
1117  }
1118 
1122  protected function getSearchProfiles() {
1123  // Builds list of Search Types (profiles)
1124  $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
1125  $defaultNs = $this->searchConfig->defaultNamespaces();
1126  $profiles = [
1127  'default' => [
1128  'message' => 'searchprofile-articles',
1129  'tooltip' => 'searchprofile-articles-tooltip',
1130  'namespaces' => $defaultNs,
1131  'namespace-messages' => $this->searchConfig->namespacesAsText(
1132  $defaultNs
1133  ),
1134  ],
1135  'images' => [
1136  'message' => 'searchprofile-images',
1137  'tooltip' => 'searchprofile-images-tooltip',
1138  'namespaces' => [ NS_FILE ],
1139  ],
1140  'all' => [
1141  'message' => 'searchprofile-everything',
1142  'tooltip' => 'searchprofile-everything-tooltip',
1143  'namespaces' => $nsAllSet,
1144  ],
1145  'advanced' => [
1146  'message' => 'searchprofile-advanced',
1147  'tooltip' => 'searchprofile-advanced-tooltip',
1148  'namespaces' => self::NAMESPACES_CURRENT,
1149  ]
1150  ];
1151 
1152  Hooks::run( 'SpecialSearchProfiles', [ &$profiles ] );
1153 
1154  foreach ( $profiles as &$data ) {
1155  if ( !is_array( $data['namespaces'] ) ) {
1156  continue;
1157  }
1158  sort( $data['namespaces'] );
1159  }
1160 
1161  return $profiles;
1162  }
1163 
1168  protected function searchProfileTabs( $term ) {
1169  $out = Html::element( 'div', [ 'class' => 'mw-search-visualclear' ] ) .
1170  Xml::openElement( 'div', [ 'class' => 'mw-search-profile-tabs' ] );
1171 
1172  $bareterm = $term;
1173  if ( $this->startsWithImage( $term ) ) {
1174  // Deletes prefixes
1175  $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1176  }
1177 
1178  $profiles = $this->getSearchProfiles();
1179  $lang = $this->getLanguage();
1180 
1181  // Outputs XML for Search Types
1182  $out .= Xml::openElement( 'div', [ 'class' => 'search-types' ] );
1183  $out .= Xml::openElement( 'ul' );
1184  foreach ( $profiles as $id => $profile ) {
1185  if ( !isset( $profile['parameters'] ) ) {
1186  $profile['parameters'] = [];
1187  }
1188  $profile['parameters']['profile'] = $id;
1189 
1190  $tooltipParam = isset( $profile['namespace-messages'] ) ?
1191  $lang->commaList( $profile['namespace-messages'] ) : null;
1192  $out .= Xml::tags(
1193  'li',
1194  [
1195  'class' => $this->profile === $id ? 'current' : 'normal'
1196  ],
1197  $this->makeSearchLink(
1198  $bareterm,
1199  [],
1200  $this->msg( $profile['message'] )->text(),
1201  $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1202  $profile['parameters']
1203  )
1204  );
1205  }
1206  $out .= Xml::closeElement( 'ul' );
1207  $out .= Xml::closeElement( 'div' );
1208  $out .= Xml::element( 'div', [ 'style' => 'clear:both' ], '', false );
1209  $out .= Xml::closeElement( 'div' );
1210 
1211  return $out;
1212  }
1213 
1218  protected function searchOptions( $term ) {
1219  $out = '';
1220  $opts = [];
1221  $opts['profile'] = $this->profile;
1222 
1223  if ( $this->isPowerSearch() ) {
1224  $out .= $this->powerSearchBox( $term, $opts );
1225  } else {
1226  $form = '';
1227  Hooks::run( 'SpecialSearchProfileForm', [ $this, &$form, $this->profile, $term, $opts ] );
1228  $out .= $form;
1229  }
1230 
1231  return $out;
1232  }
1233 
1240  protected function shortDialog( $term, $resultsShown, $totalNum ) {
1241  $searchWidget = new MediaWiki\Widget\SearchInputWidget( [
1242  'id' => 'searchText',
1243  'name' => 'search',
1244  'autofocus' => trim( $term ) === '',
1245  'value' => $term,
1246  'dataLocation' => 'content',
1247  'infusable' => true,
1248  ] );
1249 
1250  $layout = new OOUI\ActionFieldLayout( $searchWidget, new OOUI\ButtonInputWidget( [
1251  'type' => 'submit',
1252  'label' => $this->msg( 'searchbutton' )->text(),
1253  'flags' => [ 'progressive', 'primary' ],
1254  ] ), [
1255  'align' => 'top',
1256  ] );
1257 
1258  $out =
1259  Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
1260  Html::hidden( 'profile', $this->profile ) .
1261  Html::hidden( 'fulltext', 'Search' ) .
1262  $layout;
1263 
1264  // Results-info
1265  if ( $totalNum > 0 && $this->offset < $totalNum ) {
1266  $top = $this->msg( 'search-showingresults' )
1267  ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1268  ->numParams( $resultsShown )
1269  ->parse();
1270  $out .= Xml::tags( 'div', [ 'class' => 'results-info' ], $top );
1271  }
1272 
1273  return $out;
1274  }
1275 
1286  protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = [] ) {
1287  $opt = $params;
1288  foreach ( $namespaces as $n ) {
1289  $opt['ns' . $n] = 1;
1290  }
1291 
1292  $stParams = array_merge(
1293  [
1294  'search' => $term,
1295  'fulltext' => $this->msg( 'search' )->text()
1296  ],
1297  $opt
1298  );
1299 
1300  return Xml::element(
1301  'a',
1302  [
1303  'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1304  'title' => $tooltip
1305  ],
1306  $label
1307  );
1308  }
1309 
1316  protected function startsWithImage( $term ) {
1318 
1319  $parts = explode( ':', $term );
1320  if ( count( $parts ) > 1 ) {
1321  return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1322  }
1323 
1324  return false;
1325  }
1326 
1333  protected function startsWithAll( $term ) {
1334 
1335  $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1336 
1337  $parts = explode( ':', $term );
1338  if ( count( $parts ) > 1 ) {
1339  return $parts[0] == $allkeyword;
1340  }
1341 
1342  return false;
1343  }
1344 
1350  public function getSearchEngine() {
1351  if ( $this->searchEngine === null ) {
1352  $this->searchEngine = $this->searchEngineType ?
1353  MediaWikiServices::getInstance()->getSearchEngineFactory()->create( $this->searchEngineType ) :
1354  MediaWikiServices::getInstance()->newSearchEngine();
1355  }
1356 
1357  return $this->searchEngine;
1358  }
1359 
1364  function getProfile() {
1365  return $this->profile;
1366  }
1367 
1372  function getNamespaces() {
1373  return $this->namespaces;
1374  }
1375 
1385  public function setExtraParam( $key, $value ) {
1386  $this->extraParams[$key] = $value;
1387  }
1388 
1389  protected function getGroupName() {
1390  return 'pages';
1391  }
1392 }
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:2598
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:1816
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:776
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:1435
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
showHit($result, $terms, $position)
Format a single hit result.
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.
static rawElement($element, $attribs=[], $contents= '')
Returns an HTML element in a string.
Definition: Html.php:210
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:749
Generic operation result class Has warning/error list, boolean status and arbitrary value...
Definition: Status.php:40
execute($par)
Entry point.
$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.
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:256
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:1814
outputHeader($summaryMessageKey= '')
Outputs a summary message on top of special pages Per default the message key is the canonical name o...
the value to return A Title object or null for latest to be modified or replaced by the hook handler or if authentication is not possible after cache objects are set for highlighting & $link
Definition: hooks.txt:2621
static addCallableUpdate($callable, $type=self::POSTSEND)
Add a callable update.
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.
Some quick notes on the file repository architecture Functionality is
Definition: README:3
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
$params
string $mPrefix
The prefix url parameter.
const NS_CATEGORY
Definition: Defines.php:83
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes! ...
Allows to change the fields on the form that will be generated are created Can be used to omit specific feeds from being outputted You must not use this hook to add use OutputPage::addFeedLink() instead.&$feedLinks conditions will AND in the final query as a Content object as a Content object $title
Definition: hooks.txt:312
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:75
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
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:2755
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.
showMatches(&$matches, $interwiki=null)
Show whole set of results.
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:2458
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:990
$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
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:230
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.
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:310