MediaWiki  1.31.0
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 LinkTarget ) {
111  wfWarn( __METHOD__ . ': Requires $target to be a LinkTarget 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 
164  public static function linkKnown(
165  $target, $html = null, $customAttribs = [],
166  $query = [], $options = [ 'known' ]
167  ) {
168  return self::link( $target, $html, $customAttribs, $query, $options );
169  }
170 
186  public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
187  $ret = "<a class=\"mw-selflink selflink\">{$prefix}{$html}</a>{$trail}";
188  if ( !Hooks::run( 'SelfLinkBegin', [ $nt, &$html, &$trail, &$prefix, &$ret ] ) ) {
189  return $ret;
190  }
191 
192  if ( $html == '' ) {
193  $html = htmlspecialchars( $nt->getPrefixedText() );
194  }
195  list( $inside, $trail ) = self::splitTrail( $trail );
196  return "<a class=\"mw-selflink selflink\">{$prefix}{$html}{$inside}</a>{$trail}";
197  }
198 
209  public static function getInvalidTitleDescription( IContextSource $context, $namespace, $title ) {
211 
212  // First we check whether the namespace exists or not.
213  if ( MWNamespace::exists( $namespace ) ) {
214  if ( $namespace == NS_MAIN ) {
215  $name = $context->msg( 'blanknamespace' )->text();
216  } else {
217  $name = $wgContLang->getFormattedNsText( $namespace );
218  }
219  return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
220  } else {
221  return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
222  }
223  }
224 
230  public static function normaliseSpecialPage( LinkTarget $target ) {
231  if ( $target->getNamespace() == NS_SPECIAL && !$target->isExternal() ) {
232  list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $target->getDBkey() );
233  if ( !$name ) {
234  return $target;
235  }
236  $ret = SpecialPage::getTitleValueFor( $name, $subpage, $target->getFragment() );
237  return $ret;
238  } else {
239  return $target;
240  }
241  }
242 
251  private static function fnamePart( $url ) {
252  $basename = strrchr( $url, '/' );
253  if ( false === $basename ) {
254  $basename = $url;
255  } else {
256  $basename = substr( $basename, 1 );
257  }
258  return $basename;
259  }
260 
271  public static function makeExternalImage( $url, $alt = '' ) {
272  if ( $alt == '' ) {
273  $alt = self::fnamePart( $url );
274  }
275  $img = '';
276  $success = Hooks::run( 'LinkerMakeExternalImage', [ &$url, &$alt, &$img ] );
277  if ( !$success ) {
278  wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
279  . "with url {$url} and alt text {$alt} to {$img}\n", true );
280  return $img;
281  }
282  return Html::element( 'img',
283  [
284  'src' => $url,
285  'alt' => $alt ] );
286  }
287 
324  public static function makeImageLink( Parser $parser, Title $title,
325  $file, $frameParams = [], $handlerParams = [], $time = false,
326  $query = "", $widthOption = null
327  ) {
328  $res = null;
329  $dummy = new DummyLinker;
330  if ( !Hooks::run( 'ImageBeforeProduceHTML', [ &$dummy, &$title,
331  &$file, &$frameParams, &$handlerParams, &$time, &$res ] ) ) {
332  return $res;
333  }
334 
335  if ( $file && !$file->allowInlineDisplay() ) {
336  wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
337  return self::link( $title );
338  }
339 
340  // Clean up parameters
341  $page = isset( $handlerParams['page'] ) ? $handlerParams['page'] : false;
342  if ( !isset( $frameParams['align'] ) ) {
343  $frameParams['align'] = '';
344  }
345  if ( !isset( $frameParams['alt'] ) ) {
346  $frameParams['alt'] = '';
347  }
348  if ( !isset( $frameParams['title'] ) ) {
349  $frameParams['title'] = '';
350  }
351  if ( !isset( $frameParams['class'] ) ) {
352  $frameParams['class'] = '';
353  }
354 
355  $prefix = $postfix = '';
356 
357  if ( 'center' == $frameParams['align'] ) {
358  $prefix = '<div class="center">';
359  $postfix = '</div>';
360  $frameParams['align'] = 'none';
361  }
362  if ( $file && !isset( $handlerParams['width'] ) ) {
363  if ( isset( $handlerParams['height'] ) && $file->isVectorized() ) {
364  // If its a vector image, and user only specifies height
365  // we don't want it to be limited by its "normal" width.
367  $handlerParams['width'] = $wgSVGMaxSize;
368  } else {
369  $handlerParams['width'] = $file->getWidth( $page );
370  }
371 
372  if ( isset( $frameParams['thumbnail'] )
373  || isset( $frameParams['manualthumb'] )
374  || isset( $frameParams['framed'] )
375  || isset( $frameParams['frameless'] )
376  || !$handlerParams['width']
377  ) {
379 
380  if ( $widthOption === null || !isset( $wgThumbLimits[$widthOption] ) ) {
381  $widthOption = User::getDefaultOption( 'thumbsize' );
382  }
383 
384  // Reduce width for upright images when parameter 'upright' is used
385  if ( isset( $frameParams['upright'] ) && $frameParams['upright'] == 0 ) {
386  $frameParams['upright'] = $wgThumbUpright;
387  }
388 
389  // For caching health: If width scaled down due to upright
390  // parameter, round to full __0 pixel to avoid the creation of a
391  // lot of odd thumbs.
392  $prefWidth = isset( $frameParams['upright'] ) ?
393  round( $wgThumbLimits[$widthOption] * $frameParams['upright'], -1 ) :
394  $wgThumbLimits[$widthOption];
395 
396  // Use width which is smaller: real image width or user preference width
397  // Unless image is scalable vector.
398  if ( !isset( $handlerParams['height'] ) && ( $handlerParams['width'] <= 0 ||
399  $prefWidth < $handlerParams['width'] || $file->isVectorized() ) ) {
400  $handlerParams['width'] = $prefWidth;
401  }
402  }
403  }
404 
405  if ( isset( $frameParams['thumbnail'] ) || isset( $frameParams['manualthumb'] )
406  || isset( $frameParams['framed'] )
407  ) {
408  # Create a thumbnail. Alignment depends on the writing direction of
409  # the page content language (right-aligned for LTR languages,
410  # left-aligned for RTL languages)
411  # If a thumbnail width has not been provided, it is set
412  # to the default user option as specified in Language*.php
413  if ( $frameParams['align'] == '' ) {
414  $frameParams['align'] = $parser->getTargetLanguage()->alignEnd();
415  }
416  return $prefix .
417  self::makeThumbLink2( $title, $file, $frameParams, $handlerParams, $time, $query ) .
418  $postfix;
419  }
420 
421  if ( $file && isset( $frameParams['frameless'] ) ) {
422  $srcWidth = $file->getWidth( $page );
423  # For "frameless" option: do not present an image bigger than the
424  # source (for bitmap-style images). This is the same behavior as the
425  # "thumb" option does it already.
426  if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
427  $handlerParams['width'] = $srcWidth;
428  }
429  }
430 
431  if ( $file && isset( $handlerParams['width'] ) ) {
432  # Create a resized image, without the additional thumbnail features
433  $thumb = $file->transform( $handlerParams );
434  } else {
435  $thumb = false;
436  }
437 
438  if ( !$thumb ) {
439  $s = self::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
440  } else {
442  $params = [
443  'alt' => $frameParams['alt'],
444  'title' => $frameParams['title'],
445  'valign' => isset( $frameParams['valign'] ) ? $frameParams['valign'] : false,
446  'img-class' => $frameParams['class'] ];
447  if ( isset( $frameParams['border'] ) ) {
448  $params['img-class'] .= ( $params['img-class'] !== '' ? ' ' : '' ) . 'thumbborder';
449  }
451 
452  $s = $thumb->toHtml( $params );
453  }
454  if ( $frameParams['align'] != '' ) {
455  $s = "<div class=\"float{$frameParams['align']}\">{$s}</div>";
456  }
457  return str_replace( "\n", ' ', $prefix . $s . $postfix );
458  }
459 
468  private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
469  $mtoParams = [];
470  if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
471  $mtoParams['custom-url-link'] = $frameParams['link-url'];
472  if ( isset( $frameParams['link-target'] ) ) {
473  $mtoParams['custom-target-link'] = $frameParams['link-target'];
474  }
475  if ( $parser ) {
476  $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
477  foreach ( $extLinkAttrs as $name => $val ) {
478  // Currently could include 'rel' and 'target'
479  $mtoParams['parser-extlink-' . $name] = $val;
480  }
481  }
482  } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
483  $mtoParams['custom-title-link'] = Title::newFromLinkTarget(
484  self::normaliseSpecialPage( $frameParams['link-title'] )
485  );
486  } elseif ( !empty( $frameParams['no-link'] ) ) {
487  // No link
488  } else {
489  $mtoParams['desc-link'] = true;
490  $mtoParams['desc-query'] = $query;
491  }
492  return $mtoParams;
493  }
494 
507  public static function makeThumbLinkObj( Title $title, $file, $label = '', $alt,
508  $align = 'right', $params = [], $framed = false, $manualthumb = ""
509  ) {
510  $frameParams = [
511  'alt' => $alt,
512  'caption' => $label,
513  'align' => $align
514  ];
515  if ( $framed ) {
516  $frameParams['framed'] = true;
517  }
518  if ( $manualthumb ) {
519  $frameParams['manualthumb'] = $manualthumb;
520  }
521  return self::makeThumbLink2( $title, $file, $frameParams, $params );
522  }
523 
533  public static function makeThumbLink2( Title $title, $file, $frameParams = [],
534  $handlerParams = [], $time = false, $query = ""
535  ) {
536  $exists = $file && $file->exists();
537 
538  $page = isset( $handlerParams['page'] ) ? $handlerParams['page'] : false;
539  if ( !isset( $frameParams['align'] ) ) {
540  $frameParams['align'] = 'right';
541  }
542  if ( !isset( $frameParams['alt'] ) ) {
543  $frameParams['alt'] = '';
544  }
545  if ( !isset( $frameParams['title'] ) ) {
546  $frameParams['title'] = '';
547  }
548  if ( !isset( $frameParams['caption'] ) ) {
549  $frameParams['caption'] = '';
550  }
551 
552  if ( empty( $handlerParams['width'] ) ) {
553  // Reduce width for upright images when parameter 'upright' is used
554  $handlerParams['width'] = isset( $frameParams['upright'] ) ? 130 : 180;
555  }
556  $thumb = false;
557  $noscale = false;
558  $manualthumb = false;
559 
560  if ( !$exists ) {
561  $outerWidth = $handlerParams['width'] + 2;
562  } else {
563  if ( isset( $frameParams['manualthumb'] ) ) {
564  # Use manually specified thumbnail
565  $manual_title = Title::makeTitleSafe( NS_FILE, $frameParams['manualthumb'] );
566  if ( $manual_title ) {
567  $manual_img = wfFindFile( $manual_title );
568  if ( $manual_img ) {
569  $thumb = $manual_img->getUnscaledThumb( $handlerParams );
570  $manualthumb = true;
571  } else {
572  $exists = false;
573  }
574  }
575  } elseif ( isset( $frameParams['framed'] ) ) {
576  // Use image dimensions, don't scale
577  $thumb = $file->getUnscaledThumb( $handlerParams );
578  $noscale = true;
579  } else {
580  # Do not present an image bigger than the source, for bitmap-style images
581  # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
582  $srcWidth = $file->getWidth( $page );
583  if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
584  $handlerParams['width'] = $srcWidth;
585  }
586  $thumb = $file->transform( $handlerParams );
587  }
588 
589  if ( $thumb ) {
590  $outerWidth = $thumb->getWidth() + 2;
591  } else {
592  $outerWidth = $handlerParams['width'] + 2;
593  }
594  }
595 
596  # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
597  # So we don't need to pass it here in $query. However, the URL for the
598  # zoom icon still needs it, so we make a unique query for it. See T16771
599  $url = $title->getLocalURL( $query );
600  if ( $page ) {
601  $url = wfAppendQuery( $url, [ 'page' => $page ] );
602  }
603  if ( $manualthumb
604  && !isset( $frameParams['link-title'] )
605  && !isset( $frameParams['link-url'] )
606  && !isset( $frameParams['no-link'] ) ) {
607  $frameParams['link-url'] = $url;
608  }
609 
610  $s = "<div class=\"thumb t{$frameParams['align']}\">"
611  . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
612 
613  if ( !$exists ) {
614  $s .= self::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
615  $zoomIcon = '';
616  } elseif ( !$thumb ) {
617  $s .= wfMessage( 'thumbnail_error', '' )->escaped();
618  $zoomIcon = '';
619  } else {
620  if ( !$noscale && !$manualthumb ) {
622  }
623  $params = [
624  'alt' => $frameParams['alt'],
625  'title' => $frameParams['title'],
626  'img-class' => ( isset( $frameParams['class'] ) && $frameParams['class'] !== ''
627  ? $frameParams['class'] . ' '
628  : '' ) . 'thumbimage'
629  ];
630  $params = self::getImageLinkMTOParams( $frameParams, $query ) + $params;
631  $s .= $thumb->toHtml( $params );
632  if ( isset( $frameParams['framed'] ) ) {
633  $zoomIcon = "";
634  } else {
635  $zoomIcon = Html::rawElement( 'div', [ 'class' => 'magnify' ],
636  Html::rawElement( 'a', [
637  'href' => $url,
638  'class' => 'internal',
639  'title' => wfMessage( 'thumbnail-more' )->text() ],
640  "" ) );
641  }
642  }
643  $s .= ' <div class="thumbcaption">' . $zoomIcon . $frameParams['caption'] . "</div></div></div>";
644  return str_replace( "\n", ' ', $s );
645  }
646 
655  public static function processResponsiveImages( $file, $thumb, $hp ) {
657  if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
658  $hp15 = $hp;
659  $hp15['width'] = round( $hp['width'] * 1.5 );
660  $hp20 = $hp;
661  $hp20['width'] = $hp['width'] * 2;
662  if ( isset( $hp['height'] ) ) {
663  $hp15['height'] = round( $hp['height'] * 1.5 );
664  $hp20['height'] = $hp['height'] * 2;
665  }
666 
667  $thumb15 = $file->transform( $hp15 );
668  $thumb20 = $file->transform( $hp20 );
669  if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
670  $thumb->responsiveUrls['1.5'] = $thumb15->getUrl();
671  }
672  if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
673  $thumb->responsiveUrls['2'] = $thumb20->getUrl();
674  }
675  }
676  }
677 
690  public static function makeBrokenImageLinkObj( $title, $label = '',
691  $query = '', $unused1 = '', $unused2 = '', $time = false
692  ) {
693  if ( !$title instanceof Title ) {
694  wfWarn( __METHOD__ . ': Requires $title to be a Title object.' );
695  return "<!-- ERROR -->" . htmlspecialchars( $label );
696  }
697 
699  if ( $label == '' ) {
700  $label = $title->getPrefixedText();
701  }
702  $encLabel = htmlspecialchars( $label );
703  $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
704 
706  && !$currentExists
707  ) {
708  $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
709 
710  if ( $redir ) {
711  // We already know it's a redirect, so mark it
712  // accordingly
713  return self::link(
714  $title,
715  $encLabel,
716  [ 'class' => 'mw-redirect' ],
717  wfCgiToArray( $query ),
718  [ 'known', 'noclasses' ]
719  );
720  }
721 
722  $href = self::getUploadUrl( $title, $query );
723 
724  return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
725  htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES ) . '">' .
726  $encLabel . '</a>';
727  }
728 
729  return self::link( $title, $encLabel, [], wfCgiToArray( $query ), [ 'known', 'noclasses' ] );
730  }
731 
740  protected static function getUploadUrl( $destFile, $query = '' ) {
742  $q = 'wpDestFile=' . $destFile->getPartialURL();
743  if ( $query != '' ) {
744  $q .= '&' . $query;
745  }
746 
747  if ( $wgUploadMissingFileUrl ) {
749  } elseif ( $wgUploadNavigationUrl ) {
751  } else {
752  $upload = SpecialPage::getTitleFor( 'Upload' );
753  return $upload->getLocalURL( $q );
754  }
755  }
756 
766  public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
767  $img = wfFindFile( $title, [ 'time' => $time ] );
768  return self::makeMediaLinkFile( $title, $img, $html );
769  }
770 
783  public static function makeMediaLinkFile( Title $title, $file, $html = '' ) {
784  if ( $file && $file->exists() ) {
785  $url = $file->getUrl();
786  $class = 'internal';
787  } else {
788  $url = self::getUploadUrl( $title );
789  $class = 'new';
790  }
791 
792  $alt = $title->getText();
793  if ( $html == '' ) {
794  $html = $alt;
795  }
796 
797  $ret = '';
798  $attribs = [
799  'href' => $url,
800  'class' => $class,
801  'title' => $alt
802  ];
803 
804  if ( !Hooks::run( 'LinkerMakeMediaLinkFile',
805  [ $title, $file, &$html, &$attribs, &$ret ] ) ) {
806  wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
807  . "with url {$url} and text {$html} to {$ret}\n", true );
808  return $ret;
809  }
810 
811  return Html::rawElement( 'a', $attribs, $html );
812  }
813 
824  public static function specialLink( $name, $key = '' ) {
825  if ( $key == '' ) {
826  $key = strtolower( $name );
827  }
828 
830  }
831 
843  public static function makeExternalLink( $url, $text, $escape = true,
844  $linktype = '', $attribs = [], $title = null
845  ) {
847  $class = "external";
848  if ( $linktype ) {
849  $class .= " $linktype";
850  }
851  if ( isset( $attribs['class'] ) && $attribs['class'] ) {
852  $class .= " {$attribs['class']}";
853  }
854  $attribs['class'] = $class;
855 
856  if ( $escape ) {
857  $text = htmlspecialchars( $text );
858  }
859 
860  if ( !$title ) {
861  $title = $wgTitle;
862  }
863  $newRel = Parser::getExternalLinkRel( $url, $title );
864  if ( !isset( $attribs['rel'] ) || $attribs['rel'] === '' ) {
865  $attribs['rel'] = $newRel;
866  } elseif ( $newRel !== '' ) {
867  // Merge the rel attributes.
868  $newRels = explode( ' ', $newRel );
869  $oldRels = explode( ' ', $attribs['rel'] );
870  $combined = array_unique( array_merge( $newRels, $oldRels ) );
871  $attribs['rel'] = implode( ' ', $combined );
872  }
873  $link = '';
874  $success = Hooks::run( 'LinkerMakeExternalLink',
875  [ &$url, &$text, &$link, &$attribs, $linktype ] );
876  if ( !$success ) {
877  wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
878  . "with url {$url} and text {$text} to {$link}\n", true );
879  return $link;
880  }
881  $attribs['href'] = $url;
882  return Html::rawElement( 'a', $attribs, $text );
883  }
884 
893  public static function userLink( $userId, $userName, $altUserName = false ) {
894  $classes = 'mw-userlink';
895  $page = null;
896  if ( $userId == 0 ) {
897  $page = ExternalUserNames::getUserLinkTitle( $userName );
898 
899  if ( ExternalUserNames::isExternal( $userName ) ) {
900  $classes .= ' mw-extuserlink';
901  } elseif ( $altUserName === false ) {
902  $altUserName = IP::prettifyIP( $userName );
903  }
904  $classes .= ' mw-anonuserlink'; // Separate link class for anons (T45179)
905  } else {
906  $page = Title::makeTitle( NS_USER, $userName );
907  }
908 
909  // Wrap the output with <bdi> tags for directionality isolation
910  $linkText =
911  '<bdi>' . htmlspecialchars( $altUserName !== false ? $altUserName : $userName ) . '</bdi>';
912 
913  return $page
914  ? self::link( $page, $linkText, [ 'class' => $classes ] )
915  : Html::rawElement( 'span', [ 'class' => $classes ], $linkText );
916  }
917 
931  public static function userToolLinks(
932  $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
933  ) {
935  $talkable = !( $wgDisableAnonTalk && 0 == $userId );
936  $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
937  $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
938 
939  if ( $userId == 0 && ExternalUserNames::isExternal( $userText ) ) {
940  // No tools for an external user
941  return '';
942  }
943 
944  $items = [];
945  if ( $talkable ) {
946  $items[] = self::userTalkLink( $userId, $userText );
947  }
948  if ( $userId ) {
949  // check if the user has an edit
950  $attribs = [];
951  $attribs['class'] = 'mw-usertoollinks-contribs';
952  if ( $redContribsWhenNoEdits ) {
953  if ( intval( $edits ) === 0 && $edits !== 0 ) {
954  $user = User::newFromId( $userId );
955  $edits = $user->getEditCount();
956  }
957  if ( $edits === 0 ) {
958  $attribs['class'] .= ' new';
959  }
960  }
961  $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
962 
963  $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
964  }
965  if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
966  $items[] = self::blockLink( $userId, $userText );
967  }
968 
969  if ( $addEmailLink && $wgUser->canSendEmail() ) {
970  $items[] = self::emailLink( $userId, $userText );
971  }
972 
973  Hooks::run( 'UserToolLinksEdit', [ $userId, $userText, &$items ] );
974 
975  if ( $items ) {
976  return wfMessage( 'word-separator' )->escaped()
977  . '<span class="mw-usertoollinks">'
978  . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
979  . '</span>';
980  } else {
981  return '';
982  }
983  }
984 
993  public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
994  return self::userToolLinks( $userId, $userText, true, 0, $edits );
995  }
996 
1003  public static function userTalkLink( $userId, $userText ) {
1004  $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1005  $moreLinkAttribs['class'] = 'mw-usertoollinks-talk';
1006  $userTalkLink = self::link( $userTalkPage,
1007  wfMessage( 'talkpagelinktext' )->escaped(),
1008  $moreLinkAttribs );
1009  return $userTalkLink;
1010  }
1011 
1018  public static function blockLink( $userId, $userText ) {
1019  $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1020  $moreLinkAttribs['class'] = 'mw-usertoollinks-block';
1021  $blockLink = self::link( $blockPage,
1022  wfMessage( 'blocklink' )->escaped(),
1023  $moreLinkAttribs );
1024  return $blockLink;
1025  }
1026 
1032  public static function emailLink( $userId, $userText ) {
1033  $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1034  $moreLinkAttribs['class'] = 'mw-usertoollinks-mail';
1035  $emailLink = self::link( $emailPage,
1036  wfMessage( 'emaillink' )->escaped(),
1037  $moreLinkAttribs );
1038  return $emailLink;
1039  }
1040 
1048  public static function revUserLink( $rev, $isPublic = false ) {
1049  if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1050  $link = wfMessage( 'rev-deleted-user' )->escaped();
1051  } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1053  $rev->getUserText( Revision::FOR_THIS_USER ) );
1054  } else {
1055  $link = wfMessage( 'rev-deleted-user' )->escaped();
1056  }
1057  if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1058  return '<span class="history-deleted">' . $link . '</span>';
1059  }
1060  return $link;
1061  }
1062 
1070  public static function revUserTools( $rev, $isPublic = false ) {
1071  if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1072  $link = wfMessage( 'rev-deleted-user' )->escaped();
1073  } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1074  $userId = $rev->getUser( Revision::FOR_THIS_USER );
1075  $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1076  $link = self::userLink( $userId, $userText )
1077  . self::userToolLinks( $userId, $userText );
1078  } else {
1079  $link = wfMessage( 'rev-deleted-user' )->escaped();
1080  }
1081  if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1082  return ' <span class="history-deleted">' . $link . '</span>';
1083  }
1084  return $link;
1085  }
1086 
1109  public static function formatComment(
1110  $comment, $title = null, $local = false, $wikiId = null
1111  ) {
1112  # Sanitize text a bit:
1113  $comment = str_replace( "\n", " ", $comment );
1114  # Allow HTML entities (for T15815)
1115  $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1116 
1117  # Render autocomments and make links:
1118  $comment = self::formatAutocomments( $comment, $title, $local, $wikiId );
1119  $comment = self::formatLinksInComment( $comment, $title, $local, $wikiId );
1120 
1121  return $comment;
1122  }
1123 
1141  private static function formatAutocomments(
1142  $comment, $title = null, $local = false, $wikiId = null
1143  ) {
1144  // @todo $append here is something of a hack to preserve the status
1145  // quo. Someone who knows more about bidi and such should decide
1146  // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1147  // wiki, both when autocomments exist and when they don't, and
1148  // (2) what markup will make that actually happen.
1149  $append = '';
1150  $comment = preg_replace_callback(
1151  // To detect the presence of content before or after the
1152  // auto-comment, we use capturing groups inside optional zero-width
1153  // assertions. But older versions of PCRE can't directly make
1154  // zero-width assertions optional, so wrap them in a non-capturing
1155  // group.
1156  '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1157  function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1158  global $wgLang;
1159 
1160  // Ensure all match positions are defined
1161  $match += [ '', '', '', '' ];
1162 
1163  $pre = $match[1] !== '';
1164  $auto = $match[2];
1165  $post = $match[3] !== '';
1166  $comment = null;
1167 
1168  Hooks::run(
1169  'FormatAutocomments',
1170  [ &$comment, $pre, $auto, $post, $title, $local, $wikiId ]
1171  );
1172 
1173  if ( $comment === null ) {
1174  $link = '';
1175  if ( $title ) {
1176  $section = $auto;
1177  # Remove links that a user may have manually put in the autosummary
1178  # This could be improved by copying as much of Parser::stripSectionName as desired.
1179  $section = str_replace( '[[:', '', $section );
1180  $section = str_replace( '[[', '', $section );
1181  $section = str_replace( ']]', '', $section );
1182 
1183  $section = substr( Parser::guessSectionNameFromStrippedText( $section ), 1 );
1184  if ( $local ) {
1185  $sectionTitle = Title::makeTitleSafe( NS_MAIN, '', $section );
1186  } else {
1187  $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1188  $title->getDBkey(), $section );
1189  }
1190  if ( $sectionTitle ) {
1191  $link = Linker::makeCommentLink( $sectionTitle, $wgLang->getArrow(), $wikiId, 'noclasses' );
1192  } else {
1193  $link = '';
1194  }
1195  }
1196  if ( $pre ) {
1197  # written summary $presep autocomment (summary /* section */)
1198  $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1199  }
1200  if ( $post ) {
1201  # autocomment $postsep written summary (/* section */ summary)
1202  $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1203  }
1204  $auto = '<span class="autocomment">' . $auto . '</span>';
1205  $comment = $pre . $link . $wgLang->getDirMark()
1206  . '<span dir="auto">' . $auto;
1207  $append .= '</span>';
1208  }
1209  return $comment;
1210  },
1211  $comment
1212  );
1213  return $comment . $append;
1214  }
1215 
1234  public static function formatLinksInComment(
1235  $comment, $title = null, $local = false, $wikiId = null
1236  ) {
1237  return preg_replace_callback(
1238  '/
1239  \[\[
1240  :? # ignore optional leading colon
1241  ([^\]|]+) # 1. link target; page names cannot include ] or |
1242  (?:\|
1243  # 2. link text
1244  # Stop matching at ]] without relying on backtracking.
1245  ((?:]?[^\]])*+)
1246  )?
1247  \]\]
1248  ([^[]*) # 3. link trail (the text up until the next link)
1249  /x',
1250  function ( $match ) use ( $title, $local, $wikiId ) {
1252 
1253  $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1254  $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1255 
1256  $comment = $match[0];
1257 
1258  # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1259  if ( strpos( $match[1], '%' ) !== false ) {
1260  $match[1] = strtr(
1261  rawurldecode( $match[1] ),
1262  [ '<' => '&lt;', '>' => '&gt;' ]
1263  );
1264  }
1265 
1266  # Handle link renaming [[foo|text]] will show link as "text"
1267  if ( $match[2] != "" ) {
1268  $text = $match[2];
1269  } else {
1270  $text = $match[1];
1271  }
1272  $submatch = [];
1273  $thelink = null;
1274  if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1275  # Media link; trail not supported.
1276  $linkRegexp = '/\[\[(.*?)\]\]/';
1277  $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1278  if ( $title ) {
1279  $thelink = Linker::makeMediaLinkObj( $title, $text );
1280  }
1281  } else {
1282  # Other kind of link
1283  # Make sure its target is non-empty
1284  if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1285  $match[1] = substr( $match[1], 1 );
1286  }
1287  if ( $match[1] !== false && $match[1] !== '' ) {
1288  if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1289  $trail = $submatch[1];
1290  } else {
1291  $trail = "";
1292  }
1293  $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1294  list( $inside, $trail ) = Linker::splitTrail( $trail );
1295 
1296  $linkText = $text;
1297  $linkTarget = Linker::normalizeSubpageLink( $title, $match[1], $linkText );
1298 
1299  $target = Title::newFromText( $linkTarget );
1300  if ( $target ) {
1301  if ( $target->getText() == '' && !$target->isExternal()
1302  && !$local && $title
1303  ) {
1304  $target = $title->createFragmentTarget( $target->getFragment() );
1305  }
1306 
1307  $thelink = Linker::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1308  }
1309  }
1310  }
1311  if ( $thelink ) {
1312  // If the link is still valid, go ahead and replace it in!
1313  $comment = preg_replace(
1314  $linkRegexp,
1316  $comment,
1317  1
1318  );
1319  }
1320 
1321  return $comment;
1322  },
1323  $comment
1324  );
1325  }
1326 
1340  public static function makeCommentLink(
1341  LinkTarget $linkTarget, $text, $wikiId = null, $options = []
1342  ) {
1343  if ( $wikiId !== null && !$linkTarget->isExternal() ) {
1346  $wikiId,
1347  $linkTarget->getNamespace() === 0
1348  ? $linkTarget->getDBkey()
1349  : MWNamespace::getCanonicalName( $linkTarget->getNamespace() ) . ':'
1350  . $linkTarget->getDBkey(),
1351  $linkTarget->getFragment()
1352  ),
1353  $text,
1354  /* escape = */ false // Already escaped
1355  );
1356  } else {
1357  $link = self::link( $linkTarget, $text, [], [], $options );
1358  }
1359 
1360  return $link;
1361  }
1362 
1369  public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1370  # Valid link forms:
1371  # Foobar -- normal
1372  # :Foobar -- override special treatment of prefix (images, language links)
1373  # /Foobar -- convert to CurrentPage/Foobar
1374  # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1375  # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1376  # ../Foobar -- convert to CurrentPage/Foobar,
1377  # (from CurrentPage/CurrentSubPage)
1378  # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1379  # (from CurrentPage/CurrentSubPage)
1380 
1381  $ret = $target; # default return value is no change
1382 
1383  # Some namespaces don't allow subpages,
1384  # so only perform processing if subpages are allowed
1385  if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1386  $hash = strpos( $target, '#' );
1387  if ( $hash !== false ) {
1388  $suffix = substr( $target, $hash );
1389  $target = substr( $target, 0, $hash );
1390  } else {
1391  $suffix = '';
1392  }
1393  # T9425
1394  $target = trim( $target );
1395  # Look at the first character
1396  if ( $target != '' && $target[0] === '/' ) {
1397  # / at end means we don't want the slash to be shown
1398  $m = [];
1399  $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1400  if ( $trailingSlashes ) {
1401  $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1402  } else {
1403  $noslash = substr( $target, 1 );
1404  }
1405 
1406  $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1407  if ( $text === '' ) {
1408  $text = $target . $suffix;
1409  } # this might be changed for ugliness reasons
1410  } else {
1411  # check for .. subpage backlinks
1412  $dotdotcount = 0;
1413  $nodotdot = $target;
1414  while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1415  ++$dotdotcount;
1416  $nodotdot = substr( $nodotdot, 3 );
1417  }
1418  if ( $dotdotcount > 0 ) {
1419  $exploded = explode( '/', $contextTitle->getPrefixedText() );
1420  if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1421  $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1422  # / at the end means don't show full path
1423  if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1424  $nodotdot = rtrim( $nodotdot, '/' );
1425  if ( $text === '' ) {
1426  $text = $nodotdot . $suffix;
1427  }
1428  }
1429  $nodotdot = trim( $nodotdot );
1430  if ( $nodotdot != '' ) {
1431  $ret .= '/' . $nodotdot;
1432  }
1433  $ret .= $suffix;
1434  }
1435  }
1436  }
1437  }
1438 
1439  return $ret;
1440  }
1441 
1455  public static function commentBlock(
1456  $comment, $title = null, $local = false, $wikiId = null
1457  ) {
1458  // '*' used to be the comment inserted by the software way back
1459  // in antiquity in case none was provided, here for backwards
1460  // compatibility, acc. to brion -ævar
1461  if ( $comment == '' || $comment == '*' ) {
1462  return '';
1463  } else {
1464  $formatted = self::formatComment( $comment, $title, $local, $wikiId );
1465  $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1466  return " <span class=\"comment\">$formatted</span>";
1467  }
1468  }
1469 
1480  public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1481  if ( $rev->getComment( Revision::RAW ) == "" ) {
1482  return "";
1483  }
1484  if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1485  $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1486  } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1487  $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1488  $rev->getTitle(), $local );
1489  } else {
1490  $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1491  }
1492  if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1493  return " <span class=\"history-deleted\">$block</span>";
1494  }
1495  return $block;
1496  }
1497 
1503  public static function formatRevisionSize( $size ) {
1504  if ( $size == 0 ) {
1505  $stxt = wfMessage( 'historyempty' )->escaped();
1506  } else {
1507  $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1508  $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1509  }
1510  return "<span class=\"history-size\">$stxt</span>";
1511  }
1512 
1519  public static function tocIndent() {
1520  return "\n<ul>";
1521  }
1522 
1530  public static function tocUnindent( $level ) {
1531  return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1532  }
1533 
1545  public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1546  $classes = "toclevel-$level";
1547  if ( $sectionIndex !== false ) {
1548  $classes .= " tocsection-$sectionIndex";
1549  }
1550 
1551  // \n<li class="$classes"><a href="#$anchor"><span class="tocnumber">
1552  // $tocnumber</span> <span class="toctext">$tocline</span></a>
1553  return "\n" . Html::openElement( 'li', [ 'class' => $classes ] )
1554  . Html::rawElement( 'a',
1555  [ 'href' => "#$anchor" ],
1556  Html::element( 'span', [ 'class' => 'tocnumber' ], $tocnumber )
1557  . ' '
1558  . Html::rawElement( 'span', [ 'class' => 'toctext' ], $tocline )
1559  );
1560  }
1561 
1569  public static function tocLineEnd() {
1570  return "</li>\n";
1571  }
1572 
1581  public static function tocList( $toc, $lang = false ) {
1582  $lang = wfGetLangObj( $lang );
1583  $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1584 
1585  return '<div id="toc" class="toc">'
1586  . Html::openElement( 'div', [
1587  'class' => 'toctitle',
1588  'lang' => $lang->getHtmlCode(),
1589  'dir' => $lang->getDir(),
1590  ] )
1591  . '<h2>' . $title . "</h2></div>\n"
1592  . $toc
1593  . "</ul>\n</div>\n";
1594  }
1595 
1604  public static function generateTOC( $tree, $lang = false ) {
1605  $toc = '';
1606  $lastLevel = 0;
1607  foreach ( $tree as $section ) {
1608  if ( $section['toclevel'] > $lastLevel ) {
1609  $toc .= self::tocIndent();
1610  } elseif ( $section['toclevel'] < $lastLevel ) {
1611  $toc .= self::tocUnindent(
1612  $lastLevel - $section['toclevel'] );
1613  } else {
1614  $toc .= self::tocLineEnd();
1615  }
1616 
1617  $toc .= self::tocLine( $section['anchor'],
1618  $section['line'], $section['number'],
1619  $section['toclevel'], $section['index'] );
1620  $lastLevel = $section['toclevel'];
1621  }
1622  $toc .= self::tocLineEnd();
1623  return self::tocList( $toc, $lang );
1624  }
1625 
1642  public static function makeHeadline( $level, $attribs, $anchor, $html,
1643  $link, $fallbackAnchor = false
1644  ) {
1645  $anchorEscaped = htmlspecialchars( $anchor );
1646  $fallback = '';
1647  if ( $fallbackAnchor !== false && $fallbackAnchor !== $anchor ) {
1648  $fallbackAnchor = htmlspecialchars( $fallbackAnchor );
1649  $fallback = "<span id=\"$fallbackAnchor\"></span>";
1650  }
1651  $ret = "<h$level$attribs"
1652  . "$fallback<span class=\"mw-headline\" id=\"$anchorEscaped\">$html</span>"
1653  . $link
1654  . "</h$level>";
1655 
1656  return $ret;
1657  }
1658 
1665  static function splitTrail( $trail ) {
1667  $regex = $wgContLang->linkTrail();
1668  $inside = '';
1669  if ( $trail !== '' ) {
1670  $m = [];
1671  if ( preg_match( $regex, $trail, $m ) ) {
1672  $inside = $m[1];
1673  $trail = $m[2];
1674  }
1675  }
1676  return [ $inside, $trail ];
1677  }
1678 
1706  public static function generateRollback( $rev, IContextSource $context = null,
1707  $options = [ 'verify' ]
1708  ) {
1709  if ( $context === null ) {
1711  }
1712 
1713  $editCount = false;
1714  if ( in_array( 'verify', $options, true ) ) {
1715  $editCount = self::getRollbackEditCount( $rev, true );
1716  if ( $editCount === false ) {
1717  return '';
1718  }
1719  }
1720 
1721  $inner = self::buildRollbackLink( $rev, $context, $editCount );
1722 
1723  if ( !in_array( 'noBrackets', $options, true ) ) {
1724  $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1725  }
1726 
1727  return '<span class="mw-rollback-link">' . $inner . '</span>';
1728  }
1729 
1745  public static function getRollbackEditCount( $rev, $verify ) {
1747  if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
1748  // Nothing has happened, indicate this by returning 'null'
1749  return null;
1750  }
1751 
1752  $dbr = wfGetDB( DB_REPLICA );
1753 
1754  // Up to the value of $wgShowRollbackEditCount revisions are counted
1756  $res = $dbr->select(
1757  $revQuery['tables'],
1758  [ 'rev_user_text' => $revQuery['fields']['rev_user_text'], 'rev_deleted' ],
1759  // $rev->getPage() returns null sometimes
1760  [ 'rev_page' => $rev->getTitle()->getArticleID() ],
1761  __METHOD__,
1762  [
1763  'USE INDEX' => [ 'revision' => 'page_timestamp' ],
1764  'ORDER BY' => 'rev_timestamp DESC',
1765  'LIMIT' => $wgShowRollbackEditCount + 1
1766  ],
1767  $revQuery['joins']
1768  );
1769 
1770  $editCount = 0;
1771  $moreRevs = false;
1772  foreach ( $res as $row ) {
1773  if ( $rev->getUserText( Revision::RAW ) != $row->rev_user_text ) {
1774  if ( $verify &&
1775  ( $row->rev_deleted & Revision::DELETED_TEXT
1776  || $row->rev_deleted & Revision::DELETED_USER
1777  ) ) {
1778  // If the user or the text of the revision we might rollback
1779  // to is deleted in some way we can't rollback. Similar to
1780  // the sanity checks in WikiPage::commitRollback.
1781  return false;
1782  }
1783  $moreRevs = true;
1784  break;
1785  }
1786  $editCount++;
1787  }
1788 
1789  if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1790  // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1791  // and there weren't any other revisions. That means that the current user is the only
1792  // editor, so we can't rollback
1793  return false;
1794  }
1795  return $editCount;
1796  }
1797 
1807  public static function buildRollbackLink( $rev, IContextSource $context = null,
1808  $editCount = false
1809  ) {
1811 
1812  // To config which pages are affected by miser mode
1813  $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
1814 
1815  if ( $context === null ) {
1817  }
1818 
1819  $title = $rev->getTitle();
1820  $query = [
1821  'action' => 'rollback',
1822  'from' => $rev->getUserText(),
1823  'token' => $context->getUser()->getEditToken( 'rollback' ),
1824  ];
1825  $attrs = [
1826  'data-mw' => 'interface',
1827  'title' => $context->msg( 'tooltip-rollback' )->text(),
1828  ];
1829  $options = [ 'known', 'noclasses' ];
1830 
1831  if ( $context->getRequest()->getBool( 'bot' ) ) {
1832  $query['bot'] = '1';
1833  $query['hidediff'] = '1'; // T17999
1834  }
1835 
1836  $disableRollbackEditCount = false;
1837  if ( $wgMiserMode ) {
1838  foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1839  if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1840  $disableRollbackEditCount = true;
1841  break;
1842  }
1843  }
1844  }
1845 
1846  if ( !$disableRollbackEditCount
1847  && is_int( $wgShowRollbackEditCount )
1849  ) {
1850  if ( !is_numeric( $editCount ) ) {
1851  $editCount = self::getRollbackEditCount( $rev, false );
1852  }
1853 
1854  if ( $editCount > $wgShowRollbackEditCount ) {
1855  $html = $context->msg( 'rollbacklinkcount-morethan' )
1856  ->numParams( $wgShowRollbackEditCount )->parse();
1857  } else {
1858  $html = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1859  }
1860 
1861  return self::link( $title, $html, $attrs, $query, $options );
1862  } else {
1863  $html = $context->msg( 'rollbacklink' )->escaped();
1864  return self::link( $title, $html, $attrs, $query, $options );
1865  }
1866  }
1867 
1886  public static function formatTemplates( $templates, $preview = false,
1887  $section = false, $more = null
1888  ) {
1889  wfDeprecated( __METHOD__, '1.28' );
1890 
1891  $type = false;
1892  if ( $preview ) {
1893  $type = 'preview';
1894  } elseif ( $section ) {
1895  $type = 'section';
1896  }
1897 
1898  if ( $more instanceof Message ) {
1899  $more = $more->toString();
1900  }
1901 
1902  $formatter = new TemplatesOnThisPageFormatter(
1904  MediaWikiServices::getInstance()->getLinkRenderer()
1905  );
1906  return $formatter->format( $templates, $type, $more );
1907  }
1908 
1917  public static function formatHiddenCategories( $hiddencats ) {
1918  $outText = '';
1919  if ( count( $hiddencats ) > 0 ) {
1920  # Construct the HTML
1921  $outText = '<div class="mw-hiddenCategoriesExplanation">';
1922  $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
1923  $outText .= "</div><ul>\n";
1924 
1925  foreach ( $hiddencats as $titleObj ) {
1926  # If it's hidden, it must exist - no need to check with a LinkBatch
1927  $outText .= '<li>'
1928  . self::link( $titleObj, null, [], [], 'known' )
1929  . "</li>\n";
1930  }
1931  $outText .= '</ul>';
1932  }
1933  return $outText;
1934  }
1935 
1946  public static function formatSize( $size ) {
1947  wfDeprecated( __METHOD__, '1.28' );
1948 
1949  global $wgLang;
1950  return htmlspecialchars( $wgLang->formatSize( $size ) );
1951  }
1952 
1969  public static function titleAttrib( $name, $options = null, array $msgParams = [] ) {
1970  $message = wfMessage( "tooltip-$name", $msgParams );
1971  if ( !$message->exists() ) {
1972  $tooltip = false;
1973  } else {
1974  $tooltip = $message->text();
1975  # Compatibility: formerly some tooltips had [alt-.] hardcoded
1976  $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1977  # Message equal to '-' means suppress it.
1978  if ( $tooltip == '-' ) {
1979  $tooltip = false;
1980  }
1981  }
1982 
1983  $options = (array)$options;
1984 
1985  if ( in_array( 'nonexisting', $options ) ) {
1986  $tooltip = wfMessage( 'red-link-title', $tooltip ?: '' )->text();
1987  }
1988  if ( in_array( 'withaccess', $options ) ) {
1989  $accesskey = self::accesskey( $name );
1990  if ( $accesskey !== false ) {
1991  // Should be build the same as in jquery.accessKeyLabel.js
1992  if ( $tooltip === false || $tooltip === '' ) {
1993  $tooltip = wfMessage( 'brackets', $accesskey )->text();
1994  } else {
1995  $tooltip .= wfMessage( 'word-separator' )->text();
1996  $tooltip .= wfMessage( 'brackets', $accesskey )->text();
1997  }
1998  }
1999  }
2000 
2001  return $tooltip;
2002  }
2003 
2004  public static $accesskeycache;
2005 
2017  public static function accesskey( $name ) {
2018  if ( isset( self::$accesskeycache[$name] ) ) {
2019  return self::$accesskeycache[$name];
2020  }
2021 
2022  $message = wfMessage( "accesskey-$name" );
2023 
2024  if ( !$message->exists() ) {
2025  $accesskey = false;
2026  } else {
2027  $accesskey = $message->plain();
2028  if ( $accesskey === '' || $accesskey === '-' ) {
2029  # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2030  # attribute, but this is broken for accesskey: that might be a useful
2031  # value.
2032  $accesskey = false;
2033  }
2034  }
2035 
2036  self::$accesskeycache[$name] = $accesskey;
2037  return self::$accesskeycache[$name];
2038  }
2039 
2053  public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
2054  $canHide = $user->isAllowed( 'deleterevision' );
2055  if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2056  return '';
2057  }
2058 
2059  if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
2060  return self::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2061  } else {
2062  if ( $rev->getId() ) {
2063  // RevDelete links using revision ID are stable across
2064  // page deletion and undeletion; use when possible.
2065  $query = [
2066  'type' => 'revision',
2067  'target' => $title->getPrefixedDBkey(),
2068  'ids' => $rev->getId()
2069  ];
2070  } else {
2071  // Older deleted entries didn't save a revision ID.
2072  // We have to refer to these by timestamp, ick!
2073  $query = [
2074  'type' => 'archive',
2075  'target' => $title->getPrefixedDBkey(),
2076  'ids' => $rev->getTimestamp()
2077  ];
2078  }
2079  return self::revDeleteLink( $query,
2080  $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2081  }
2082  }
2083 
2094  public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2095  $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2096  $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2097  $html = wfMessage( $msgKey )->escaped();
2098  $tag = $restricted ? 'strong' : 'span';
2099  $link = self::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2100  return Xml::tags(
2101  $tag,
2102  [ 'class' => 'mw-revdelundel-link' ],
2103  wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2104  );
2105  }
2106 
2116  public static function revDeleteLinkDisabled( $delete = true ) {
2117  $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2118  $html = wfMessage( $msgKey )->escaped();
2119  $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2120  return Xml::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2121  }
2122 
2135  public static function tooltipAndAccesskeyAttribs(
2136  $name,
2137  array $msgParams = [],
2138  $options = null
2139  ) {
2140  $options = (array)$options;
2141  $options[] = 'withaccess';
2142 
2143  $attribs = [
2144  'title' => self::titleAttrib( $name, $options, $msgParams ),
2145  'accesskey' => self::accesskey( $name )
2146  ];
2147  if ( $attribs['title'] === false ) {
2148  unset( $attribs['title'] );
2149  }
2150  if ( $attribs['accesskey'] === false ) {
2151  unset( $attribs['accesskey'] );
2152  }
2153  return $attribs;
2154  }
2155 
2163  public static function tooltip( $name, $options = null ) {
2164  $tooltip = self::titleAttrib( $name, $options );
2165  if ( $tooltip === false ) {
2166  return '';
2167  }
2168  return Xml::expandAttributes( [
2169  'title' => $tooltip
2170  ] );
2171  }
2172 
2173 }
User\getDefaultOption
static getDefaultOption( $opt)
Get a given default option value.
Definition: User.php:1762
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:468
Revision\DELETED_USER
const DELETED_USER
Definition: Revision.php:49
$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:244
Revision\DELETED_RESTRICTED
const DELETED_RESTRICTED
Definition: Revision.php:50
$wgUser
$wgUser
Definition: Setup.php:894
User\newFromId
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:614
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:273
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:1376
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:1234
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:1003
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:48
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
Linker\userToolLinksRedContribs
static userToolLinksRedContribs( $userId, $userText, $edits=null)
Alias for userToolLinks( $userId, $userText, true );.
Definition: Linker.php:993
Linker\emailLink
static emailLink( $userId, $userText)
Definition: Linker.php:1032
$context
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2604
$wgResponsiveImages
$wgResponsiveImages
Generate and use thumbnails suitable for screens with 1.5 and 2.0 pixel densities.
Definition: DefaultSettings.php:1499
Linker\revUserLink
static revUserLink( $rev, $isPublic=false)
Generate a user link if the current user is allowed to view it.
Definition: Linker.php:1048
Xml\tags
static tags( $element, $attribs=null, $contents)
Same as Xml::element(), but does not escape contents.
Definition: Xml.php:131
Linker\userLink
static userLink( $userId, $userName, $altUserName=false)
Make user link (or user contributions for unregistered users)
Definition: Linker.php:893
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:186
Linker\generateTOC
static generateTOC( $tree, $lang=false)
Generate a table of contents from a section tree.
Definition: Linker.php:1604
Linker\getUploadUrl
static getUploadUrl( $destFile, $query='')
Get the URL to upload a certain file.
Definition: Linker.php:740
captcha-old.count
count
Definition: captcha-old.py:249
Linker\tocIndent
static tocIndent()
Add another level to the Table of Contents.
Definition: Linker.php:1519
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
$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 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:1482
$fallback
$fallback
Definition: MessagesAb.php:11
$wgSVGMaxSize
$wgSVGMaxSize
Don't scale a SVG larger than this.
Definition: DefaultSettings.php:1135
MediaWiki\getTitle
getTitle()
Get the Title object that we'll be acting on, as specified in the WebRequest.
Definition: MediaWiki.php:138
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:171
Linker\fnamePart
static fnamePart( $url)
Returns the filename part of an url.
Definition: Linker.php:251
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
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:824
StringUtils\escapeRegexReplacement
static escapeRegexReplacement( $string)
Escape a string to make it suitable for inclusion in a preg_replace() replacement parameter.
Definition: StringUtils.php:310
NS_FILE
const NS_FILE
Definition: Defines.php:71
$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:164
$s
$s
Definition: mergeMessageFileList.php:187
$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:1987
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
page
target page
Definition: All_system_messages.txt:1267
Linker\processResponsiveImages
static processResponsiveImages( $file, $thumb, $hp)
Process responsive images: add 1.5x and 2x subimages to the thumbnail, where applicable.
Definition: Linker.php:655
value
if( $inline) $status value
Definition: SyntaxHighlight.php:349
$res
$res
Definition: database.txt:21
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
$wgTitle
if(! $wgRequest->checkUrlExtension()) if(isset( $_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] !='') if(! $wgEnableAPI) $wgTitle
Definition: api.php:68
$success
$success
Definition: NoLocalSettings.php:42
Linker\getInvalidTitleDescription
static getInvalidTitleDescription(IContextSource $context, $namespace, $title)
Get a message saying that an invalid title was encountered.
Definition: Linker.php:209
MediaWiki\Linker\LinkTarget\isExternal
isExternal()
Whether this LinkTarget has an interwiki component.
$revQuery
$revQuery
Definition: testCompression.php:51
Linker\tocLine
static tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex=false)
parameter level defines if we are on an indentation level
Definition: Linker.php:1545
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:1917
Linker\tooltipAndAccesskeyAttribs
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[], $options=null)
Returns the attributes for the tooltip and access key.
Definition: Linker.php:2135
$dbr
$dbr
Definition: testCompression.php:50
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:56
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:469
Revision
Definition: Revision.php:41
NS_MAIN
const NS_MAIN
Definition: Defines.php:65
$customAttribs
null means default & $customAttribs
Definition: hooks.txt:1987
$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:1591
NS_SPECIAL
const NS_SPECIAL
Definition: Defines.php:54
Linker\$accesskeycache
static $accesskeycache
Definition: Linker.php:2004
MediaWiki\Linker\LinkTarget\getNamespace
getNamespace()
Get the namespace index.
Revision\getQueryInfo
static getQueryInfo( $options=[])
Return the tables, fields, and join conditions to be selected to create a new revision object.
Definition: Revision.php:492
$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:1987
$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:766
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1111
Linker\generateRollback
static generateRollback( $rev, IContextSource $context=null, $options=[ 'verify'])
Generate a rollback link for a given revision.
Definition: Linker.php:1706
Linker\makeThumbLink2
static makeThumbLink2(Title $title, $file, $frameParams=[], $handlerParams=[], $time=false, $query="")
Definition: Linker.php:533
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:244
Linker\formatAutocomments
static formatAutocomments( $comment, $title=null, $local=false, $wikiId=null)
Converts autogenerated comments in edit summaries into section links.
Definition: Linker.php:1141
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2800
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:1070
Linker\tocList
static tocList( $toc, $lang=false)
Wraps the TOC in a table and provides the hide/collapse javascript.
Definition: Linker.php:1581
Linker\getRollbackEditCount
static getRollbackEditCount( $rev, $verify)
This function will return the number of revisions which a rollback would revert and,...
Definition: Linker.php:1745
$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:1987
Linker\makeHeadline
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
Definition: Linker.php:1642
not
if not
Definition: COPYING.txt:307
Linker\tocLineEnd
static tocLineEnd()
End a Table Of Contents line.
Definition: Linker.php:1569
wfGetLangObj
wfGetLangObj( $langcode=false)
Return a Language object from $langcode.
Definition: GlobalFunctions.php:1294
MWNamespace\hasSubpages
static hasSubpages( $index)
Does the namespace allow subpages?
Definition: MWNamespace.php:368
wfCgiToArray
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
Definition: GlobalFunctions.php:422
Linker\revDeleteLinkDisabled
static revDeleteLinkDisabled( $delete=true)
Creates a dead (show/hide) link for deleting revisions/log entries.
Definition: Linker.php:2116
$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:2595
Linker\makeExternalLink
static makeExternalLink( $url, $text, $escape=true, $linktype='', $attribs=[], $title=null)
Make an external link.
Definition: Linker.php:843
$time
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1795
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:534
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
Linker\makeCommentLink
static makeCommentLink(LinkTarget $linkTarget, $text, $wikiId=null, $options=[])
Generates a link to the given Title.
Definition: Linker.php:1340
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:982
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:2220
$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 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:1482
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:1665
IP\prettifyIP
static prettifyIP( $ip)
Prettify an IP for display to end users.
Definition: IP.php:213
$wgShowRollbackEditCount
$wgShowRollbackEditCount
The $wgShowRollbackEditCount variable is used to show how many edits can be rolled back.
Definition: DefaultSettings.php:3487
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:562
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:1480
Linker\blockLink
static blockLink( $userId, $userText)
Definition: Linker.php:1018
NS_USER_TALK
const NS_USER_TALK
Definition: Defines.php:68
Linker\normaliseSpecialPage
static normaliseSpecialPage(LinkTarget $target)
Definition: Linker.php:230
TemplatesOnThisPageFormatter
Handles formatting for the "templates used on this page" lists.
Definition: TemplatesOnThisPageFormatter.php:30
ExternalUserNames\getUserLinkTitle
static getUserLinkTitle( $userName)
Get a target Title to link a username.
Definition: ExternalUserNames.php:50
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:931
Linker\TOOL_LINKS_EMAIL
const TOOL_LINKS_EMAIL
Definition: Linker.php:39
NS_MEDIA
const NS_MEDIA
Definition: Defines.php:53
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:2053
Linker\formatSize
static formatSize( $size)
Definition: Linker.php:1946
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:1503
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:328
$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:1987
Revision\RAW
const RAW
Definition: Revision.php:57
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:324
Linker\formatTemplates
static formatTemplates( $templates, $preview=false, $section=false, $more=null)
Definition: Linker.php:1886
MWNamespace\exists
static exists( $index)
Returns whether the specified namespace exists.
Definition: MWNamespace.php:182
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:434
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:801
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:1969
wfFindFile
wfFindFile( $title, $options=[])
Find a file.
Definition: GlobalFunctions.php:2841
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:53
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:1109
$handlerParams
see documentation in includes Linker php for Linker::makeImageLink & $handlerParams
Definition: hooks.txt:1793
Linker\tooltip
static tooltip( $name, $options=null)
Returns raw bits of HTML, use titleAttrib()
Definition: Linker.php:2163
Title
Represents a title within MediaWiki.
Definition: Title.php:39
$wgMiserMode
$wgMiserMode
Disable database-intensive features.
Definition: DefaultSettings.php:2170
$options
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 & $options
Definition: hooks.txt:1987
$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:3005
$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:1767
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:1482
Linker\tocUnindent
static tocUnindent( $level)
Finish one or more sublevels on the Table of Contents.
Definition: Linker.php:1530
Html\openElement
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:251
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:783
Linker\revDeleteLink
static revDeleteLink( $query=[], $restricted=false, $delete=true)
Creates a (show/hide) link for deleting revisions/log entries.
Definition: Linker.php:2094
$wgEnableUploads
$wgEnableUploads
Uploads have to be specially set up to be secure.
Definition: DefaultSettings.php:382
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:1455
NS_USER
const NS_USER
Definition: Defines.php:67
$link
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:3005
Linker\normalizeSubpageLink
static normalizeSubpageLink( $contextTitle, $target, &$text)
Definition: Linker.php:1369
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:1125
$t
$t
Definition: testCompression.php:69
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:808
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
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
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:26
Linker\accesskey
static accesskey( $name)
Given the id of an interface element, constructs the appropriate accesskey attribute from the system ...
Definition: Linker.php:2017
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:53
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:507
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:203
Linker\buildRollbackLink
static buildRollbackLink( $rev, IContextSource $context=null, $editCount=false)
Build a raw rollback link, useful for collections of "tool" links.
Definition: Linker.php:1807
ExternalUserNames\isExternal
static isExternal( $username)
Tells whether the username is external or not.
Definition: ExternalUserNames.php:115
Linker\makeExternalImage
static makeExternalImage( $url, $alt='')
Return the code for images which were added via external links, via Parser::maybeMakeExternalImage().
Definition: Linker.php:271
MWNamespace\getCanonicalName
static getCanonicalName( $index)
Returns the canonical (English) name for a given index.
Definition: MWNamespace.php:255
Revision\DELETED_TEXT
const DELETED_TEXT
Definition: Revision.php:47
Linker\makeBrokenImageLinkObj
static makeBrokenImageLinkObj( $title, $label='', $query='', $unused1='', $unused2='', $time=false)
Make a "broken" link to an image.
Definition: Linker.php:690
$wgDisableAnonTalk
$wgDisableAnonTalk
Disable links to talk pages of anonymous users (IPs) in listings on special pages like page history,...
Definition: DefaultSettings.php:6936
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
$type
$type
Definition: testCompression.php:48