MediaWiki  1.29.1
Linker.php
Go to the documentation of this file.
1 <?php
24 
34 class Linker {
38  const TOOL_LINKS_NOBLOCK = 1;
39  const TOOL_LINKS_EMAIL = 2;
40 
51  public static function getLinkColour( LinkTarget $t, $threshold ) {
52  wfDeprecated( __METHOD__, '1.28' );
53  $services = MediaWikiServices::getInstance();
54  $linkRenderer = $services->getLinkRenderer();
55  if ( $threshold !== $linkRenderer->getStubThreshold() ) {
56  // Need to create a new instance with the right stub threshold...
57  $linkRenderer = $services->getLinkRendererFactory()->create();
58  $linkRenderer->setStubThreshold( $threshold );
59  }
60 
61  return $linkRenderer->getLinkClasses( $t );
62  }
63 
107  public static function link(
108  $target, $html = null, $customAttribs = [], $query = [], $options = []
109  ) {
110  if ( !$target instanceof Title ) {
111  wfWarn( __METHOD__ . ': Requires $target to be a Title object.', 2 );
112  return "<!-- ERROR -->$html";
113  }
114 
115  if ( is_string( $query ) ) {
116  // some functions withing core using this still hand over query strings
117  wfDeprecated( __METHOD__ . ' with parameter $query as string (should be array)', '1.20' );
119  }
120 
121  $services = MediaWikiServices::getInstance();
123  if ( $options ) {
124  // Custom options, create new LinkRenderer
125  if ( !isset( $options['stubThreshold'] ) ) {
126  $defaultLinkRenderer = $services->getLinkRenderer();
127  $options['stubThreshold'] = $defaultLinkRenderer->getStubThreshold();
128  }
129  $linkRenderer = $services->getLinkRendererFactory()
130  ->createFromLegacyOptions( $options );
131  } else {
132  $linkRenderer = $services->getLinkRenderer();
133  }
134 
135  if ( $html !== null ) {
136  $text = new HtmlArmor( $html );
137  } else {
138  $text = $html; // null
139  }
140  if ( in_array( 'known', $options, true ) ) {
141  return $linkRenderer->makeKnownLink( $target, $text, $customAttribs, $query );
142  } elseif ( in_array( 'broken', $options, true ) ) {
143  return $linkRenderer->makeBrokenLink( $target, $text, $customAttribs, $query );
144  } elseif ( in_array( 'noclasses', $options, true ) ) {
145  return $linkRenderer->makePreloadedLink( $target, $text, '', $customAttribs, $query );
146  } else {
147  return $linkRenderer->makeLink( $target, $text, $customAttribs, $query );
148  }
149  }
150 
159  public static function linkKnown(
160  $target, $html = null, $customAttribs = [],
161  $query = [], $options = [ 'known' ]
162  ) {
163  return self::link( $target, $html, $customAttribs, $query, $options );
164  }
165 
181  public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
182  $ret = "<a class=\"mw-selflink selflink\">{$prefix}{$html}</a>{$trail}";
183  if ( !Hooks::run( 'SelfLinkBegin', [ $nt, &$html, &$trail, &$prefix, &$ret ] ) ) {
184  return $ret;
185  }
186 
187  if ( $html == '' ) {
188  $html = htmlspecialchars( $nt->getPrefixedText() );
189  }
190  list( $inside, $trail ) = self::splitTrail( $trail );
191  return "<a class=\"mw-selflink selflink\">{$prefix}{$html}{$inside}</a>{$trail}";
192  }
193 
204  public static function getInvalidTitleDescription( IContextSource $context, $namespace, $title ) {
206 
207  // First we check whether the namespace exists or not.
208  if ( MWNamespace::exists( $namespace ) ) {
209  if ( $namespace == NS_MAIN ) {
210  $name = $context->msg( 'blanknamespace' )->text();
211  } else {
212  $name = $wgContLang->getFormattedNsText( $namespace );
213  }
214  return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
215  } else {
216  return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
217  }
218  }
219 
225  public static function normaliseSpecialPage( LinkTarget $target ) {
226  if ( $target->getNamespace() == NS_SPECIAL && !$target->isExternal() ) {
227  list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $target->getDBkey() );
228  if ( !$name ) {
229  return $target;
230  }
231  $ret = SpecialPage::getTitleValueFor( $name, $subpage, $target->getFragment() );
232  return $ret;
233  } else {
234  return $target;
235  }
236  }
237 
246  private static function fnamePart( $url ) {
247  $basename = strrchr( $url, '/' );
248  if ( false === $basename ) {
249  $basename = $url;
250  } else {
251  $basename = substr( $basename, 1 );
252  }
253  return $basename;
254  }
255 
266  public static function makeExternalImage( $url, $alt = '' ) {
267  if ( $alt == '' ) {
268  $alt = self::fnamePart( $url );
269  }
270  $img = '';
271  $success = Hooks::run( 'LinkerMakeExternalImage', [ &$url, &$alt, &$img ] );
272  if ( !$success ) {
273  wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
274  . "with url {$url} and alt text {$alt} to {$img}\n", true );
275  return $img;
276  }
277  return Html::element( 'img',
278  [
279  'src' => $url,
280  'alt' => $alt ] );
281  }
282 
319  public static function makeImageLink( Parser $parser, Title $title,
320  $file, $frameParams = [], $handlerParams = [], $time = false,
321  $query = "", $widthOption = null
322  ) {
323  $res = null;
324  $dummy = new DummyLinker;
325  if ( !Hooks::run( 'ImageBeforeProduceHTML', [ &$dummy, &$title,
326  &$file, &$frameParams, &$handlerParams, &$time, &$res ] ) ) {
327  return $res;
328  }
329 
330  if ( $file && !$file->allowInlineDisplay() ) {
331  wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
332  return self::link( $title );
333  }
334 
335  // Clean up parameters
336  $page = isset( $handlerParams['page'] ) ? $handlerParams['page'] : false;
337  if ( !isset( $frameParams['align'] ) ) {
338  $frameParams['align'] = '';
339  }
340  if ( !isset( $frameParams['alt'] ) ) {
341  $frameParams['alt'] = '';
342  }
343  if ( !isset( $frameParams['title'] ) ) {
344  $frameParams['title'] = '';
345  }
346  if ( !isset( $frameParams['class'] ) ) {
347  $frameParams['class'] = '';
348  }
349 
350  $prefix = $postfix = '';
351 
352  if ( 'center' == $frameParams['align'] ) {
353  $prefix = '<div class="center">';
354  $postfix = '</div>';
355  $frameParams['align'] = 'none';
356  }
357  if ( $file && !isset( $handlerParams['width'] ) ) {
358  if ( isset( $handlerParams['height'] ) && $file->isVectorized() ) {
359  // If its a vector image, and user only specifies height
360  // we don't want it to be limited by its "normal" width.
362  $handlerParams['width'] = $wgSVGMaxSize;
363  } else {
364  $handlerParams['width'] = $file->getWidth( $page );
365  }
366 
367  if ( isset( $frameParams['thumbnail'] )
368  || isset( $frameParams['manualthumb'] )
369  || isset( $frameParams['framed'] )
370  || isset( $frameParams['frameless'] )
371  || !$handlerParams['width']
372  ) {
374 
375  if ( $widthOption === null || !isset( $wgThumbLimits[$widthOption] ) ) {
376  $widthOption = User::getDefaultOption( 'thumbsize' );
377  }
378 
379  // Reduce width for upright images when parameter 'upright' is used
380  if ( isset( $frameParams['upright'] ) && $frameParams['upright'] == 0 ) {
381  $frameParams['upright'] = $wgThumbUpright;
382  }
383 
384  // For caching health: If width scaled down due to upright
385  // parameter, round to full __0 pixel to avoid the creation of a
386  // lot of odd thumbs.
387  $prefWidth = isset( $frameParams['upright'] ) ?
388  round( $wgThumbLimits[$widthOption] * $frameParams['upright'], -1 ) :
389  $wgThumbLimits[$widthOption];
390 
391  // Use width which is smaller: real image width or user preference width
392  // Unless image is scalable vector.
393  if ( !isset( $handlerParams['height'] ) && ( $handlerParams['width'] <= 0 ||
394  $prefWidth < $handlerParams['width'] || $file->isVectorized() ) ) {
395  $handlerParams['width'] = $prefWidth;
396  }
397  }
398  }
399 
400  if ( isset( $frameParams['thumbnail'] ) || isset( $frameParams['manualthumb'] )
401  || isset( $frameParams['framed'] )
402  ) {
403  # Create a thumbnail. Alignment depends on the writing direction of
404  # the page content language (right-aligned for LTR languages,
405  # left-aligned for RTL languages)
406  # If a thumbnail width has not been provided, it is set
407  # to the default user option as specified in Language*.php
408  if ( $frameParams['align'] == '' ) {
409  $frameParams['align'] = $parser->getTargetLanguage()->alignEnd();
410  }
411  return $prefix .
412  self::makeThumbLink2( $title, $file, $frameParams, $handlerParams, $time, $query ) .
413  $postfix;
414  }
415 
416  if ( $file && isset( $frameParams['frameless'] ) ) {
417  $srcWidth = $file->getWidth( $page );
418  # For "frameless" option: do not present an image bigger than the
419  # source (for bitmap-style images). This is the same behavior as the
420  # "thumb" option does it already.
421  if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
422  $handlerParams['width'] = $srcWidth;
423  }
424  }
425 
426  if ( $file && isset( $handlerParams['width'] ) ) {
427  # Create a resized image, without the additional thumbnail features
428  $thumb = $file->transform( $handlerParams );
429  } else {
430  $thumb = false;
431  }
432 
433  if ( !$thumb ) {
434  $s = self::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
435  } else {
437  $params = [
438  'alt' => $frameParams['alt'],
439  'title' => $frameParams['title'],
440  'valign' => isset( $frameParams['valign'] ) ? $frameParams['valign'] : false,
441  'img-class' => $frameParams['class'] ];
442  if ( isset( $frameParams['border'] ) ) {
443  $params['img-class'] .= ( $params['img-class'] !== '' ? ' ' : '' ) . 'thumbborder';
444  }
446 
447  $s = $thumb->toHtml( $params );
448  }
449  if ( $frameParams['align'] != '' ) {
450  $s = "<div class=\"float{$frameParams['align']}\">{$s}</div>";
451  }
452  return str_replace( "\n", ' ', $prefix . $s . $postfix );
453  }
454 
463  private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
464  $mtoParams = [];
465  if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
466  $mtoParams['custom-url-link'] = $frameParams['link-url'];
467  if ( isset( $frameParams['link-target'] ) ) {
468  $mtoParams['custom-target-link'] = $frameParams['link-target'];
469  }
470  if ( $parser ) {
471  $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
472  foreach ( $extLinkAttrs as $name => $val ) {
473  // Currently could include 'rel' and 'target'
474  $mtoParams['parser-extlink-' . $name] = $val;
475  }
476  }
477  } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
478  $mtoParams['custom-title-link'] = Title::newFromLinkTarget(
479  self::normaliseSpecialPage( $frameParams['link-title'] )
480  );
481  } elseif ( !empty( $frameParams['no-link'] ) ) {
482  // No link
483  } else {
484  $mtoParams['desc-link'] = true;
485  $mtoParams['desc-query'] = $query;
486  }
487  return $mtoParams;
488  }
489 
502  public static function makeThumbLinkObj( Title $title, $file, $label = '', $alt,
503  $align = 'right', $params = [], $framed = false, $manualthumb = ""
504  ) {
505  $frameParams = [
506  'alt' => $alt,
507  'caption' => $label,
508  'align' => $align
509  ];
510  if ( $framed ) {
511  $frameParams['framed'] = true;
512  }
513  if ( $manualthumb ) {
514  $frameParams['manualthumb'] = $manualthumb;
515  }
516  return self::makeThumbLink2( $title, $file, $frameParams, $params );
517  }
518 
528  public static function makeThumbLink2( Title $title, $file, $frameParams = [],
529  $handlerParams = [], $time = false, $query = ""
530  ) {
531  $exists = $file && $file->exists();
532 
533  $page = isset( $handlerParams['page'] ) ? $handlerParams['page'] : false;
534  if ( !isset( $frameParams['align'] ) ) {
535  $frameParams['align'] = 'right';
536  }
537  if ( !isset( $frameParams['alt'] ) ) {
538  $frameParams['alt'] = '';
539  }
540  if ( !isset( $frameParams['title'] ) ) {
541  $frameParams['title'] = '';
542  }
543  if ( !isset( $frameParams['caption'] ) ) {
544  $frameParams['caption'] = '';
545  }
546 
547  if ( empty( $handlerParams['width'] ) ) {
548  // Reduce width for upright images when parameter 'upright' is used
549  $handlerParams['width'] = isset( $frameParams['upright'] ) ? 130 : 180;
550  }
551  $thumb = false;
552  $noscale = false;
553  $manualthumb = false;
554 
555  if ( !$exists ) {
556  $outerWidth = $handlerParams['width'] + 2;
557  } else {
558  if ( isset( $frameParams['manualthumb'] ) ) {
559  # Use manually specified thumbnail
560  $manual_title = Title::makeTitleSafe( NS_FILE, $frameParams['manualthumb'] );
561  if ( $manual_title ) {
562  $manual_img = wfFindFile( $manual_title );
563  if ( $manual_img ) {
564  $thumb = $manual_img->getUnscaledThumb( $handlerParams );
565  $manualthumb = true;
566  } else {
567  $exists = false;
568  }
569  }
570  } elseif ( isset( $frameParams['framed'] ) ) {
571  // Use image dimensions, don't scale
572  $thumb = $file->getUnscaledThumb( $handlerParams );
573  $noscale = true;
574  } else {
575  # Do not present an image bigger than the source, for bitmap-style images
576  # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
577  $srcWidth = $file->getWidth( $page );
578  if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
579  $handlerParams['width'] = $srcWidth;
580  }
581  $thumb = $file->transform( $handlerParams );
582  }
583 
584  if ( $thumb ) {
585  $outerWidth = $thumb->getWidth() + 2;
586  } else {
587  $outerWidth = $handlerParams['width'] + 2;
588  }
589  }
590 
591  # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
592  # So we don't need to pass it here in $query. However, the URL for the
593  # zoom icon still needs it, so we make a unique query for it. See T16771
594  $url = $title->getLocalURL( $query );
595  if ( $page ) {
596  $url = wfAppendQuery( $url, [ 'page' => $page ] );
597  }
598  if ( $manualthumb
599  && !isset( $frameParams['link-title'] )
600  && !isset( $frameParams['link-url'] )
601  && !isset( $frameParams['no-link'] ) ) {
602  $frameParams['link-url'] = $url;
603  }
604 
605  $s = "<div class=\"thumb t{$frameParams['align']}\">"
606  . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
607 
608  if ( !$exists ) {
609  $s .= self::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
610  $zoomIcon = '';
611  } elseif ( !$thumb ) {
612  $s .= wfMessage( 'thumbnail_error', '' )->escaped();
613  $zoomIcon = '';
614  } else {
615  if ( !$noscale && !$manualthumb ) {
617  }
618  $params = [
619  'alt' => $frameParams['alt'],
620  'title' => $frameParams['title'],
621  'img-class' => ( isset( $frameParams['class'] ) && $frameParams['class'] !== ''
622  ? $frameParams['class'] . ' '
623  : '' ) . 'thumbimage'
624  ];
625  $params = self::getImageLinkMTOParams( $frameParams, $query ) + $params;
626  $s .= $thumb->toHtml( $params );
627  if ( isset( $frameParams['framed'] ) ) {
628  $zoomIcon = "";
629  } else {
630  $zoomIcon = Html::rawElement( 'div', [ 'class' => 'magnify' ],
631  Html::rawElement( 'a', [
632  'href' => $url,
633  'class' => 'internal',
634  'title' => wfMessage( 'thumbnail-more' )->text() ],
635  "" ) );
636  }
637  }
638  $s .= ' <div class="thumbcaption">' . $zoomIcon . $frameParams['caption'] . "</div></div></div>";
639  return str_replace( "\n", ' ', $s );
640  }
641 
650  public static function processResponsiveImages( $file, $thumb, $hp ) {
652  if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
653  $hp15 = $hp;
654  $hp15['width'] = round( $hp['width'] * 1.5 );
655  $hp20 = $hp;
656  $hp20['width'] = $hp['width'] * 2;
657  if ( isset( $hp['height'] ) ) {
658  $hp15['height'] = round( $hp['height'] * 1.5 );
659  $hp20['height'] = $hp['height'] * 2;
660  }
661 
662  $thumb15 = $file->transform( $hp15 );
663  $thumb20 = $file->transform( $hp20 );
664  if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
665  $thumb->responsiveUrls['1.5'] = $thumb15->getUrl();
666  }
667  if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
668  $thumb->responsiveUrls['2'] = $thumb20->getUrl();
669  }
670  }
671  }
672 
685  public static function makeBrokenImageLinkObj( $title, $label = '',
686  $query = '', $unused1 = '', $unused2 = '', $time = false
687  ) {
688  if ( !$title instanceof Title ) {
689  wfWarn( __METHOD__ . ': Requires $title to be a Title object.' );
690  return "<!-- ERROR -->" . htmlspecialchars( $label );
691  }
692 
694  if ( $label == '' ) {
695  $label = $title->getPrefixedText();
696  }
697  $encLabel = htmlspecialchars( $label );
698  $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
699 
701  && !$currentExists
702  ) {
703  $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
704 
705  if ( $redir ) {
706  // We already know it's a redirect, so mark it
707  // accordingly
708  return self::link(
709  $title,
710  $encLabel,
711  [ 'class' => 'mw-redirect' ],
712  wfCgiToArray( $query ),
713  [ 'known', 'noclasses' ]
714  );
715  }
716 
717  $href = self::getUploadUrl( $title, $query );
718 
719  return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
720  htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES ) . '">' .
721  $encLabel . '</a>';
722  }
723 
724  return self::link( $title, $encLabel, [], wfCgiToArray( $query ), [ 'known', 'noclasses' ] );
725  }
726 
735  protected static function getUploadUrl( $destFile, $query = '' ) {
737  $q = 'wpDestFile=' . $destFile->getPartialURL();
738  if ( $query != '' ) {
739  $q .= '&' . $query;
740  }
741 
742  if ( $wgUploadMissingFileUrl ) {
744  } elseif ( $wgUploadNavigationUrl ) {
746  } else {
747  $upload = SpecialPage::getTitleFor( 'Upload' );
748  return $upload->getLocalURL( $q );
749  }
750  }
751 
761  public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
762  $img = wfFindFile( $title, [ 'time' => $time ] );
763  return self::makeMediaLinkFile( $title, $img, $html );
764  }
765 
778  public static function makeMediaLinkFile( Title $title, $file, $html = '' ) {
779  if ( $file && $file->exists() ) {
780  $url = $file->getUrl();
781  $class = 'internal';
782  } else {
783  $url = self::getUploadUrl( $title );
784  $class = 'new';
785  }
786 
787  $alt = $title->getText();
788  if ( $html == '' ) {
789  $html = $alt;
790  }
791 
792  $ret = '';
793  $attribs = [
794  'href' => $url,
795  'class' => $class,
796  'title' => $alt
797  ];
798 
799  if ( !Hooks::run( 'LinkerMakeMediaLinkFile',
800  [ $title, $file, &$html, &$attribs, &$ret ] ) ) {
801  wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
802  . "with url {$url} and text {$html} to {$ret}\n", true );
803  return $ret;
804  }
805 
806  return Html::rawElement( 'a', $attribs, $html );
807  }
808 
819  public static function specialLink( $name, $key = '' ) {
820  if ( $key == '' ) {
821  $key = strtolower( $name );
822  }
823 
825  }
826 
838  public static function makeExternalLink( $url, $text, $escape = true,
839  $linktype = '', $attribs = [], $title = null
840  ) {
842  $class = "external";
843  if ( $linktype ) {
844  $class .= " $linktype";
845  }
846  if ( isset( $attribs['class'] ) && $attribs['class'] ) {
847  $class .= " {$attribs['class']}";
848  }
849  $attribs['class'] = $class;
850 
851  if ( $escape ) {
852  $text = htmlspecialchars( $text );
853  }
854 
855  if ( !$title ) {
856  $title = $wgTitle;
857  }
858  $newRel = Parser::getExternalLinkRel( $url, $title );
859  if ( !isset( $attribs['rel'] ) || $attribs['rel'] === '' ) {
860  $attribs['rel'] = $newRel;
861  } elseif ( $newRel !== '' ) {
862  // Merge the rel attributes.
863  $newRels = explode( ' ', $newRel );
864  $oldRels = explode( ' ', $attribs['rel'] );
865  $combined = array_unique( array_merge( $newRels, $oldRels ) );
866  $attribs['rel'] = implode( ' ', $combined );
867  }
868  $link = '';
869  $success = Hooks::run( 'LinkerMakeExternalLink',
870  [ &$url, &$text, &$link, &$attribs, $linktype ] );
871  if ( !$success ) {
872  wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
873  . "with url {$url} and text {$text} to {$link}\n", true );
874  return $link;
875  }
876  $attribs['href'] = $url;
877  return Html::rawElement( 'a', $attribs, $text );
878  }
879 
888  public static function userLink( $userId, $userName, $altUserName = false ) {
889  $classes = 'mw-userlink';
890  if ( $userId == 0 ) {
891  $page = SpecialPage::getTitleFor( 'Contributions', $userName );
892  if ( $altUserName === false ) {
893  $altUserName = IP::prettifyIP( $userName );
894  }
895  $classes .= ' mw-anonuserlink'; // Separate link class for anons (T45179)
896  } else {
897  $page = Title::makeTitle( NS_USER, $userName );
898  }
899 
900  // Wrap the output with <bdi> tags for directionality isolation
901  return self::link(
902  $page,
903  '<bdi>' . htmlspecialchars( $altUserName !== false ? $altUserName : $userName ) . '</bdi>',
904  [ 'class' => $classes ]
905  );
906  }
907 
921  public static function userToolLinks(
922  $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
923  ) {
924  global $wgUser, $wgDisableAnonTalk, $wgLang;
925  $talkable = !( $wgDisableAnonTalk && 0 == $userId );
926  $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
927  $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
928 
929  $items = [];
930  if ( $talkable ) {
931  $items[] = self::userTalkLink( $userId, $userText );
932  }
933  if ( $userId ) {
934  // check if the user has an edit
935  $attribs = [];
936  $attribs['class'] = 'mw-usertoollinks-contribs';
937  if ( $redContribsWhenNoEdits ) {
938  if ( intval( $edits ) === 0 && $edits !== 0 ) {
939  $user = User::newFromId( $userId );
940  $edits = $user->getEditCount();
941  }
942  if ( $edits === 0 ) {
943  $attribs['class'] .= ' new';
944  }
945  }
946  $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
947 
948  $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
949  }
950  if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
951  $items[] = self::blockLink( $userId, $userText );
952  }
953 
954  if ( $addEmailLink && $wgUser->canSendEmail() ) {
955  $items[] = self::emailLink( $userId, $userText );
956  }
957 
958  Hooks::run( 'UserToolLinksEdit', [ $userId, $userText, &$items ] );
959 
960  if ( $items ) {
961  return wfMessage( 'word-separator' )->escaped()
962  . '<span class="mw-usertoollinks">'
963  . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
964  . '</span>';
965  } else {
966  return '';
967  }
968  }
969 
978  public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
979  return self::userToolLinks( $userId, $userText, true, 0, $edits );
980  }
981 
988  public static function userTalkLink( $userId, $userText ) {
989  $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
990  $moreLinkAttribs['class'] = 'mw-usertoollinks-talk';
991  $userTalkLink = self::link( $userTalkPage,
992  wfMessage( 'talkpagelinktext' )->escaped(),
993  $moreLinkAttribs );
994  return $userTalkLink;
995  }
996 
1003  public static function blockLink( $userId, $userText ) {
1004  $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1005  $moreLinkAttribs['class'] = 'mw-usertoollinks-block';
1006  $blockLink = self::link( $blockPage,
1007  wfMessage( 'blocklink' )->escaped(),
1008  $moreLinkAttribs );
1009  return $blockLink;
1010  }
1011 
1017  public static function emailLink( $userId, $userText ) {
1018  $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1019  $moreLinkAttribs['class'] = 'mw-usertoollinks-mail';
1020  $emailLink = self::link( $emailPage,
1021  wfMessage( 'emaillink' )->escaped(),
1022  $moreLinkAttribs );
1023  return $emailLink;
1024  }
1025 
1033  public static function revUserLink( $rev, $isPublic = false ) {
1034  if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1035  $link = wfMessage( 'rev-deleted-user' )->escaped();
1036  } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1038  $rev->getUserText( Revision::FOR_THIS_USER ) );
1039  } else {
1040  $link = wfMessage( 'rev-deleted-user' )->escaped();
1041  }
1042  if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1043  return '<span class="history-deleted">' . $link . '</span>';
1044  }
1045  return $link;
1046  }
1047 
1055  public static function revUserTools( $rev, $isPublic = false ) {
1056  if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1057  $link = wfMessage( 'rev-deleted-user' )->escaped();
1058  } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1059  $userId = $rev->getUser( Revision::FOR_THIS_USER );
1060  $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1061  $link = self::userLink( $userId, $userText )
1062  . self::userToolLinks( $userId, $userText );
1063  } else {
1064  $link = wfMessage( 'rev-deleted-user' )->escaped();
1065  }
1066  if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1067  return ' <span class="history-deleted">' . $link . '</span>';
1068  }
1069  return $link;
1070  }
1071 
1094  public static function formatComment(
1095  $comment, $title = null, $local = false, $wikiId = null
1096  ) {
1097  # Sanitize text a bit:
1098  $comment = str_replace( "\n", " ", $comment );
1099  # Allow HTML entities (for T15815)
1100  $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1101 
1102  # Render autocomments and make links:
1103  $comment = self::formatAutocomments( $comment, $title, $local, $wikiId );
1104  $comment = self::formatLinksInComment( $comment, $title, $local, $wikiId );
1105 
1106  return $comment;
1107  }
1108 
1126  private static function formatAutocomments(
1127  $comment, $title = null, $local = false, $wikiId = null
1128  ) {
1129  // @todo $append here is something of a hack to preserve the status
1130  // quo. Someone who knows more about bidi and such should decide
1131  // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1132  // wiki, both when autocomments exist and when they don't, and
1133  // (2) what markup will make that actually happen.
1134  $append = '';
1135  $comment = preg_replace_callback(
1136  // To detect the presence of content before or after the
1137  // auto-comment, we use capturing groups inside optional zero-width
1138  // assertions. But older versions of PCRE can't directly make
1139  // zero-width assertions optional, so wrap them in a non-capturing
1140  // group.
1141  '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1142  function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1143  global $wgLang;
1144 
1145  // Ensure all match positions are defined
1146  $match += [ '', '', '', '' ];
1147 
1148  $pre = $match[1] !== '';
1149  $auto = $match[2];
1150  $post = $match[3] !== '';
1151  $comment = null;
1152 
1153  Hooks::run(
1154  'FormatAutocomments',
1155  [ &$comment, $pre, $auto, $post, $title, $local, $wikiId ]
1156  );
1157 
1158  if ( $comment === null ) {
1159  $link = '';
1160  if ( $title ) {
1161  $section = $auto;
1162  # Remove links that a user may have manually put in the autosummary
1163  # This could be improved by copying as much of Parser::stripSectionName as desired.
1164  $section = str_replace( '[[:', '', $section );
1165  $section = str_replace( '[[', '', $section );
1166  $section = str_replace( ']]', '', $section );
1167 
1168  $section = Sanitizer::normalizeSectionNameWhitespace( $section ); # T24784
1169  if ( $local ) {
1170  $sectionTitle = Title::newFromText( '#' . $section );
1171  } else {
1172  $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1173  $title->getDBkey(), $section );
1174  }
1175  if ( $sectionTitle ) {
1176  $link = Linker::makeCommentLink( $sectionTitle, $wgLang->getArrow(), $wikiId, 'noclasses' );
1177  } else {
1178  $link = '';
1179  }
1180  }
1181  if ( $pre ) {
1182  # written summary $presep autocomment (summary /* section */)
1183  $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1184  }
1185  if ( $post ) {
1186  # autocomment $postsep written summary (/* section */ summary)
1187  $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1188  }
1189  $auto = '<span class="autocomment">' . $auto . '</span>';
1190  $comment = $pre . $link . $wgLang->getDirMark()
1191  . '<span dir="auto">' . $auto;
1192  $append .= '</span>';
1193  }
1194  return $comment;
1195  },
1196  $comment
1197  );
1198  return $comment . $append;
1199  }
1200 
1219  public static function formatLinksInComment(
1220  $comment, $title = null, $local = false, $wikiId = null
1221  ) {
1222  return preg_replace_callback(
1223  '/
1224  \[\[
1225  :? # ignore optional leading colon
1226  ([^\]|]+) # 1. link target; page names cannot include ] or |
1227  (?:\|
1228  # 2. link text
1229  # Stop matching at ]] without relying on backtracking.
1230  ((?:]?[^\]])*+)
1231  )?
1232  \]\]
1233  ([^[]*) # 3. link trail (the text up until the next link)
1234  /x',
1235  function ( $match ) use ( $title, $local, $wikiId ) {
1237 
1238  $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1239  $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1240 
1241  $comment = $match[0];
1242 
1243  # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1244  if ( strpos( $match[1], '%' ) !== false ) {
1245  $match[1] = strtr(
1246  rawurldecode( $match[1] ),
1247  [ '<' => '&lt;', '>' => '&gt;' ]
1248  );
1249  }
1250 
1251  # Handle link renaming [[foo|text]] will show link as "text"
1252  if ( $match[2] != "" ) {
1253  $text = $match[2];
1254  } else {
1255  $text = $match[1];
1256  }
1257  $submatch = [];
1258  $thelink = null;
1259  if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1260  # Media link; trail not supported.
1261  $linkRegexp = '/\[\[(.*?)\]\]/';
1262  $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1263  if ( $title ) {
1264  $thelink = Linker::makeMediaLinkObj( $title, $text );
1265  }
1266  } else {
1267  # Other kind of link
1268  # Make sure its target is non-empty
1269  if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1270  $match[1] = substr( $match[1], 1 );
1271  }
1272  if ( $match[1] !== false && $match[1] !== '' ) {
1273  if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1274  $trail = $submatch[1];
1275  } else {
1276  $trail = "";
1277  }
1278  $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1279  list( $inside, $trail ) = Linker::splitTrail( $trail );
1280 
1281  $linkText = $text;
1282  $linkTarget = Linker::normalizeSubpageLink( $title, $match[1], $linkText );
1283 
1284  $target = Title::newFromText( $linkTarget );
1285  if ( $target ) {
1286  if ( $target->getText() == '' && !$target->isExternal()
1287  && !$local && $title
1288  ) {
1289  $newTarget = clone $title;
1290  $newTarget->setFragment( '#' . $target->getFragment() );
1291  $target = $newTarget;
1292  }
1293 
1294  $thelink = Linker::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1295  }
1296  }
1297  }
1298  if ( $thelink ) {
1299  // If the link is still valid, go ahead and replace it in!
1300  $comment = preg_replace(
1301  $linkRegexp,
1303  $comment,
1304  1
1305  );
1306  }
1307 
1308  return $comment;
1309  },
1310  $comment
1311  );
1312  }
1313 
1327  public static function makeCommentLink(
1328  Title $title, $text, $wikiId = null, $options = []
1329  ) {
1330  if ( $wikiId !== null && !$title->isExternal() ) {
1333  $wikiId,
1334  $title->getPrefixedText(),
1335  $title->getFragment()
1336  ),
1337  $text,
1338  /* escape = */ false // Already escaped
1339  );
1340  } else {
1341  $link = Linker::link( $title, $text, [], [], $options );
1342  }
1343 
1344  return $link;
1345  }
1346 
1353  public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1354  # Valid link forms:
1355  # Foobar -- normal
1356  # :Foobar -- override special treatment of prefix (images, language links)
1357  # /Foobar -- convert to CurrentPage/Foobar
1358  # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1359  # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1360  # ../Foobar -- convert to CurrentPage/Foobar,
1361  # (from CurrentPage/CurrentSubPage)
1362  # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1363  # (from CurrentPage/CurrentSubPage)
1364 
1365  $ret = $target; # default return value is no change
1366 
1367  # Some namespaces don't allow subpages,
1368  # so only perform processing if subpages are allowed
1369  if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1370  $hash = strpos( $target, '#' );
1371  if ( $hash !== false ) {
1372  $suffix = substr( $target, $hash );
1373  $target = substr( $target, 0, $hash );
1374  } else {
1375  $suffix = '';
1376  }
1377  # T9425
1378  $target = trim( $target );
1379  # Look at the first character
1380  if ( $target != '' && $target[0] === '/' ) {
1381  # / at end means we don't want the slash to be shown
1382  $m = [];
1383  $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1384  if ( $trailingSlashes ) {
1385  $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1386  } else {
1387  $noslash = substr( $target, 1 );
1388  }
1389 
1390  $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1391  if ( $text === '' ) {
1392  $text = $target . $suffix;
1393  } # this might be changed for ugliness reasons
1394  } else {
1395  # check for .. subpage backlinks
1396  $dotdotcount = 0;
1397  $nodotdot = $target;
1398  while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1399  ++$dotdotcount;
1400  $nodotdot = substr( $nodotdot, 3 );
1401  }
1402  if ( $dotdotcount > 0 ) {
1403  $exploded = explode( '/', $contextTitle->getPrefixedText() );
1404  if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1405  $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1406  # / at the end means don't show full path
1407  if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1408  $nodotdot = rtrim( $nodotdot, '/' );
1409  if ( $text === '' ) {
1410  $text = $nodotdot . $suffix;
1411  }
1412  }
1413  $nodotdot = trim( $nodotdot );
1414  if ( $nodotdot != '' ) {
1415  $ret .= '/' . $nodotdot;
1416  }
1417  $ret .= $suffix;
1418  }
1419  }
1420  }
1421  }
1422 
1423  return $ret;
1424  }
1425 
1439  public static function commentBlock(
1440  $comment, $title = null, $local = false, $wikiId = null
1441  ) {
1442  // '*' used to be the comment inserted by the software way back
1443  // in antiquity in case none was provided, here for backwards
1444  // compatibility, acc. to brion -√¶var
1445  if ( $comment == '' || $comment == '*' ) {
1446  return '';
1447  } else {
1448  $formatted = self::formatComment( $comment, $title, $local, $wikiId );
1449  $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1450  return " <span class=\"comment\">$formatted</span>";
1451  }
1452  }
1453 
1464  public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1465  if ( $rev->getComment( Revision::RAW ) == "" ) {
1466  return "";
1467  }
1468  if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1469  $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1470  } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1471  $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1472  $rev->getTitle(), $local );
1473  } else {
1474  $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1475  }
1476  if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1477  return " <span class=\"history-deleted\">$block</span>";
1478  }
1479  return $block;
1480  }
1481 
1487  public static function formatRevisionSize( $size ) {
1488  if ( $size == 0 ) {
1489  $stxt = wfMessage( 'historyempty' )->escaped();
1490  } else {
1491  $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1492  $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1493  }
1494  return "<span class=\"history-size\">$stxt</span>";
1495  }
1496 
1503  public static function tocIndent() {
1504  return "\n<ul>";
1505  }
1506 
1514  public static function tocUnindent( $level ) {
1515  return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1516  }
1517 
1529  public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1530  $classes = "toclevel-$level";
1531  if ( $sectionIndex !== false ) {
1532  $classes .= " tocsection-$sectionIndex";
1533  }
1534  return "\n<li class=\"$classes\"><a href=\"#" .
1535  $anchor . '"><span class="tocnumber">' .
1536  $tocnumber . '</span> <span class="toctext">' .
1537  $tocline . '</span></a>';
1538  }
1539 
1547  public static function tocLineEnd() {
1548  return "</li>\n";
1549  }
1550 
1559  public static function tocList( $toc, $lang = false ) {
1560  $lang = wfGetLangObj( $lang );
1561  $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1562 
1563  return '<div id="toc" class="toc">'
1564  . '<div id="toctitle" class="toctitle"><h2>' . $title . "</h2></div>\n"
1565  . $toc
1566  . "</ul>\n</div>\n";
1567  }
1568 
1577  public static function generateTOC( $tree, $lang = false ) {
1578  $toc = '';
1579  $lastLevel = 0;
1580  foreach ( $tree as $section ) {
1581  if ( $section['toclevel'] > $lastLevel ) {
1582  $toc .= self::tocIndent();
1583  } elseif ( $section['toclevel'] < $lastLevel ) {
1584  $toc .= self::tocUnindent(
1585  $lastLevel - $section['toclevel'] );
1586  } else {
1587  $toc .= self::tocLineEnd();
1588  }
1589 
1590  $toc .= self::tocLine( $section['anchor'],
1591  $section['line'], $section['number'],
1592  $section['toclevel'], $section['index'] );
1593  $lastLevel = $section['toclevel'];
1594  }
1595  $toc .= self::tocLineEnd();
1596  return self::tocList( $toc, $lang );
1597  }
1598 
1615  public static function makeHeadline( $level, $attribs, $anchor, $html,
1616  $link, $legacyAnchor = false
1617  ) {
1618  $ret = "<h$level$attribs"
1619  . "<span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1620  . $link
1621  . "</h$level>";
1622  if ( $legacyAnchor !== false ) {
1623  $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1624  }
1625  return $ret;
1626  }
1627 
1634  static function splitTrail( $trail ) {
1636  $regex = $wgContLang->linkTrail();
1637  $inside = '';
1638  if ( $trail !== '' ) {
1639  $m = [];
1640  if ( preg_match( $regex, $trail, $m ) ) {
1641  $inside = $m[1];
1642  $trail = $m[2];
1643  }
1644  }
1645  return [ $inside, $trail ];
1646  }
1647 
1675  public static function generateRollback( $rev, IContextSource $context = null,
1676  $options = [ 'verify' ]
1677  ) {
1678  if ( $context === null ) {
1680  }
1681 
1682  $editCount = false;
1683  if ( in_array( 'verify', $options, true ) ) {
1684  $editCount = self::getRollbackEditCount( $rev, true );
1685  if ( $editCount === false ) {
1686  return '';
1687  }
1688  }
1689 
1690  $inner = self::buildRollbackLink( $rev, $context, $editCount );
1691 
1692  if ( !in_array( 'noBrackets', $options, true ) ) {
1693  $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1694  }
1695 
1696  return '<span class="mw-rollback-link">' . $inner . '</span>';
1697  }
1698 
1714  public static function getRollbackEditCount( $rev, $verify ) {
1715  global $wgShowRollbackEditCount;
1716  if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
1717  // Nothing has happened, indicate this by returning 'null'
1718  return null;
1719  }
1720 
1721  $dbr = wfGetDB( DB_REPLICA );
1722 
1723  // Up to the value of $wgShowRollbackEditCount revisions are counted
1724  $res = $dbr->select(
1725  'revision',
1726  [ 'rev_user_text', 'rev_deleted' ],
1727  // $rev->getPage() returns null sometimes
1728  [ 'rev_page' => $rev->getTitle()->getArticleID() ],
1729  __METHOD__,
1730  [
1731  'USE INDEX' => [ 'revision' => 'page_timestamp' ],
1732  'ORDER BY' => 'rev_timestamp DESC',
1733  'LIMIT' => $wgShowRollbackEditCount + 1
1734  ]
1735  );
1736 
1737  $editCount = 0;
1738  $moreRevs = false;
1739  foreach ( $res as $row ) {
1740  if ( $rev->getUserText( Revision::RAW ) != $row->rev_user_text ) {
1741  if ( $verify &&
1742  ( $row->rev_deleted & Revision::DELETED_TEXT
1743  || $row->rev_deleted & Revision::DELETED_USER
1744  ) ) {
1745  // If the user or the text of the revision we might rollback
1746  // to is deleted in some way we can't rollback. Similar to
1747  // the sanity checks in WikiPage::commitRollback.
1748  return false;
1749  }
1750  $moreRevs = true;
1751  break;
1752  }
1753  $editCount++;
1754  }
1755 
1756  if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1757  // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1758  // and there weren't any other revisions. That means that the current user is the only
1759  // editor, so we can't rollback
1760  return false;
1761  }
1762  return $editCount;
1763  }
1764 
1774  public static function buildRollbackLink( $rev, IContextSource $context = null,
1775  $editCount = false
1776  ) {
1777  global $wgShowRollbackEditCount, $wgMiserMode;
1778 
1779  // To config which pages are affected by miser mode
1780  $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
1781 
1782  if ( $context === null ) {
1784  }
1785 
1786  $title = $rev->getTitle();
1787  $query = [
1788  'action' => 'rollback',
1789  'from' => $rev->getUserText(),
1790  'token' => $context->getUser()->getEditToken( 'rollback' ),
1791  ];
1792  $attrs = [
1793  'data-mw' => 'interface',
1794  'title' => $context->msg( 'tooltip-rollback' )->text(),
1795  ];
1796  $options = [ 'known', 'noclasses' ];
1797 
1798  if ( $context->getRequest()->getBool( 'bot' ) ) {
1799  $query['bot'] = '1';
1800  $query['hidediff'] = '1'; // T17999
1801  }
1802 
1803  $disableRollbackEditCount = false;
1804  if ( $wgMiserMode ) {
1805  foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1806  if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1807  $disableRollbackEditCount = true;
1808  break;
1809  }
1810  }
1811  }
1812 
1813  if ( !$disableRollbackEditCount
1814  && is_int( $wgShowRollbackEditCount )
1815  && $wgShowRollbackEditCount > 0
1816  ) {
1817  if ( !is_numeric( $editCount ) ) {
1818  $editCount = self::getRollbackEditCount( $rev, false );
1819  }
1820 
1821  if ( $editCount > $wgShowRollbackEditCount ) {
1822  $html = $context->msg( 'rollbacklinkcount-morethan' )
1823  ->numParams( $wgShowRollbackEditCount )->parse();
1824  } else {
1825  $html = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1826  }
1827 
1828  return self::link( $title, $html, $attrs, $query, $options );
1829  } else {
1830  $html = $context->msg( 'rollbacklink' )->escaped();
1831  return self::link( $title, $html, $attrs, $query, $options );
1832  }
1833  }
1834 
1853  public static function formatTemplates( $templates, $preview = false,
1854  $section = false, $more = null
1855  ) {
1856  wfDeprecated( __METHOD__, '1.28' );
1857 
1858  $type = false;
1859  if ( $preview ) {
1860  $type = 'preview';
1861  } elseif ( $section ) {
1862  $type = 'section';
1863  }
1864 
1865  if ( $more instanceof Message ) {
1866  $more = $more->toString();
1867  }
1868 
1869  $formatter = new TemplatesOnThisPageFormatter(
1871  MediaWikiServices::getInstance()->getLinkRenderer()
1872  );
1873  return $formatter->format( $templates, $type, $more );
1874  }
1875 
1884  public static function formatHiddenCategories( $hiddencats ) {
1885 
1886  $outText = '';
1887  if ( count( $hiddencats ) > 0 ) {
1888  # Construct the HTML
1889  $outText = '<div class="mw-hiddenCategoriesExplanation">';
1890  $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
1891  $outText .= "</div><ul>\n";
1892 
1893  foreach ( $hiddencats as $titleObj ) {
1894  # If it's hidden, it must exist - no need to check with a LinkBatch
1895  $outText .= '<li>'
1896  . self::link( $titleObj, null, [], [], 'known' )
1897  . "</li>\n";
1898  }
1899  $outText .= '</ul>';
1900  }
1901  return $outText;
1902  }
1903 
1914  public static function formatSize( $size ) {
1915  wfDeprecated( __METHOD__, '1.28' );
1916 
1917  global $wgLang;
1918  return htmlspecialchars( $wgLang->formatSize( $size ) );
1919  }
1920 
1936  public static function titleAttrib( $name, $options = null, array $msgParams = [] ) {
1937  $message = wfMessage( "tooltip-$name", $msgParams );
1938  if ( !$message->exists() ) {
1939  $tooltip = false;
1940  } else {
1941  $tooltip = $message->text();
1942  # Compatibility: formerly some tooltips had [alt-.] hardcoded
1943  $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1944  # Message equal to '-' means suppress it.
1945  if ( $tooltip == '-' ) {
1946  $tooltip = false;
1947  }
1948  }
1949 
1950  if ( $options == 'withaccess' ) {
1951  $accesskey = self::accesskey( $name );
1952  if ( $accesskey !== false ) {
1953  // Should be build the same as in jquery.accessKeyLabel.js
1954  if ( $tooltip === false || $tooltip === '' ) {
1955  $tooltip = wfMessage( 'brackets', $accesskey )->text();
1956  } else {
1957  $tooltip .= wfMessage( 'word-separator' )->text();
1958  $tooltip .= wfMessage( 'brackets', $accesskey )->text();
1959  }
1960  }
1961  }
1962 
1963  return $tooltip;
1964  }
1965 
1966  public static $accesskeycache;
1967 
1979  public static function accesskey( $name ) {
1980  if ( isset( self::$accesskeycache[$name] ) ) {
1981  return self::$accesskeycache[$name];
1982  }
1983 
1984  $message = wfMessage( "accesskey-$name" );
1985 
1986  if ( !$message->exists() ) {
1987  $accesskey = false;
1988  } else {
1989  $accesskey = $message->plain();
1990  if ( $accesskey === '' || $accesskey === '-' ) {
1991  # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
1992  # attribute, but this is broken for accesskey: that might be a useful
1993  # value.
1994  $accesskey = false;
1995  }
1996  }
1997 
1998  self::$accesskeycache[$name] = $accesskey;
1999  return self::$accesskeycache[$name];
2000  }
2001 
2015  public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
2016  $canHide = $user->isAllowed( 'deleterevision' );
2017  if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2018  return '';
2019  }
2020 
2021  if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
2022  return Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2023  } else {
2024  if ( $rev->getId() ) {
2025  // RevDelete links using revision ID are stable across
2026  // page deletion and undeletion; use when possible.
2027  $query = [
2028  'type' => 'revision',
2029  'target' => $title->getPrefixedDBkey(),
2030  'ids' => $rev->getId()
2031  ];
2032  } else {
2033  // Older deleted entries didn't save a revision ID.
2034  // We have to refer to these by timestamp, ick!
2035  $query = [
2036  'type' => 'archive',
2037  'target' => $title->getPrefixedDBkey(),
2038  'ids' => $rev->getTimestamp()
2039  ];
2040  }
2041  return Linker::revDeleteLink( $query,
2042  $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2043  }
2044  }
2045 
2056  public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2057  $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2058  $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2059  $html = wfMessage( $msgKey )->escaped();
2060  $tag = $restricted ? 'strong' : 'span';
2061  $link = self::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2062  return Xml::tags(
2063  $tag,
2064  [ 'class' => 'mw-revdelundel-link' ],
2065  wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2066  );
2067  }
2068 
2078  public static function revDeleteLinkDisabled( $delete = true ) {
2079  $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2080  $html = wfMessage( $msgKey )->escaped();
2081  $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2082  return Xml::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2083  }
2084 
2085  /* Deprecated methods */
2086 
2096  public static function tooltipAndAccesskeyAttribs( $name, array $msgParams = [] ) {
2097  # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2098  # no attribute" instead of "output '' as value for attribute", this
2099  # would be three lines.
2100  $attribs = [
2101  'title' => self::titleAttrib( $name, 'withaccess', $msgParams ),
2102  'accesskey' => self::accesskey( $name )
2103  ];
2104  if ( $attribs['title'] === false ) {
2105  unset( $attribs['title'] );
2106  }
2107  if ( $attribs['accesskey'] === false ) {
2108  unset( $attribs['accesskey'] );
2109  }
2110  return $attribs;
2111  }
2112 
2120  public static function tooltip( $name, $options = null ) {
2121  # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2122  # no attribute" instead of "output '' as value for attribute", this
2123  # would be two lines.
2124  $tooltip = self::titleAttrib( $name, $options );
2125  if ( $tooltip === false ) {
2126  return '';
2127  }
2128  return Xml::expandAttributes( [
2129  'title' => $tooltip
2130  ] );
2131  }
2132 
2133 }
User\getDefaultOption
static getDefaultOption( $opt)
Get a given default option value.
Definition: User.php:1603
Linker\getImageLinkMTOParams
static getImageLinkMTOParams( $frameParams, $query='', $parser=null)
Get the link parameters for MediaTransformOutput::toHtml() from given frame parameters supplied by th...
Definition: Linker.php:463
Revision\DELETED_USER
const DELETED_USER
Definition: Revision.php:92
Revision\DELETED_RESTRICTED
const DELETED_RESTRICTED
Definition: Revision.php:93
$wgUser
$wgUser
Definition: Setup.php:781
$context
error also a ContextSource you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2612
User\newFromId
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:579
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:265
HtmlArmor
Marks HTML that shouldn't be escaped.
Definition: HtmlArmor.php:28
$wgThumbLimits
$wgThumbLimits
Adjust thumbnails on image pages according to a user setting.
Definition: DefaultSettings.php:1356
Linker\formatLinksInComment
static formatLinksInComment( $comment, $title=null, $local=false, $wikiId=null)
Formats wiki links and media links in text; all other wiki formatting is ignored.
Definition: Linker.php:1219
Linker
Some internal bits split of from Skin.php.
Definition: Linker.php:34
Linker\TOOL_LINKS_NOBLOCK
const TOOL_LINKS_NOBLOCK
Flags for userToolLinks()
Definition: Linker.php:38
Linker\userTalkLink
static userTalkLink( $userId, $userText)
Definition: Linker.php:988
RepoGroup\singleton
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:59
Xml\expandAttributes
static expandAttributes( $attribs)
Given an array of ('attributename' => 'value'), it generates the code to set the XML attributes : att...
Definition: Xml.php:67
Revision\DELETED_COMMENT
const DELETED_COMMENT
Definition: Revision.php:91
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
Linker\userToolLinksRedContribs
static userToolLinksRedContribs( $userId, $userText, $edits=null)
Alias for userToolLinks( $userId, $userText, true );.
Definition: Linker.php:978
Linker\emailLink
static emailLink( $userId, $userText)
Definition: Linker.php:1017
$wgResponsiveImages
$wgResponsiveImages
Generate and use thumbnails suitable for screens with 1.5 and 2.0 pixel densities.
Definition: DefaultSettings.php:1483
ContextSource\msg
msg()
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:187
Linker\revUserLink
static revUserLink( $rev, $isPublic=false)
Generate a user link if the current user is allowed to view it.
Definition: Linker.php:1033
Xml\tags
static tags( $element, $attribs=null, $contents)
Same as Xml::element(), but does not escape contents.
Definition: Xml.php:131
$auto
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers temp or archived zone change it to an object instance and return false override the list derivative used the name of the old file when set the default code will be skipped true if there is text before this autocomment $auto
Definition: hooks.txt:1459
Linker\userLink
static userLink( $userId, $userName, $altUserName=false)
Make user link (or user contributions for unregistered users)
Definition: Linker.php:888
is
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
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:33
Linker\makeSelfLinkObj
static makeSelfLinkObj( $nt, $html='', $query='', $trail='', $prefix='')
Make appropriate markup for a link to the current article.
Definition: Linker.php:181
Linker\generateTOC
static generateTOC( $tree, $lang=false)
Generate a table of contents from a section tree.
Definition: Linker.php:1577
Linker\getUploadUrl
static getUploadUrl( $destFile, $query='')
Get the URL to upload a certain file.
Definition: Linker.php:735
captcha-old.count
count
Definition: captcha-old.py:225
Linker\tocIndent
static tocIndent()
Add another level to the Table of Contents.
Definition: Linker.php:1503
text
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
$wgSVGMaxSize
$wgSVGMaxSize
Don't scale a SVG larger than this.
Definition: DefaultSettings.php:1115
change
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 change
Definition: distributors.txt:9
Linker\getLinkColour
static getLinkColour(LinkTarget $t, $threshold)
Return the CSS colour of a known link.
Definition: Linker.php:51
WikiMap\getForeignURL
static getForeignURL( $wikiID, $page, $fragmentId=null)
Convenience to get a url to a page on a foreign wiki.
Definition: WikiMap.php:168
Linker\fnamePart
static fnamePart( $url)
Returns the filename part of an url.
Definition: Linker.php:246
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
$user
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 account $user
Definition: hooks.txt:246
Linker\specialLink
static specialLink( $name, $key='')
Make a link to a special page given its name and, optionally, a message key from the link text.
Definition: Linker.php:819
StringUtils\escapeRegexReplacement
static escapeRegexReplacement( $string)
Escape a string to make it suitable for inclusion in a preg_replace() replacement parameter.
Definition: StringUtils.php:322
NS_FILE
const NS_FILE
Definition: Defines.php:68
$params
$params
Definition: styleTest.css.php:40
Linker\linkKnown
static linkKnown( $target, $html=null, $customAttribs=[], $query=[], $options=[ 'known'])
Identical to link(), except $options defaults to 'known'.
Definition: Linker.php:159
$s
$s
Definition: mergeMessageFileList.php:188
$linkRenderer
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 after processing after in associative array form before processing starts Return false to skip default processing and return $ret $linkRenderer
Definition: hooks.txt:1956
SpecialPage\getTitleFor
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
Definition: SpecialPage.php:82
Linker\processResponsiveImages
static processResponsiveImages( $file, $thumb, $hp)
Process responsive images: add 1.5x and 2x subimages to the thumbnail, where applicable.
Definition: Linker.php:650
Linker\makeCommentLink
static makeCommentLink(Title $title, $text, $wikiId=null, $options=[])
Generates a link to the given Title.
Definition: Linker.php:1327
$res
$res
Definition: database.txt:21
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:304
$wgTitle
if(! $wgRequest->checkUrlExtension()) if(! $wgEnableAPI) $wgTitle
Definition: api.php:57
ContextSource\getRequest
getRequest()
Get the WebRequest object.
Definition: ContextSource.php:78
$success
$success
Definition: NoLocalSettings.php:44
Linker\getInvalidTitleDescription
static getInvalidTitleDescription(IContextSource $context, $namespace, $title)
Get a message saying that an invalid title was encountered.
Definition: Linker.php:204
$type
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2536
MediaWiki\Linker\LinkTarget\isExternal
isExternal()
Whether this LinkTarget has an interwiki component.
ContextSource\getUser
getUser()
Get the User object.
Definition: ContextSource.php:133
ContextSource\getTitle
getTitle()
Get the Title object.
Definition: ContextSource.php:88
Linker\tocLine
static tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex=false)
parameter level defines if we are on an indentation level
Definition: Linker.php:1529
php
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
Linker\formatHiddenCategories
static formatHiddenCategories( $hiddencats)
Returns HTML for the "hidden categories on this page" list.
Definition: Linker.php:1884
below
controlled by $wgMainCacheType controlled by $wgParserCacheType controlled by $wgMessageCacheType If you set CACHE_NONE to one of the three control default value for MediaWiki still create a but requests to it are no ops and we always fall through to the database If the cache daemon can t be it should also disable itself fairly smoothly By $wgMemc is used but when it is $parserMemc or $messageMemc this is mentioned below
Definition: memcached.txt:96
Revision\FOR_THIS_USER
const FOR_THIS_USER
Definition: Revision.php:99
wfAppendQuery
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
Definition: GlobalFunctions.php:500
Revision
Definition: Revision.php:33
NS_MAIN
const NS_MAIN
Definition: Defines.php:62
$customAttribs
null means default & $customAttribs
Definition: hooks.txt:1956
$query
null for the 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:1572
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:51
Linker\$accesskeycache
static $accesskeycache
Definition: Linker.php:1966
MediaWiki\Linker\LinkTarget\getNamespace
getNamespace()
Get the namespace index.
$html
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:1956
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:934
Linker\makeMediaLinkObj
static makeMediaLinkObj( $title, $html='', $time=false)
Create a direct link to a given uploaded file.
Definition: Linker.php:761
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1128
Linker\generateRollback
static generateRollback( $rev, IContextSource $context=null, $options=[ 'verify'])
Generate a rollback link for a given revision.
Definition: Linker.php:1675
Linker\makeThumbLink2
static makeThumbLink2(Title $title, $file, $frameParams=[], $handlerParams=[], $time=false, $query="")
Definition: Linker.php:528
SpecialPage\getTitleValueFor
static getTitleValueFor( $name, $subpage=false, $fragment='')
Get a localised TitleValue object for a specified special page name.
Definition: SpecialPage.php:97
Title\newFromLinkTarget
static newFromLinkTarget(LinkTarget $linkTarget)
Create a new Title from a LinkTarget.
Definition: Title.php:239
Linker\formatAutocomments
static formatAutocomments( $comment, $title=null, $local=false, $wikiId=null)
Converts autogenerated comments in edit summaries into section links.
Definition: Linker.php:1126
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:3060
reasons
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 in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database etc For and for historical reasons
Definition: design.txt:25
Linker\revUserTools
static revUserTools( $rev, $isPublic=false)
Generate a user tool link cluster if the current user is allowed to view it.
Definition: Linker.php:1055
$page
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2536
Linker\tocList
static tocList( $toc, $lang=false)
Wraps the TOC in a table and provides the hide/collapse javascript.
Definition: Linker.php:1559
$tag
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books $tag
Definition: hooks.txt:1028
Linker\getRollbackEditCount
static getRollbackEditCount( $rev, $verify)
This function will return the number of revisions which a rollback would revert and,...
Definition: Linker.php:1714
$attribs
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 after processing & $attribs
Definition: hooks.txt:1956
not
if not
Definition: COPYING.txt:307
Linker\tocLineEnd
static tocLineEnd()
End a Table Of Contents line.
Definition: Linker.php:1547
wfGetLangObj
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
Definition: GlobalFunctions.php:1321
MWNamespace\hasSubpages
static hasSubpages( $index)
Does the namespace allow subpages?
Definition: MWNamespace.php:330
wfCgiToArray
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
Definition: GlobalFunctions.php:453
Linker\revDeleteLinkDisabled
static revDeleteLinkDisabled( $delete=true)
Creates a dead (show/hide) link for deleting revisions/log entries.
Definition: Linker.php:2078
$wgLang
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 $wgLang
Definition: design.txt:56
$parser
do that in ParserLimitReportFormat instead $parser
Definition: hooks.txt:2536
Linker\makeExternalLink
static makeExternalLink( $url, $text, $escape=true, $linktype='', $attribs=[], $title=null)
Make an external link.
Definition: Linker.php:838
$time
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1769
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:514
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:999
list
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
$services
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition: hooks.txt:2179
Linker\splitTrail
static splitTrail( $trail)
Split a link trail, return the "inside" portion and the remainder of the trail as a two-element array...
Definition: Linker.php:1634
IP\prettifyIP
static prettifyIP( $ip)
Prettify an IP for display to end users.
Definition: IP.php:201
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:538
Linker\revComment
static revComment(Revision $rev, $local=false, $isPublic=false)
Wrap and format the given revision's comment block, if the current user is allowed to view it.
Definition: Linker.php:1464
Linker\blockLink
static blockLink( $userId, $userText)
Definition: Linker.php:1003
NS_USER_TALK
const NS_USER_TALK
Definition: Defines.php:65
value
$status value
Definition: SyntaxHighlight_GeSHi.class.php:309
Linker\normaliseSpecialPage
static normaliseSpecialPage(LinkTarget $target)
Definition: Linker.php:225
TemplatesOnThisPageFormatter
Handles formatting for the "templates used on this page" lists.
Definition: TemplatesOnThisPageFormatter.php:30
Linker\userToolLinks
static userToolLinks( $userId, $userText, $redContribsWhenNoEdits=false, $flags=0, $edits=null)
Generate standard user tool links (talk, contributions, block link, etc.)
Definition: Linker.php:921
Linker\TOOL_LINKS_EMAIL
const TOOL_LINKS_EMAIL
Definition: Linker.php:39
Linker\tooltipAndAccesskeyAttribs
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[])
Returns the attributes for the tooltip and access key.
Definition: Linker.php:2096
NS_MEDIA
const NS_MEDIA
Definition: Defines.php:50
Linker\getRevDeleteLink
static getRevDeleteLink(User $user, Revision $rev, Title $title)
Get a revision-deletion link, or disabled link, or nothing, depending on user permissions & the setti...
Definition: Linker.php:2015
Linker\formatSize
static formatSize( $size)
Definition: Linker.php:1914
Linker\link
static link( $target, $html=null, $customAttribs=[], $query=[], $options=[])
This function returns an HTML link to the given target.
Definition: Linker.php:107
MediaWiki\Linker\LinkTarget\getDBkey
getDBkey()
Get the main part with underscores.
Linker\formatRevisionSize
static formatRevisionSize( $size)
Definition: Linker.php:1487
MediaWiki\Linker\LinkTarget\getFragment
getFragment()
Get the link fragment (i.e.
SpecialPageFactory\resolveAlias
static resolveAlias( $alias)
Given a special page name with a possible subpage, return an array where the first element is the spe...
Definition: SpecialPageFactory.php:338
$ret
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 & $ret
Definition: hooks.txt:1956
Revision\RAW
const RAW
Definition: Revision.php:100
Linker\makeHeadline
static makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor=false)
Create a headline for content.
Definition: Linker.php:1615
Linker\makeImageLink
static makeImageLink(Parser $parser, Title $title, $file, $frameParams=[], $handlerParams=[], $time=false, $query="", $widthOption=null)
Given parameters derived from [[Image:Foo|options...]], generate the HTML that that syntax inserts in...
Definition: Linker.php:319
Linker\formatTemplates
static formatTemplates( $templates, $preview=false, $section=false, $more=null)
Definition: Linker.php:1853
MWNamespace\exists
static exists( $index)
Returns whether the specified namespace exists.
Definition: MWNamespace.php:160
RequestContext\getMain
static getMain()
Static methods.
Definition: RequestContext.php:468
DummyLinker
Definition: DummyLinker.php:6
$wgUploadNavigationUrl
$wgUploadNavigationUrl
Point the upload navigation link to an external URL Useful if you want to use a shared repository by ...
Definition: DefaultSettings.php:798
Linker\titleAttrib
static titleAttrib( $name, $options=null, array $msgParams=[])
Given the id of an interface element, constructs the appropriate title attribute from the system mess...
Definition: Linker.php:1936
wfFindFile
wfFindFile( $title, $options=[])
Find a file.
Definition: GlobalFunctions.php:3101
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:55
Linker\formatComment
static formatComment( $comment, $title=null, $local=false, $wikiId=null)
This function is called by all recent changes variants, by the page history, and by the user contribu...
Definition: Linker.php:1094
$handlerParams
see documentation in includes Linker php for Linker::makeImageLink & $handlerParams
Definition: hooks.txt:1767
Linker\tooltip
static tooltip( $name, $options=null)
Returns raw bits of HTML, use titleAttrib()
Definition: Linker.php:2120
page
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached my talk page
Definition: hooks.txt:2536
Title
Represents a title within MediaWiki.
Definition: Title.php:39
$wgMiserMode
$wgMiserMode
Disable database-intensive features.
Definition: DefaultSettings.php:2144
$dbr
if(! $regexes) $dbr
Definition: cleanup.php:94
$section
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:2929
$rev
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1741
as
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
$wgThumbUpright
$wgThumbUpright
Adjust width of upright images when parameter 'upright' is used This allows a nicer look for upright ...
Definition: DefaultSettings.php:1466
Linker\tocUnindent
static tocUnindent( $level)
Finish one or more sublevels on the Table of Contents.
Definition: Linker.php:1514
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
Linker\makeMediaLinkFile
static makeMediaLinkFile(Title $title, $file, $html='')
Create a direct link to a given uploaded file.
Definition: Linker.php:778
Linker\revDeleteLink
static revDeleteLink( $query=[], $restricted=false, $delete=true)
Creates a (show/hide) link for deleting revisions/log entries.
Definition: Linker.php:2056
$wgEnableUploads
$wgEnableUploads
Uploads have to be specially set up to be secure.
Definition: DefaultSettings.php:378
Linker\commentBlock
static commentBlock( $comment, $title=null, $local=false, $wikiId=null)
Wrap a comment in standard punctuation and formatting if it's non-empty, otherwise return empty strin...
Definition: Linker.php:1439
NS_USER
const NS_USER
Definition: Defines.php:64
$link
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:2929
Linker\normalizeSubpageLink
static normalizeSubpageLink( $contextTitle, $target, &$text)
Definition: Linker.php:1353
wfMessage
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
wfWarn
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
Definition: GlobalFunctions.php:1142
$t
$t
Definition: testCompression.php:67
Html\element
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
$wgUploadMissingFileUrl
$wgUploadMissingFileUrl
Point the upload link for missing files to an external URL, as with $wgUploadNavigationUrl.
Definition: DefaultSettings.php:805
MediaWikiServices
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
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:27
Linker\accesskey
static accesskey( $name)
Given the id of an interface element, constructs the appropriate accesskey attribute from the system ...
Definition: Linker.php:1979
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:50
Linker\makeThumbLinkObj
static makeThumbLinkObj(Title $title, $file, $label='', $alt, $align='right', $params=[], $framed=false, $manualthumb="")
Make HTML for a thumbnail including image, border and caption.
Definition: Linker.php:502
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
Linker\buildRollbackLink
static buildRollbackLink( $rev, IContextSource $context=null, $editCount=false)
Build a raw rollback link, useful for collections of "tool" links.
Definition: Linker.php:1774
$pre
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers temp or archived zone change it to an object instance and return false override the list derivative used the name of the old file when set the default code will be skipped $pre
Definition: hooks.txt:1459
Linker\makeExternalImage
static makeExternalImage( $url, $alt='')
Return the code for images which were added via external links, via Parser::maybeMakeExternalImage().
Definition: Linker.php:266
$options
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1049
MWNamespace\getCanonicalName
static getCanonicalName( $index)
Returns the canonical (English) name for a given index.
Definition: MWNamespace.php:228
Revision\DELETED_TEXT
const DELETED_TEXT
Definition: Revision.php:90
$flags
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2749
Linker\makeBrokenImageLinkObj
static makeBrokenImageLinkObj( $title, $label='', $query='', $unused1='', $unused2='', $time=false)
Make a "broken" link to an image.
Definition: Linker.php:685
array
the array() calling protocol came about after MediaWiki 1.4rc1.
$wgContLang
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 content language as $wgContLang
Definition: design.txt:56