MediaWiki  master
Linker.php
Go to the documentation of this file.
1 <?php
23 namespace MediaWiki\Linker;
24 
25 use Config;
26 use ContextSource;
29 use File;
30 use HtmlArmor;
31 use IContextSource;
32 use Language;
43 use Message;
45 use Parser;
46 use RequestContext;
47 use SpecialPage;
48 use TitleValue;
49 use User;
50 use WatchedItem;
51 use Wikimedia\Assert\Assert;
52 use Wikimedia\IPUtils;
53 use Wikimedia\Parsoid\Core\TOCData;
55 use Wikimedia\RemexHtml\Serializer\SerializerNode;
56 use Xml;
57 
67 class Linker {
71  public const TOOL_LINKS_NOBLOCK = 1;
72  public const TOOL_LINKS_EMAIL = 2;
73 
116  public static function link(
117  $target, $html = null, $customAttribs = [], $query = [], $options = []
118  ) {
119  if ( !$target instanceof LinkTarget ) {
120  wfWarn( __METHOD__ . ': Requires $target to be a LinkTarget object.', 2 );
121  return "<!-- ERROR -->$html";
122  }
123 
124  $services = MediaWikiServices::getInstance();
125  $options = (array)$options;
126  if ( $options ) {
127  // Custom options, create new LinkRenderer
128  $linkRenderer = $services->getLinkRendererFactory()
129  ->createFromLegacyOptions( $options );
130  } else {
131  $linkRenderer = $services->getLinkRenderer();
132  }
133 
134  if ( $html !== null ) {
135  $text = new HtmlArmor( $html );
136  } else {
137  $text = null;
138  }
139 
140  if ( in_array( 'known', $options, true ) ) {
141  return $linkRenderer->makeKnownLink( $target, $text, $customAttribs, $query );
142  }
143 
144  if ( in_array( 'broken', $options, true ) ) {
145  return $linkRenderer->makeBrokenLink( $target, $text, $customAttribs, $query );
146  }
147 
148  if ( in_array( 'noclasses', $options, true ) ) {
149  return $linkRenderer->makePreloadedLink( $target, $text, '', $customAttribs, $query );
150  }
151 
152  return $linkRenderer->makeLink( $target, $text, $customAttribs, $query );
153  }
154 
168  public static function linkKnown(
169  $target, $html = null, $customAttribs = [],
170  $query = [], $options = [ 'known' ]
171  ) {
172  return self::link( $target, $html, $customAttribs, $query, $options );
173  }
174 
192  public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '', $hash = '' ) {
193  $nt = Title::newFromLinkTarget( $nt );
194  $attrs = [];
195  if ( $hash ) {
196  $attrs['class'] = 'mw-selflink-fragment';
197  $attrs['href'] = '#' . $hash;
198  } else {
199  // For backwards compatibility with gadgets we add selflink as well.
200  $attrs['class'] = 'mw-selflink selflink';
201  }
202  $ret = Html::rawElement( 'a', $attrs, $prefix . $html ) . $trail;
203  $hookRunner = new HookRunner( MediaWikiServices::getInstance()->getHookContainer() );
204  if ( !$hookRunner->onSelfLinkBegin( $nt, $html, $trail, $prefix, $ret ) ) {
205  return $ret;
206  }
207 
208  if ( $html == '' ) {
209  $html = htmlspecialchars( $nt->getPrefixedText() );
210  }
211  [ $inside, $trail ] = self::splitTrail( $trail );
212  return Html::rawElement( 'a', $attrs, $prefix . $html . $inside ) . $trail;
213  }
214 
225  public static function getInvalidTitleDescription( IContextSource $context, $namespace, $title ) {
226  // First we check whether the namespace exists or not.
227  if ( MediaWikiServices::getInstance()->getNamespaceInfo()->exists( $namespace ) ) {
228  if ( $namespace == NS_MAIN ) {
229  $name = $context->msg( 'blanknamespace' )->text();
230  } else {
231  $name = MediaWikiServices::getInstance()->getContentLanguage()->
232  getFormattedNsText( $namespace );
233  }
234  return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
235  }
236 
237  return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
238  }
239 
248  private static function fnamePart( $url ) {
249  $basename = strrchr( $url, '/' );
250  if ( $basename === false ) {
251  $basename = $url;
252  } else {
253  $basename = substr( $basename, 1 );
254  }
255  return $basename;
256  }
257 
268  public static function makeExternalImage( $url, $alt = '' ) {
269  if ( $alt == '' ) {
270  $alt = self::fnamePart( $url );
271  }
272  $img = '';
273  $success = ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
274  ->onLinkerMakeExternalImage( $url, $alt, $img );
275  if ( !$success ) {
276  wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
277  . "with url {$url} and alt text {$alt} to {$img}" );
278  return $img;
279  }
280  return Html::element( 'img',
281  [
282  'src' => $url,
283  'alt' => $alt
284  ]
285  );
286  }
287 
326  public static function makeImageLink( Parser $parser, LinkTarget $title,
327  $file, $frameParams = [], $handlerParams = [], $time = false,
328  $query = '', $widthOption = null
329  ) {
331  $res = null;
332  $dummy = new DummyLinker;
333  $hookRunner = new HookRunner( MediaWikiServices::getInstance()->getHookContainer() );
334  if ( !$hookRunner->onImageBeforeProduceHTML( $dummy, $title,
335  // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
336  $file, $frameParams, $handlerParams, $time, $res,
337  // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
338  $parser, $query, $widthOption )
339  ) {
340  return $res;
341  }
342 
343  if ( $file && !$file->allowInlineDisplay() ) {
344  wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . ' does not allow inline display' );
345  return self::link( $title );
346  }
347 
348  // Clean up parameters
349  $page = $handlerParams['page'] ?? false;
350  if ( !isset( $frameParams['align'] ) ) {
351  $frameParams['align'] = '';
352  }
353  if ( !isset( $frameParams['title'] ) ) {
354  $frameParams['title'] = '';
355  }
356  if ( !isset( $frameParams['class'] ) ) {
357  $frameParams['class'] = '';
358  }
359 
360  $services = MediaWikiServices::getInstance();
361  $config = $services->getMainConfig();
362  $enableLegacyMediaDOM = $config->get( MainConfigNames::ParserEnableLegacyMediaDOM );
363 
364  $classes = [];
365  if (
366  !isset( $handlerParams['width'] ) &&
367  !isset( $frameParams['manualthumb'] ) &&
368  !isset( $frameParams['framed'] )
369  ) {
370  $classes[] = 'mw-default-size';
371  }
372 
373  $prefix = $postfix = '';
374 
375  if ( $enableLegacyMediaDOM ) {
376  if ( $frameParams['align'] == 'center' ) {
377  $prefix = '<div class="center">';
378  $postfix = '</div>';
379  $frameParams['align'] = 'none';
380  }
381  }
382 
383  if ( $file && !isset( $handlerParams['width'] ) ) {
384  if ( isset( $handlerParams['height'] ) && $file->isVectorized() ) {
385  // If its a vector image, and user only specifies height
386  // we don't want it to be limited by its "normal" width.
387  $svgMaxSize = $config->get( MainConfigNames::SVGMaxSize );
388  $handlerParams['width'] = $svgMaxSize;
389  } else {
390  $handlerParams['width'] = $file->getWidth( $page );
391  }
392 
393  if ( isset( $frameParams['thumbnail'] )
394  || isset( $frameParams['manualthumb'] )
395  || isset( $frameParams['framed'] )
396  || isset( $frameParams['frameless'] )
397  || !$handlerParams['width']
398  ) {
399  $thumbLimits = $config->get( MainConfigNames::ThumbLimits );
400  $thumbUpright = $config->get( MainConfigNames::ThumbUpright );
401  if ( $widthOption === null || !isset( $thumbLimits[$widthOption] ) ) {
402  $userOptionsLookup = $services->getUserOptionsLookup();
403  $widthOption = $userOptionsLookup->getDefaultOption( 'thumbsize' );
404  }
405 
406  // Reduce width for upright images when parameter 'upright' is used
407  if ( isset( $frameParams['upright'] ) && $frameParams['upright'] == 0 ) {
408  $frameParams['upright'] = $thumbUpright;
409  }
410 
411  // For caching health: If width scaled down due to upright
412  // parameter, round to full __0 pixel to avoid the creation of a
413  // lot of odd thumbs.
414  $prefWidth = isset( $frameParams['upright'] ) ?
415  round( $thumbLimits[$widthOption] * $frameParams['upright'], -1 ) :
416  $thumbLimits[$widthOption];
417 
418  // Use width which is smaller: real image width or user preference width
419  // Unless image is scalable vector.
420  if ( !isset( $handlerParams['height'] ) && ( $handlerParams['width'] <= 0 ||
421  $prefWidth < $handlerParams['width'] || $file->isVectorized() ) ) {
422  $handlerParams['width'] = $prefWidth;
423  }
424  }
425  }
426 
427  // Parser::makeImage has a similarly named variable
428  $hasVisibleCaption = isset( $frameParams['thumbnail'] ) ||
429  isset( $frameParams['manualthumb'] ) ||
430  isset( $frameParams['framed'] );
431 
432  if ( $hasVisibleCaption ) {
433  if ( $enableLegacyMediaDOM ) {
434  // This is no longer needed in our new media output, since the
435  // default styling in content.media-common.less takes care of it;
436  // see T269704.
437 
438  # Create a thumbnail. Alignment depends on the writing direction of
439  # the page content language (right-aligned for LTR languages,
440  # left-aligned for RTL languages)
441  # If a thumbnail width has not been provided, it is set
442  # to the default user option as specified in Language*.php
443  if ( $frameParams['align'] == '' ) {
444  $frameParams['align'] = $parser->getTargetLanguage()->alignEnd();
445  }
446  }
447  return $prefix . self::makeThumbLink2(
448  $title, $file, $frameParams, $handlerParams, $time, $query,
449  $classes, $parser
450  ) . $postfix;
451  }
452 
453  $rdfaType = 'mw:File';
454 
455  if ( isset( $frameParams['frameless'] ) ) {
456  $rdfaType .= '/Frameless';
457  if ( $file ) {
458  $srcWidth = $file->getWidth( $page );
459  # For "frameless" option: do not present an image bigger than the
460  # source (for bitmap-style images). This is the same behavior as the
461  # "thumb" option does it already.
462  if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
463  $handlerParams['width'] = $srcWidth;
464  }
465  }
466  }
467 
468  if ( $file && isset( $handlerParams['width'] ) ) {
469  # Create a resized image, without the additional thumbnail features
470  $thumb = $file->transform( $handlerParams );
471  } else {
472  $thumb = false;
473  }
474 
475  if ( !$thumb || ( !$enableLegacyMediaDOM && $thumb->isError() ) ) {
476  $rdfaType = 'mw:Error ' . $rdfaType;
477  $currentExists = $file && $file->exists();
478  if ( $enableLegacyMediaDOM ) {
479  $label = $frameParams['title'];
480  } else {
481  if ( $currentExists && !$thumb ) {
482  $label = wfMessage( 'thumbnail_error', '' )->text();
483  } elseif ( $thumb && $thumb->isError() ) {
484  Assert::invariant(
485  $thumb instanceof MediaTransformError,
486  'Unknown MediaTransformOutput: ' . get_class( $thumb )
487  );
488  $label = $thumb->toText();
489  } else {
490  $label = $frameParams['alt'] ?? '';
491  }
492  }
494  $title, $label, '', '', '', (bool)$time, $handlerParams, $currentExists
495  );
496  } else {
497  self::processResponsiveImages( $file, $thumb, $handlerParams );
498  $params = [];
499  // An empty alt indicates an image is not a key part of the content
500  // and that non-visual browsers may omit it from rendering. Only
501  // set the parameter if it's explicitly requested.
502  if ( isset( $frameParams['alt'] ) ) {
503  $params['alt'] = $frameParams['alt'];
504  }
505  $params['title'] = $frameParams['title'];
506  if ( $enableLegacyMediaDOM ) {
507  $params += [
508  'valign' => $frameParams['valign'] ?? false,
509  'img-class' => $frameParams['class'],
510  ];
511  if ( isset( $frameParams['border'] ) ) {
512  $params['img-class'] .= ( $params['img-class'] !== '' ? ' ' : '' ) . 'thumbborder';
513  }
514  } else {
515  $params += [
516  'img-class' => 'mw-file-element',
517  ];
518  }
519  $params = self::getImageLinkMTOParams( $frameParams, $query, $parser ) + $params;
520  $s = $thumb->toHtml( $params );
521  }
522 
523  if ( $enableLegacyMediaDOM ) {
524  if ( $frameParams['align'] != '' ) {
525  $s = Html::rawElement(
526  'div',
527  [ 'class' => 'float' . $frameParams['align'] ],
528  $s
529  );
530  }
531  return str_replace( "\n", ' ', $prefix . $s . $postfix );
532  }
533 
534  $wrapper = 'span';
535  $caption = '';
536 
537  if ( $frameParams['align'] != '' ) {
538  $wrapper = 'figure';
539  // Possible values: mw-halign-left mw-halign-center mw-halign-right mw-halign-none
540  $classes[] = "mw-halign-{$frameParams['align']}";
541  $caption = Html::rawElement(
542  'figcaption', [], $frameParams['caption'] ?? ''
543  );
544  } elseif ( isset( $frameParams['valign'] ) ) {
545  // Possible values: mw-valign-middle mw-valign-baseline mw-valign-sub
546  // mw-valign-super mw-valign-top mw-valign-text-top mw-valign-bottom
547  // mw-valign-text-bottom
548  $classes[] = "mw-valign-{$frameParams['valign']}";
549  }
550 
551  if ( isset( $frameParams['border'] ) ) {
552  $classes[] = 'mw-image-border';
553  }
554 
555  if ( isset( $frameParams['class'] ) ) {
556  $classes[] = $frameParams['class'];
557  }
558 
559  $attribs = [
560  'class' => $classes,
561  'typeof' => $rdfaType,
562  ];
563 
564  $s = Html::rawElement( $wrapper, $attribs, $s . $caption );
565 
566  return str_replace( "\n", ' ', $s );
567  }
568 
577  public static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
578  $mtoParams = [];
579  if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
580  $mtoParams['custom-url-link'] = $frameParams['link-url'];
581  if ( isset( $frameParams['link-target'] ) ) {
582  $mtoParams['custom-target-link'] = $frameParams['link-target'];
583  }
584  if ( $parser ) {
585  $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
586  foreach ( $extLinkAttrs as $name => $val ) {
587  // Currently could include 'rel' and 'target'
588  $mtoParams['parser-extlink-' . $name] = $val;
589  }
590  }
591  } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
592  $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
593  $mtoParams['custom-title-link'] = Title::newFromLinkTarget(
594  $linkRenderer->normalizeTarget( $frameParams['link-title'] )
595  );
596  if ( isset( $frameParams['link-title-query'] ) ) {
597  $mtoParams['custom-title-link-query'] = $frameParams['link-title-query'];
598  }
599  } elseif ( !empty( $frameParams['no-link'] ) ) {
600  // No link
601  } else {
602  $mtoParams['desc-link'] = true;
603  $mtoParams['desc-query'] = $query;
604  }
605  return $mtoParams;
606  }
607 
620  public static function makeThumbLinkObj(
621  LinkTarget $title, $file, $label = '', $alt = '', $align = null,
622  $params = [], $framed = false, $manualthumb = ''
623  ) {
624  $frameParams = [
625  'alt' => $alt,
626  'caption' => $label,
627  'align' => $align
628  ];
629  $classes = [];
630  if ( $manualthumb ) {
631  $frameParams['manualthumb'] = $manualthumb;
632  } elseif ( $framed ) {
633  $frameParams['framed'] = true;
634  } elseif ( !isset( $params['width'] ) ) {
635  $classes[] = 'mw-default-size';
636  }
637  return self::makeThumbLink2(
638  $title, $file, $frameParams, $params, false, '', $classes
639  );
640  }
641 
653  public static function makeThumbLink2(
654  LinkTarget $title, $file, $frameParams = [], $handlerParams = [],
655  $time = false, $query = '', array $classes = [], ?Parser $parser = null
656  ) {
657  $exists = $file && $file->exists();
658 
659  $services = MediaWikiServices::getInstance();
660  $enableLegacyMediaDOM = $services->getMainConfig()->get( MainConfigNames::ParserEnableLegacyMediaDOM );
661 
662  $page = $handlerParams['page'] ?? false;
663  $lang = $handlerParams['lang'] ?? false;
664 
665  if ( !isset( $frameParams['align'] ) ) {
666  $frameParams['align'] = '';
667  if ( $enableLegacyMediaDOM ) {
668  $frameParams['align'] = 'right';
669  }
670  }
671  if ( !isset( $frameParams['caption'] ) ) {
672  $frameParams['caption'] = '';
673  }
674 
675  if ( empty( $handlerParams['width'] ) ) {
676  // Reduce width for upright images when parameter 'upright' is used
677  $handlerParams['width'] = isset( $frameParams['upright'] ) ? 130 : 180;
678  }
679 
680  $thumb = false;
681  $noscale = false;
682  $manualthumb = false;
683  $rdfaType = 'mw:File/Thumb';
684 
685  if ( !$exists ) {
686  // Same precedence as the $exists case
687  if ( !isset( $frameParams['manualthumb'] ) && isset( $frameParams['framed'] ) ) {
688  $rdfaType = 'mw:File/Frame';
689  }
690  $outerWidth = $handlerParams['width'] + 2;
691  } else {
692  if ( isset( $frameParams['manualthumb'] ) ) {
693  # Use manually specified thumbnail
694  $manual_title = Title::makeTitleSafe( NS_FILE, $frameParams['manualthumb'] );
695  if ( $manual_title ) {
696  $manual_img = $services->getRepoGroup()
697  ->findFile( $manual_title );
698  if ( $manual_img ) {
699  $thumb = $manual_img->getUnscaledThumb( $handlerParams );
700  $manualthumb = true;
701  }
702  }
703  } elseif ( isset( $frameParams['framed'] ) ) {
704  // Use image dimensions, don't scale
705  $thumb = $file->getUnscaledThumb( $handlerParams );
706  $noscale = true;
707  $rdfaType = 'mw:File/Frame';
708  } else {
709  # Do not present an image bigger than the source, for bitmap-style images
710  # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
711  $srcWidth = $file->getWidth( $page );
712  if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
713  $handlerParams['width'] = $srcWidth;
714  }
715  $thumb = $file->transform( $handlerParams );
716  }
717 
718  if ( $thumb ) {
719  $outerWidth = $thumb->getWidth() + 2;
720  } else {
721  $outerWidth = $handlerParams['width'] + 2;
722  }
723  }
724 
725  $url = Title::newFromLinkTarget( $title )->getLocalURL( $query );
726  $linkTitleQuery = [];
727  if ( $page || $lang ) {
728  if ( $page ) {
729  $linkTitleQuery['page'] = $page;
730  }
731  if ( $lang ) {
732  $linkTitleQuery['lang'] = $lang;
733  }
734  # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
735  # So we don't need to pass it here in $query. However, the URL for the
736  # zoom icon still needs it, so we make a unique query for it. See T16771
737  $url = wfAppendQuery( $url, $linkTitleQuery );
738  }
739 
740  if ( $manualthumb
741  && !isset( $frameParams['link-title'] )
742  && !isset( $frameParams['link-url'] )
743  && !isset( $frameParams['no-link'] ) ) {
744  $frameParams['link-title'] = $title;
745  $frameParams['link-title-query'] = $linkTitleQuery;
746  }
747 
748  if ( $frameParams['align'] != '' ) {
749  // Possible values: mw-halign-left mw-halign-center mw-halign-right mw-halign-none
750  $classes[] = "mw-halign-{$frameParams['align']}";
751  }
752 
753  if ( isset( $frameParams['class'] ) ) {
754  $classes[] = $frameParams['class'];
755  }
756 
757  $s = '';
758 
759  if ( $enableLegacyMediaDOM ) {
760  $s .= "<div class=\"thumb t{$frameParams['align']}\">"
761  . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
762  }
763 
764  if ( !$exists ) {
765  $rdfaType = 'mw:Error ' . $rdfaType;
766  $label = '';
767  if ( !$enableLegacyMediaDOM ) {
768  $label = $frameParams['alt'] ?? '';
769  }
771  $title, $label, '', '', '', (bool)$time, $handlerParams, false
772  );
773  $zoomIcon = '';
774  } elseif ( !$thumb || ( !$enableLegacyMediaDOM && $thumb->isError() ) ) {
775  $rdfaType = 'mw:Error ' . $rdfaType;
776  if ( $enableLegacyMediaDOM ) {
777  $s .= wfMessage( 'thumbnail_error', '' )->escaped();
778  } else {
779  if ( $thumb && $thumb->isError() ) {
780  Assert::invariant(
781  $thumb instanceof MediaTransformError,
782  'Unknown MediaTransformOutput: ' . get_class( $thumb )
783  );
784  $label = $thumb->toText();
785  } else {
786  $label = wfMessage( 'thumbnail_error', '' )->text();
787  }
789  $title, $label, '', '', '', (bool)$time, $handlerParams, true
790  );
791  }
792  $zoomIcon = '';
793  } else {
794  if ( !$noscale && !$manualthumb ) {
795  self::processResponsiveImages( $file, $thumb, $handlerParams );
796  }
797  $params = [];
798  // An empty alt indicates an image is not a key part of the content
799  // and that non-visual browsers may omit it from rendering. Only
800  // set the parameter if it's explicitly requested.
801  if ( isset( $frameParams['alt'] ) ) {
802  $params['alt'] = $frameParams['alt'];
803  }
804  if ( $enableLegacyMediaDOM ) {
805  $params += [
806  'img-class' => ( isset( $frameParams['class'] ) && $frameParams['class'] !== ''
807  ? $frameParams['class'] . ' '
808  : '' ) . 'thumbimage'
809  ];
810  } else {
811  $params += [
812  'img-class' => 'mw-file-element',
813  ];
814  // Only thumbs gets the magnify link
815  if ( $rdfaType === 'mw:File/Thumb' && $parser ) {
816  $params['magnify-resource'] = $url;
817  $parser->getOutput()->addModules( [ 'mediawiki.page.media' ] );
818  }
819  }
820  $params = self::getImageLinkMTOParams( $frameParams, $query, $parser ) + $params;
821  $s .= $thumb->toHtml( $params );
822  if ( isset( $frameParams['framed'] ) ) {
823  $zoomIcon = '';
824  } else {
825  $zoomIcon = Html::rawElement( 'div', [ 'class' => 'magnify' ],
826  Html::rawElement( 'a', [
827  'href' => $url,
828  'class' => 'internal',
829  'title' => wfMessage( 'thumbnail-more' )->text(),
830  ] )
831  );
832  }
833  }
834 
835  if ( $enableLegacyMediaDOM ) {
836  $s .= ' <div class="thumbcaption">' . $zoomIcon . $frameParams['caption'] . '</div></div></div>';
837  return str_replace( "\n", ' ', $s );
838  }
839 
840  $s .= Html::rawElement(
841  'figcaption', [], $frameParams['caption'] ?? ''
842  );
843 
844  $attribs = [
845  'class' => $classes,
846  'typeof' => $rdfaType,
847  ];
848 
849  $s = Html::rawElement( 'figure', $attribs, $s );
850 
851  return str_replace( "\n", ' ', $s );
852  }
853 
862  public static function processResponsiveImages( $file, $thumb, $hp ) {
863  $responsiveImages = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::ResponsiveImages );
864  if ( $responsiveImages && $thumb && !$thumb->isError() ) {
865  $hp15 = $hp;
866  $hp15['width'] = round( $hp['width'] * 1.5 );
867  $hp20 = $hp;
868  $hp20['width'] = $hp['width'] * 2;
869  if ( isset( $hp['height'] ) ) {
870  $hp15['height'] = round( $hp['height'] * 1.5 );
871  $hp20['height'] = $hp['height'] * 2;
872  }
873 
874  $thumb15 = $file->transform( $hp15 );
875  $thumb20 = $file->transform( $hp20 );
876  if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
877  $thumb->responsiveUrls['1.5'] = $thumb15->getUrl();
878  }
879  if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
880  $thumb->responsiveUrls['2'] = $thumb20->getUrl();
881  }
882  }
883  }
884 
899  public static function makeBrokenImageLinkObj(
900  $title, $label = '', $query = '', $unused1 = '', $unused2 = '',
901  $time = false, array $handlerParams = [], bool $currentExists = false
902  ) {
903  if ( !$title instanceof LinkTarget ) {
904  wfWarn( __METHOD__ . ': Requires $title to be a LinkTarget object.' );
905  return "<!-- ERROR -->" . htmlspecialchars( $label );
906  }
907 
909  $services = MediaWikiServices::getInstance();
910  $mainConfig = $services->getMainConfig();
911  $enableUploads = $mainConfig->get( MainConfigNames::EnableUploads );
912  $uploadMissingFileUrl = $mainConfig->get( MainConfigNames::UploadMissingFileUrl );
913  $uploadNavigationUrl = $mainConfig->get( MainConfigNames::UploadNavigationUrl );
914  if ( $label == '' ) {
915  $label = $title->getPrefixedText();
916  }
917 
918  $html = Html::element( 'span', [
919  'class' => 'mw-file-element mw-broken-media',
920  // These data attributes are used to dynamically size the span, see T273013
921  'data-width' => $handlerParams['width'] ?? null,
922  'data-height' => $handlerParams['height'] ?? null,
923  ], $label );
924 
925  if ( $mainConfig->get( MainConfigNames::ParserEnableLegacyMediaDOM ) ) {
926  $html = htmlspecialchars( $label, ENT_COMPAT );
927  }
928 
929  $repoGroup = $services->getRepoGroup();
930  $currentExists = $currentExists ||
931  ( $time && $repoGroup->findFile( $title ) !== false );
932 
933  if ( ( $uploadMissingFileUrl || $uploadNavigationUrl || $enableUploads )
934  && !$currentExists
935  ) {
936  if (
937  $title->inNamespace( NS_FILE ) &&
938  $repoGroup->getLocalRepo()->checkRedirect( $title )
939  ) {
940  // We already know it's a redirect, so mark it accordingly
941  return self::link(
942  $title,
943  $html,
944  [ 'class' => 'mw-redirect' ],
945  wfCgiToArray( $query ),
946  [ 'known', 'noclasses' ]
947  );
948  }
949  return Html::rawElement( 'a', [
950  'href' => self::getUploadUrl( $title, $query ),
951  'class' => 'new',
952  'title' => $title->getPrefixedText()
953  ], $html );
954  }
955  return self::link(
956  $title,
957  $html,
958  [],
959  wfCgiToArray( $query ),
960  [ 'known', 'noclasses' ]
961  );
962  }
963 
972  protected static function getUploadUrl( $destFile, $query = '' ) {
973  $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
974  $uploadMissingFileUrl = $mainConfig->get( MainConfigNames::UploadMissingFileUrl );
975  $uploadNavigationUrl = $mainConfig->get( MainConfigNames::UploadNavigationUrl );
976  $q = 'wpDestFile=' . Title::newFromLinkTarget( $destFile )->getPartialURL();
977  if ( $query != '' ) {
978  $q .= '&' . $query;
979  }
980 
981  if ( $uploadMissingFileUrl ) {
982  return wfAppendQuery( $uploadMissingFileUrl, $q );
983  }
984 
985  if ( $uploadNavigationUrl ) {
986  return wfAppendQuery( $uploadNavigationUrl, $q );
987  }
988 
989  $upload = SpecialPage::getTitleFor( 'Upload' );
990 
991  return $upload->getLocalURL( $q );
992  }
993 
1003  public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
1004  $img = MediaWikiServices::getInstance()->getRepoGroup()->findFile(
1005  $title, [ 'time' => $time ]
1006  );
1007  return self::makeMediaLinkFile( $title, $img, $html );
1008  }
1009 
1022  public static function makeMediaLinkFile( LinkTarget $title, $file, $html = '' ) {
1023  if ( $file && $file->exists() ) {
1024  $url = $file->getUrl();
1025  $class = 'internal';
1026  } else {
1027  $url = self::getUploadUrl( $title );
1028  $class = 'new';
1029  }
1030 
1031  $alt = $title->getText();
1032  if ( $html == '' ) {
1033  $html = $alt;
1034  }
1035 
1036  $ret = '';
1037  $attribs = [
1038  'href' => $url,
1039  'class' => $class,
1040  'title' => $alt
1041  ];
1042 
1043  if ( !( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onLinkerMakeMediaLinkFile(
1044  Title::newFromLinkTarget( $title ), $file, $html, $attribs, $ret )
1045  ) {
1046  wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
1047  . "with url {$url} and text {$html} to {$ret}" );
1048  return $ret;
1049  }
1050 
1051  return Html::rawElement( 'a', $attribs, $html );
1052  }
1053 
1064  public static function specialLink( $name, $key = '' ) {
1065  $queryPos = strpos( $name, '?' );
1066  if ( $queryPos !== false ) {
1067  $getParams = wfCgiToArray( substr( $name, $queryPos + 1 ) );
1068  $name = substr( $name, 0, $queryPos );
1069  } else {
1070  $getParams = [];
1071  }
1072 
1073  $slashPos = strpos( $name, '/' );
1074  if ( $slashPos !== false ) {
1075  $subpage = substr( $name, $slashPos + 1 );
1076  $name = substr( $name, 0, $slashPos );
1077  } else {
1078  $subpage = false;
1079  }
1080 
1081  if ( $key == '' ) {
1082  $key = strtolower( $name );
1083  }
1084 
1085  return self::linkKnown(
1086  SpecialPage::getTitleFor( $name, $subpage ),
1087  wfMessage( $key )->escaped(),
1088  [],
1089  $getParams
1090  );
1091  }
1092 
1111  public static function makeExternalLink( $url, $text, $escape = true,
1112  $linktype = '', $attribs = [], $title = null
1113  ) {
1114  global $wgTitle;
1115  $class = 'external';
1116  if ( $linktype ) {
1117  $class .= " $linktype";
1118  }
1119  if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1120  $class .= " {$attribs['class']}";
1121  }
1122  $attribs['class'] = $class;
1123 
1124  if ( $escape ) {
1125  $text = htmlspecialchars( $text, ENT_COMPAT );
1126  }
1127 
1128  if ( !$title ) {
1129  $title = $wgTitle;
1130  }
1131  $newRel = Parser::getExternalLinkRel( $url, $title );
1132  if ( !isset( $attribs['rel'] ) || $attribs['rel'] === '' ) {
1133  $attribs['rel'] = $newRel;
1134  } elseif ( $newRel !== null ) {
1135  // Merge the rel attributes.
1136  $newRels = explode( ' ', $newRel );
1137  $oldRels = explode( ' ', $attribs['rel'] );
1138  $combined = array_unique( array_merge( $newRels, $oldRels ) );
1139  $attribs['rel'] = implode( ' ', $combined );
1140  }
1141  $link = '';
1142  $success = ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onLinkerMakeExternalLink(
1143  $url, $text, $link, $attribs, $linktype );
1144  if ( !$success ) {
1145  wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
1146  . "with url {$url} and text {$text} to {$link}" );
1147  return $link;
1148  }
1149  $attribs['href'] = $url;
1150  return Html::rawElement( 'a', $attribs, $text );
1151  }
1152 
1165  public static function userLink(
1166  $userId,
1167  $userName,
1168  $altUserName = false,
1169  $attributes = []
1170  ) {
1171  if ( $userName === '' || $userName === false || $userName === null ) {
1172  wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1173  'that need to be fixed?' );
1174  return wfMessage( 'empty-username' )->parse();
1175  }
1176 
1177  $classes = 'mw-userlink';
1178  if ( MediaWikiServices::getInstance()->getTempUserConfig()->isTempName( $userName ) ) {
1179  $classes .= ' mw-tempuserlink';
1180  $page = SpecialPage::getTitleValueFor( 'Contributions', $userName );
1181  } elseif ( $userId == 0 ) {
1182  $page = ExternalUserNames::getUserLinkTitle( $userName );
1183 
1184  if ( ExternalUserNames::isExternal( $userName ) ) {
1185  $classes .= ' mw-extuserlink';
1186  } elseif ( $altUserName === false ) {
1187  $altUserName = IPUtils::prettifyIP( $userName );
1188  }
1189  $classes .= ' mw-anonuserlink'; // Separate link class for anons (T45179)
1190  } else {
1191  $page = TitleValue::tryNew( NS_USER, strtr( $userName, ' ', '_' ) );
1192  }
1193 
1194  // Wrap the output with <bdi> tags for directionality isolation
1195  $linkText =
1196  '<bdi>' . htmlspecialchars( $altUserName !== false ? $altUserName : $userName ) . '</bdi>';
1197 
1198  if ( isset( $attributes['class'] ) ) {
1199  $attributes['class'] .= ' ' . $classes;
1200  } else {
1201  $attributes['class'] = $classes;
1202  }
1203 
1204  return $page
1205  ? self::link( $page, $linkText, $attributes )
1206  : Html::rawElement( 'span', $attributes, $linkText );
1207  }
1208 
1223  public static function userToolLinks(
1224  $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null,
1225  $useParentheses = true
1226  ) {
1227  if ( $userText === '' ) {
1228  wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1229  'that need to be fixed?' );
1230  return ' ' . wfMessage( 'empty-username' )->parse();
1231  }
1232  global $wgLang;
1233  $services = MediaWikiServices::getInstance();
1234  $disableAnonTalk = $services->getMainConfig()->get( MainConfigNames::DisableAnonTalk );
1235  $talkable = !( $disableAnonTalk && $userId == 0 );
1236  $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1237  $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1238 
1239  if ( $userId == 0 && ExternalUserNames::isExternal( $userText ) ) {
1240  // No tools for an external user
1241  return '';
1242  }
1243 
1244  $items = [];
1245  if ( $talkable ) {
1246  $items[] = self::userTalkLink( $userId, $userText );
1247  }
1248  if ( $userId ) {
1249  // check if the user has an edit
1250  $attribs = [];
1251  $attribs['class'] = 'mw-usertoollinks-contribs';
1252  if ( $redContribsWhenNoEdits ) {
1253  if ( intval( $edits ) === 0 && $edits !== 0 ) {
1254  $user = User::newFromId( $userId );
1255  $edits = $user->getEditCount();
1256  }
1257  if ( $edits === 0 ) {
1258  // Note: "new" class is inappropriate here, as "new" class
1259  // should only be used for pages that do not exist.
1260  $attribs['class'] .= ' mw-usertoollinks-contribs-no-edits';
1261  }
1262  }
1263  $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1264 
1265  $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1266  }
1267  $userCanBlock = RequestContext::getMain()->getAuthority()->isAllowed( 'block' );
1268  if ( $blockable && $userCanBlock ) {
1269  $items[] = self::blockLink( $userId, $userText );
1270  }
1271 
1272  $user = RequestContext::getMain()->getUser();
1273  if ( $addEmailLink && $user->canSendEmail() ) {
1274  $items[] = self::emailLink( $userId, $userText );
1275  }
1276 
1277  ( new HookRunner( $services->getHookContainer() ) )->onUserToolLinksEdit( $userId, $userText, $items );
1278 
1279  if ( !$items ) {
1280  return '';
1281  }
1282 
1283  if ( $useParentheses ) {
1284  return wfMessage( 'word-separator' )->escaped()
1285  . '<span class="mw-usertoollinks">'
1286  . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1287  . '</span>';
1288  }
1289 
1290  $tools = [];
1291  foreach ( $items as $tool ) {
1292  $tools[] = Html::rawElement( 'span', [], $tool );
1293  }
1294  return ' <span class="mw-usertoollinks mw-changeslist-links">' .
1295  implode( ' ', $tools ) . '</span>';
1296  }
1297 
1307  public static function userToolLinksRedContribs(
1308  $userId, $userText, $edits = null, $useParentheses = true
1309  ) {
1310  return self::userToolLinks( $userId, $userText, true, 0, $edits, $useParentheses );
1311  }
1312 
1319  public static function userTalkLink( $userId, $userText ) {
1320  if ( $userText === '' ) {
1321  wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1322  'that need to be fixed?' );
1323  return wfMessage( 'empty-username' )->parse();
1324  }
1325 
1326  $userTalkPage = TitleValue::tryNew( NS_USER_TALK, strtr( $userText, ' ', '_' ) );
1327  $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-talk' ];
1328  $linkText = wfMessage( 'talkpagelinktext' )->escaped();
1329 
1330  return $userTalkPage
1331  ? self::link( $userTalkPage, $linkText, $moreLinkAttribs )
1332  : Html::rawElement( 'span', $moreLinkAttribs, $linkText );
1333  }
1334 
1341  public static function blockLink( $userId, $userText ) {
1342  if ( $userText === '' ) {
1343  wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1344  'that need to be fixed?' );
1345  return wfMessage( 'empty-username' )->parse();
1346  }
1347 
1348  $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1349  $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-block' ];
1350 
1351  return self::link( $blockPage,
1352  wfMessage( 'blocklink' )->escaped(),
1353  $moreLinkAttribs
1354  );
1355  }
1356 
1362  public static function emailLink( $userId, $userText ) {
1363  if ( $userText === '' ) {
1364  wfLogWarning( __METHOD__ . ' received an empty username. Are there database errors ' .
1365  'that need to be fixed?' );
1366  return wfMessage( 'empty-username' )->parse();
1367  }
1368 
1369  $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1370  $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-mail' ];
1371  return self::link( $emailPage,
1372  wfMessage( 'emaillink' )->escaped(),
1373  $moreLinkAttribs
1374  );
1375  }
1376 
1388  public static function revUserLink( RevisionRecord $revRecord, $isPublic = false ) {
1389  // TODO inject authority
1390  $authority = RequestContext::getMain()->getAuthority();
1391 
1392  $revUser = $revRecord->getUser(
1394  $authority
1395  );
1396  if ( $revUser ) {
1397  $link = self::userLink( $revUser->getId(), $revUser->getName() );
1398  } else {
1399  // User is deleted and we can't (or don't want to) view it
1400  $link = wfMessage( 'rev-deleted-user' )->escaped();
1401  }
1402 
1403  if ( $revRecord->isDeleted( RevisionRecord::DELETED_USER ) ) {
1404  $class = self::getRevisionDeletedClass( $revRecord );
1405  return '<span class="' . $class . '">' . $link . '</span>';
1406  }
1407  return $link;
1408  }
1409 
1416  public static function getRevisionDeletedClass( RevisionRecord $revisionRecord ): string {
1417  $class = 'history-deleted';
1418  if ( $revisionRecord->isDeleted( RevisionRecord::DELETED_RESTRICTED ) ) {
1419  $class .= ' mw-history-suppressed';
1420  }
1421  return $class;
1422  }
1423 
1436  public static function revUserTools(
1437  RevisionRecord $revRecord,
1438  $isPublic = false,
1439  $useParentheses = true
1440  ) {
1441  // TODO inject authority
1442  $authority = RequestContext::getMain()->getAuthority();
1443 
1444  $revUser = $revRecord->getUser(
1446  $authority
1447  );
1448  if ( $revUser ) {
1449  $link = self::userLink(
1450  $revUser->getId(),
1451  $revUser->getName(),
1452  false,
1453  [ 'data-mw-revid' => $revRecord->getId() ]
1454  ) . self::userToolLinks(
1455  $revUser->getId(),
1456  $revUser->getName(),
1457  false,
1458  0,
1459  null,
1460  $useParentheses
1461  );
1462  } else {
1463  // User is deleted and we can't (or don't want to) view it
1464  $link = wfMessage( 'rev-deleted-user' )->escaped();
1465  }
1466 
1467  if ( $revRecord->isDeleted( RevisionRecord::DELETED_USER ) ) {
1468  $class = self::getRevisionDeletedClass( $revRecord );
1469  return ' <span class="' . $class . ' mw-userlink">' . $link . '</span>';
1470  }
1471  return $link;
1472  }
1473 
1484  public static function expandLocalLinks( string $html ) {
1486  $html,
1487  static function ( SerializerNode $node ): bool {
1488  return $node->name === 'a' && isset( $node->attrs['href'] );
1489  },
1490  static function ( SerializerNode $node ): SerializerNode {
1491  $node->attrs['href'] =
1492  wfExpandUrl( $node->attrs['href'], PROTO_RELATIVE );
1493  return $node;
1494  }
1495  );
1496  }
1497 
1518  public static function formatComment(
1519  $comment, $title = null, $local = false, $wikiId = null
1520  ) {
1521  $formatter = MediaWikiServices::getInstance()->getCommentFormatter();
1522  return $formatter->format( $comment, $title, $local, $wikiId );
1523  }
1524 
1544  public static function formatLinksInComment(
1545  $comment, $title = null, $local = false, $wikiId = null
1546  ) {
1547  $formatter = MediaWikiServices::getInstance()->getCommentFormatter();
1548  return $formatter->formatLinksUnsafe( $comment, $title, $local, $wikiId );
1549  }
1550 
1557  public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1558  # Valid link forms:
1559  # Foobar -- normal
1560  # :Foobar -- override special treatment of prefix (images, language links)
1561  # /Foobar -- convert to CurrentPage/Foobar
1562  # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1563  # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1564  # ../Foobar -- convert to CurrentPage/Foobar,
1565  # (from CurrentPage/CurrentSubPage)
1566  # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1567  # (from CurrentPage/CurrentSubPage)
1568 
1569  $ret = $target; # default return value is no change
1570 
1571  # Some namespaces don't allow subpages,
1572  # so only perform processing if subpages are allowed
1573  if (
1574  $contextTitle && MediaWikiServices::getInstance()->getNamespaceInfo()->
1575  hasSubpages( $contextTitle->getNamespace() )
1576  ) {
1577  $hash = strpos( $target, '#' );
1578  if ( $hash !== false ) {
1579  $suffix = substr( $target, $hash );
1580  $target = substr( $target, 0, $hash );
1581  } else {
1582  $suffix = '';
1583  }
1584  # T9425
1585  $target = trim( $target );
1586  $contextPrefixedText = MediaWikiServices::getInstance()->getTitleFormatter()->
1587  getPrefixedText( $contextTitle );
1588  # Look at the first character
1589  if ( $target != '' && $target[0] === '/' ) {
1590  # / at end means we don't want the slash to be shown
1591  $m = [];
1592  $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1593  if ( $trailingSlashes ) {
1594  $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1595  } else {
1596  $noslash = substr( $target, 1 );
1597  }
1598 
1599  $ret = $contextPrefixedText . '/' . trim( $noslash ) . $suffix;
1600  if ( $text === '' ) {
1601  $text = $target . $suffix;
1602  } # this might be changed for ugliness reasons
1603  } else {
1604  # check for .. subpage backlinks
1605  $dotdotcount = 0;
1606  $nodotdot = $target;
1607  while ( str_starts_with( $nodotdot, '../' ) ) {
1608  ++$dotdotcount;
1609  $nodotdot = substr( $nodotdot, 3 );
1610  }
1611  if ( $dotdotcount > 0 ) {
1612  $exploded = explode( '/', $contextPrefixedText );
1613  if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1614  $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1615  # / at the end means don't show full path
1616  if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1617  $nodotdot = rtrim( $nodotdot, '/' );
1618  if ( $text === '' ) {
1619  $text = $nodotdot . $suffix;
1620  }
1621  }
1622  $nodotdot = trim( $nodotdot );
1623  if ( $nodotdot != '' ) {
1624  $ret .= '/' . $nodotdot;
1625  }
1626  $ret .= $suffix;
1627  }
1628  }
1629  }
1630  }
1631 
1632  return $ret;
1633  }
1634 
1654  public static function commentBlock(
1655  $comment, $title = null, $local = false, $wikiId = null, $useParentheses = true
1656  ) {
1657  return MediaWikiServices::getInstance()->getCommentFormatter()
1658  ->formatBlock( $comment, $title, $local, $wikiId, $useParentheses );
1659  }
1660 
1676  public static function revComment(
1677  RevisionRecord $revRecord,
1678  $local = false,
1679  $isPublic = false,
1680  $useParentheses = true
1681  ) {
1682  $authority = RequestContext::getMain()->getAuthority();
1683  $formatter = MediaWikiServices::getInstance()->getCommentFormatter();
1684  return $formatter->formatRevision( $revRecord, $authority, $local, $isPublic, $useParentheses );
1685  }
1686 
1692  public static function formatRevisionSize( $size ) {
1693  if ( $size == 0 ) {
1694  $stxt = wfMessage( 'historyempty' )->escaped();
1695  } else {
1696  $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1697  }
1698  return "<span class=\"history-size mw-diff-bytes\" data-mw-bytes=\"$size\">$stxt</span>";
1699  }
1700 
1707  public static function tocIndent() {
1708  return "\n<ul>\n";
1709  }
1710 
1718  public static function tocUnindent( $level ) {
1719  return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1720  }
1721 
1733  public static function tocLine( $linkAnchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1734  $classes = "toclevel-$level";
1735 
1736  // Parser.php used to suppress tocLine by setting $sectionindex to false.
1737  // In those circumstances, we can now encounter '' or a "T-" prefixed index
1738  // for when the section comes from templates.
1739  if ( $sectionIndex !== false && $sectionIndex !== '' && !str_starts_with( $sectionIndex, "T-" ) ) {
1740  $classes .= " tocsection-$sectionIndex";
1741  }
1742 
1743  // <li class="$classes"><a href="#$linkAnchor"><span class="tocnumber">
1744  // $tocnumber</span> <span class="toctext">$tocline</span></a>
1745  return Html::openElement( 'li', [ 'class' => $classes ] )
1746  . Html::rawElement( 'a',
1747  [ 'href' => "#$linkAnchor" ],
1748  Html::element( 'span', [ 'class' => 'tocnumber' ], $tocnumber )
1749  . ' '
1750  . Html::rawElement( 'span', [ 'class' => 'toctext' ], $tocline )
1751  );
1752  }
1753 
1761  public static function tocLineEnd() {
1762  return "</li>\n";
1763  }
1764 
1773  public static function tocList( $toc, Language $lang = null ) {
1774  $lang ??= RequestContext::getMain()->getLanguage();
1775 
1776  $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1777 
1778  return '<div id="toc" class="toc" role="navigation" aria-labelledby="mw-toc-heading">'
1779  . Html::element( 'input', [
1780  'type' => 'checkbox',
1781  'role' => 'button',
1782  'id' => 'toctogglecheckbox',
1783  'class' => 'toctogglecheckbox',
1784  'style' => 'display:none',
1785  ] )
1786  . Html::openElement( 'div', [
1787  'class' => 'toctitle',
1788  'lang' => $lang->getHtmlCode(),
1789  'dir' => $lang->getDir(),
1790  ] )
1791  . '<h2 id="mw-toc-heading">' . $title . '</h2>'
1792  . '<span class="toctogglespan">'
1793  . Html::label( '', 'toctogglecheckbox', [
1794  'class' => 'toctogglelabel',
1795  ] )
1796  . '</span>'
1797  . '</div>'
1798  . $toc
1799  . "</ul>\n</div>\n";
1800  }
1801 
1813  public static function generateTOC( ?TOCData $tocData, Language $lang = null, array $options = [] ): string {
1814  $toc = '';
1815  $lastLevel = 0;
1816  $maxTocLevel = $options['maxtoclevel'] ?? null;
1817  if ( $maxTocLevel === null ) {
1818  // Use wiki-configured default
1819  $services = MediaWikiServices::getInstance();
1820  $config = $services->getMainConfig();
1821  $maxTocLevel = $config->get( MainConfigNames::MaxTocLevel );
1822  }
1823  foreach ( ( $tocData ? $tocData->getSections() : [] ) as $section ) {
1824  $tocLevel = $section->tocLevel;
1825  if ( $tocLevel < $maxTocLevel ) {
1826  if ( $tocLevel > $lastLevel ) {
1827  $toc .= self::tocIndent();
1828  } elseif ( $tocLevel < $lastLevel ) {
1829  if ( $lastLevel < $maxTocLevel ) {
1830  $toc .= self::tocUnindent(
1831  $lastLevel - $tocLevel );
1832  } else {
1833  $toc .= self::tocLineEnd();
1834  }
1835  } else {
1836  $toc .= self::tocLineEnd();
1837  }
1838 
1839  $toc .= self::tocLine( $section->linkAnchor,
1840  $section->line, $section->number,
1841  $tocLevel, $section->index );
1842  $lastLevel = $tocLevel;
1843  }
1844  }
1845  if ( $lastLevel < $maxTocLevel && $lastLevel > 0 ) {
1846  $toc .= self::tocUnindent( $lastLevel - 1 );
1847  }
1848  return self::tocList( $toc, $lang );
1849  }
1850 
1867  public static function makeHeadline( $level, $attribs, $anchor, $html,
1868  $link, $fallbackAnchor = false
1869  ) {
1870  $anchorEscaped = htmlspecialchars( $anchor, ENT_COMPAT );
1871  $fallback = '';
1872  if ( $fallbackAnchor !== false && $fallbackAnchor !== $anchor ) {
1873  $fallbackAnchor = htmlspecialchars( $fallbackAnchor, ENT_COMPAT );
1874  $fallback = "<span id=\"$fallbackAnchor\"></span>";
1875  }
1876  return "<h$level$attribs"
1877  . "$fallback<span class=\"mw-headline\" id=\"$anchorEscaped\">$html</span>"
1878  . $link
1879  . "</h$level>";
1880  }
1881 
1888  public static function splitTrail( $trail ) {
1889  $regex = MediaWikiServices::getInstance()->getContentLanguage()->linkTrail();
1890  $inside = '';
1891  if ( $trail !== '' && preg_match( $regex, $trail, $m ) ) {
1892  [ , $inside, $trail ] = $m;
1893  }
1894  return [ $inside, $trail ];
1895  }
1896 
1927  public static function generateRollback(
1928  RevisionRecord $revRecord,
1929  IContextSource $context = null,
1930  $options = []
1931  ) {
1932  $context ??= RequestContext::getMain();
1933 
1934  $editCount = self::getRollbackEditCount( $revRecord );
1935  if ( $editCount === false ) {
1936  return '';
1937  }
1938 
1939  $inner = self::buildRollbackLink( $revRecord, $context, $editCount );
1940 
1941  $services = MediaWikiServices::getInstance();
1942  // Allow extensions to modify the rollback link.
1943  // Abort further execution if the extension wants full control over the link.
1944  if ( !( new HookRunner( $services->getHookContainer() ) )->onLinkerGenerateRollbackLink(
1945  $revRecord, $context, $options, $inner ) ) {
1946  return $inner;
1947  }
1948 
1949  if ( !in_array( 'noBrackets', $options, true ) ) {
1950  $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1951  }
1952 
1953  if ( $services->getUserOptionsLookup()
1954  ->getBoolOption( $context->getUser(), 'showrollbackconfirmation' )
1955  ) {
1956  $stats = $services->getStatsdDataFactory();
1957  $stats->increment( 'rollbackconfirmation.event.load' );
1958  $context->getOutput()->addModules( 'mediawiki.misc-authed-curate' );
1959  }
1960 
1961  return '<span class="mw-rollback-link">' . $inner . '</span>';
1962  }
1963 
1982  public static function getRollbackEditCount( RevisionRecord $revRecord, $verify = true ) {
1983  if ( func_num_args() > 1 ) {
1984  wfDeprecated( __METHOD__ . ' with $verify parameter', '1.40' );
1985  }
1986  $showRollbackEditCount = MediaWikiServices::getInstance()->getMainConfig()
1987  ->get( MainConfigNames::ShowRollbackEditCount );
1988 
1989  if ( !is_int( $showRollbackEditCount ) || !$showRollbackEditCount > 0 ) {
1990  // Nothing has happened, indicate this by returning 'null'
1991  return null;
1992  }
1993 
1994  $dbr = wfGetDB( DB_REPLICA );
1995 
1996  // Up to the value of $wgShowRollbackEditCount revisions are counted
1997  $revQuery = MediaWikiServices::getInstance()->getRevisionStore()->getQueryInfo();
1998  $res = $dbr->newSelectQueryBuilder()
1999  ->select( [ 'rev_user_text' => $revQuery['fields']['rev_user_text'], 'rev_deleted' ] )
2000  ->tables( $revQuery['tables'] )
2001  ->where( [ 'rev_page' => $revRecord->getPageId() ] )
2002  ->joinConds( $revQuery['joins'] )
2003  ->useIndex( [ 'revision' => 'rev_page_timestamp' ] )
2004  ->orderBy( [ 'rev_timestamp', 'rev_id' ], SelectQueryBuilder::SORT_DESC )
2005  ->limit( $showRollbackEditCount + 1 )
2006  ->caller( __METHOD__ )
2007  ->fetchResultSet();
2008 
2009  $revUser = $revRecord->getUser( RevisionRecord::RAW );
2010  $revUserText = $revUser ? $revUser->getName() : '';
2011 
2012  $editCount = 0;
2013  $moreRevs = false;
2014  foreach ( $res as $row ) {
2015  if ( $row->rev_user_text != $revUserText ) {
2016  if ( $row->rev_deleted & RevisionRecord::DELETED_TEXT
2017  || $row->rev_deleted & RevisionRecord::DELETED_USER
2018  ) {
2019  // If the user or the text of the revision we might rollback
2020  // to is deleted in some way we can't rollback. Similar to
2021  // the checks in WikiPage::commitRollback.
2022  return false;
2023  }
2024  $moreRevs = true;
2025  break;
2026  }
2027  $editCount++;
2028  }
2029 
2030  if ( $editCount <= $showRollbackEditCount && !$moreRevs ) {
2031  // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
2032  // and there weren't any other revisions. That means that the current user is the only
2033  // editor, so we can't rollback
2034  return false;
2035  }
2036  return $editCount;
2037  }
2038 
2053  public static function buildRollbackLink(
2054  RevisionRecord $revRecord,
2055  IContextSource $context = null,
2056  $editCount = false
2057  ) {
2058  $config = MediaWikiServices::getInstance()->getMainConfig();
2059  $showRollbackEditCount = $config->get( MainConfigNames::ShowRollbackEditCount );
2060  $miserMode = $config->get( MainConfigNames::MiserMode );
2061  // To config which pages are affected by miser mode
2062  $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
2063 
2064  $context ??= RequestContext::getMain();
2065 
2066  $title = $revRecord->getPageAsLinkTarget();
2067  $revUser = $revRecord->getUser();
2068  $revUserText = $revUser ? $revUser->getName() : '';
2069 
2070  $query = [
2071  'action' => 'rollback',
2072  'from' => $revUserText,
2073  'token' => $context->getUser()->getEditToken( 'rollback' ),
2074  ];
2075 
2076  $attrs = [
2077  'data-mw' => 'interface',
2078  'title' => $context->msg( 'tooltip-rollback' )->text()
2079  ];
2080 
2081  $options = [ 'known', 'noclasses' ];
2082 
2083  if ( $context->getRequest()->getBool( 'bot' ) ) {
2084  // T17999
2085  $query['hidediff'] = '1';
2086  $query['bot'] = '1';
2087  }
2088 
2089  if ( $miserMode ) {
2090  foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
2091  if ( $context->getTitle()->isSpecial( $specialPage ) ) {
2092  $showRollbackEditCount = false;
2093  break;
2094  }
2095  }
2096  }
2097 
2098  // The edit count can be 0 on replica lag, fall back to the generic rollbacklink message
2099  $msg = [ 'rollbacklink' ];
2100  if ( is_int( $showRollbackEditCount ) && $showRollbackEditCount > 0 ) {
2101  if ( !is_numeric( $editCount ) ) {
2102  $editCount = self::getRollbackEditCount( $revRecord );
2103  }
2104 
2105  if ( $editCount > $showRollbackEditCount ) {
2106  $msg = [ 'rollbacklinkcount-morethan', Message::numParam( $showRollbackEditCount ) ];
2107  } elseif ( $editCount ) {
2108  $msg = [ 'rollbacklinkcount', Message::numParam( $editCount ) ];
2109  }
2110  }
2111 
2112  $html = $context->msg( ...$msg )->parse();
2113  return self::link( $title, $html, $attrs, $query, $options );
2114  }
2115 
2124  public static function formatHiddenCategories( $hiddencats ) {
2125  $outText = '';
2126  if ( count( $hiddencats ) > 0 ) {
2127  # Construct the HTML
2128  $outText = '<div class="mw-hiddenCategoriesExplanation">';
2129  $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
2130  $outText .= "</div><ul>\n";
2131 
2132  foreach ( $hiddencats as $titleObj ) {
2133  # If it's hidden, it must exist - no need to check with a LinkBatch
2134  $outText .= '<li>'
2135  . self::link( $titleObj, null, [], [], 'known' )
2136  . "</li>\n";
2137  }
2138  $outText .= '</ul>';
2139  }
2140  return $outText;
2141  }
2142 
2146  private static function getContextFromMain() {
2147  $context = RequestContext::getMain();
2148  $context = new DerivativeContext( $context );
2149  return $context;
2150  }
2151 
2169  public static function titleAttrib( $name, $options = null, array $msgParams = [], $localizer = null ) {
2170  if ( !$localizer ) {
2171  $localizer = self::getContextFromMain();
2172  }
2173  $message = $localizer->msg( "tooltip-$name", $msgParams );
2174  if ( $message->isDisabled() ) {
2175  $tooltip = false;
2176  } else {
2177  $tooltip = $message->text();
2178  # Compatibility: formerly some tooltips had [alt-.] hardcoded
2179  $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2180  }
2181 
2182  $options = (array)$options;
2183 
2184  if ( in_array( 'nonexisting', $options ) ) {
2185  $tooltip = $localizer->msg( 'red-link-title', $tooltip ?: '' )->text();
2186  }
2187  if ( in_array( 'withaccess', $options ) ) {
2188  $accesskey = self::accesskey( $name, $localizer );
2189  if ( $accesskey !== false ) {
2190  // Should be build the same as in jquery.accessKeyLabel.js
2191  if ( $tooltip === false || $tooltip === '' ) {
2192  $tooltip = $localizer->msg( 'brackets', $accesskey )->text();
2193  } else {
2194  $tooltip .= $localizer->msg( 'word-separator' )->text();
2195  $tooltip .= $localizer->msg( 'brackets', $accesskey )->text();
2196  }
2197  }
2198  }
2199 
2200  return $tooltip;
2201  }
2202 
2203  public static $accesskeycache;
2204 
2217  public static function accesskey( $name, $localizer = null ) {
2218  if ( !isset( self::$accesskeycache[$name] ) ) {
2219  if ( !$localizer ) {
2220  $localizer = self::getContextFromMain();
2221  }
2222  $msg = $localizer->msg( "accesskey-$name" );
2223  self::$accesskeycache[$name] = $msg->isDisabled() ? false : $msg->plain();
2224  }
2225  return self::$accesskeycache[$name];
2226  }
2227 
2242  public static function getRevDeleteLink(
2243  Authority $performer,
2244  RevisionRecord $revRecord,
2246  ) {
2247  $canHide = $performer->isAllowed( 'deleterevision' );
2248  $canHideHistory = $performer->isAllowed( 'deletedhistory' );
2249  if ( !$canHide && !( $revRecord->getVisibility() && $canHideHistory ) ) {
2250  return '';
2251  }
2252 
2253  if ( !$revRecord->userCan( RevisionRecord::DELETED_RESTRICTED, $performer ) ) {
2254  return self::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2255  }
2256  $prefixedDbKey = MediaWikiServices::getInstance()->getTitleFormatter()->
2257  getPrefixedDBkey( $title );
2258  if ( $revRecord->getId() ) {
2259  // RevDelete links using revision ID are stable across
2260  // page deletion and undeletion; use when possible.
2261  $query = [
2262  'type' => 'revision',
2263  'target' => $prefixedDbKey,
2264  'ids' => $revRecord->getId()
2265  ];
2266  } else {
2267  // Older deleted entries didn't save a revision ID.
2268  // We have to refer to these by timestamp, ick!
2269  $query = [
2270  'type' => 'archive',
2271  'target' => $prefixedDbKey,
2272  'ids' => $revRecord->getTimestamp()
2273  ];
2274  }
2275  return self::revDeleteLink(
2276  $query,
2277  $revRecord->isDeleted( RevisionRecord::DELETED_RESTRICTED ),
2278  $canHide
2279  );
2280  }
2281 
2294  public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2295  $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2296  $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2297  $html = wfMessage( $msgKey )->escaped();
2298  $tag = $restricted ? 'strong' : 'span';
2299  $link = self::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2300  return Xml::tags(
2301  $tag,
2302  [ 'class' => 'mw-revdelundel-link' ],
2303  wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2304  );
2305  }
2306 
2318  public static function revDeleteLinkDisabled( $delete = true ) {
2319  $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2320  $html = wfMessage( $msgKey )->escaped();
2321  $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2322  return Xml::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2323  }
2324 
2336  private static function updateWatchstarTooltipMessage(
2337  string &$tooltip, array &$msgParams, $config, $user, $relevantTitle
2338  ): void {
2339  if ( !$config || !$user || !$relevantTitle ) {
2340  $mainContext = self::getContextFromMain();
2341  if ( !$config ) {
2342  $config = $mainContext->getConfig();
2343  }
2344  if ( !$user ) {
2345  $user = $mainContext->getUser();
2346  }
2347  if ( !$relevantTitle ) {
2348  $relevantTitle = $mainContext->getSkin()->getRelevantTitle();
2349  }
2350  }
2351 
2352  $isWatchlistExpiryEnabled = $config->get( MainConfigNames::WatchlistExpiry );
2353  if ( !$isWatchlistExpiryEnabled || !$relevantTitle || !$relevantTitle->canExist() ) {
2354  return;
2355  }
2356 
2357  $watchStore = MediaWikiServices::getInstance()->getWatchedItemStore();
2358  $watchedItem = $watchStore->getWatchedItem( $user, $relevantTitle );
2359  if ( $watchedItem instanceof WatchedItem && $watchedItem->getExpiry() !== null ) {
2360  $diffInDays = $watchedItem->getExpiryInDays();
2361 
2362  if ( $diffInDays ) {
2363  $msgParams = [ $diffInDays ];
2364  // Resolves to tooltip-ca-unwatch-expiring message
2365  $tooltip = 'ca-unwatch-expiring';
2366  } else { // Resolves to tooltip-ca-unwatch-expiring-hours message
2367  $tooltip = 'ca-unwatch-expiring-hours';
2368  }
2369  }
2370  }
2371 
2388  public static function tooltipAndAccesskeyAttribs(
2389  $name,
2390  array $msgParams = [],
2391  $options = null,
2392  $localizer = null,
2393  $user = null,
2394  $config = null,
2395  $relevantTitle = null
2396  ) {
2397  $options = (array)$options;
2398  $options[] = 'withaccess';
2399  $tooltipTitle = $name;
2400 
2401  // Get optional parameters from global context if any missing.
2402  if ( !$localizer ) {
2403  $localizer = self::getContextFromMain();
2404  }
2405 
2406  // @since 1.35 - add a WatchlistExpiry feature flag to show new watchstar tooltip message
2407  if ( $name === 'ca-unwatch' ) {
2408  self::updateWatchstarTooltipMessage( $tooltipTitle, $msgParams, $config, $user, $relevantTitle );
2409  }
2410 
2411  $attribs = [
2412  'title' => self::titleAttrib( $tooltipTitle, $options, $msgParams, $localizer ),
2413  'accesskey' => self::accesskey( $name, $localizer )
2414  ];
2415  if ( $attribs['title'] === false ) {
2416  unset( $attribs['title'] );
2417  }
2418  if ( $attribs['accesskey'] === false ) {
2419  unset( $attribs['accesskey'] );
2420  }
2421  return $attribs;
2422  }
2423 
2431  public static function tooltip( $name, $options = null ) {
2432  $tooltip = self::titleAttrib( $name, $options );
2433  if ( $tooltip === false ) {
2434  return '';
2435  }
2436  return Xml::expandAttributes( [
2437  'title' => $tooltip
2438  ] );
2439  }
2440 
2441 }
2442 
2443 class_alias( Linker::class, 'Linker' );
const NS_USER
Definition: Defines.php:66
const NS_FILE
Definition: Defines.php:70
const NS_MAIN
Definition: Defines.php:64
const PROTO_RELATIVE
Definition: Defines.php:195
const NS_USER_TALK
Definition: Defines.php:67
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL using $wgServer (or one of its alternatives).
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
$fallback
Definition: MessagesAb.php:8
$success
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgLang
Definition: Setup.php:528
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgTitle
Definition: Setup.php:528
if(!defined('MW_SETUP_CALLBACK'))
Definition: WebStart.php:88
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
An IContextSource implementation which will inherit context from another source but allow individual ...
Class to parse and build external user names.
static getUserLinkTitle( $userName)
Get a target Title to link a username.
static isExternal( $username)
Tells whether the username is external or not.
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:68
Marks HTML that shouldn't be escaped.
Definition: HtmlArmor.php:30
Base class for language-specific code.
Definition: Language.php:57
Basic media transform error class.
Base class for the output of MediaHandler::doTransform() and File::transform().
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:565
Static utilities for manipulating HTML strings.
Definition: HtmlHelper.php:17
static modifyElements(string $htmlFragment, callable $shouldModifyCallback, callable $modifyCallback)
Modify elements of an HTML fragment via a user-provided callback.
Definition: HtmlHelper.php:30
This class is a collection of static functions that serve two purposes:
Definition: Html.php:55
static label( $label, $id, array $attribs=[])
Convenience function for generating a label for inputs.
Definition: Html.php:843
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:264
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:219
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:240
Some internal bits split of from Skin.php.
Definition: Linker.php:67
static expandLocalLinks(string $html)
Helper function to expand local links.
Definition: Linker.php:1484
static revComment(RevisionRecord $revRecord, $local=false, $isPublic=false, $useParentheses=true)
Wrap and format the given revision's comment block, if the current user is allowed to view it.
Definition: Linker.php:1676
static revDeleteLink( $query=[], $restricted=false, $delete=true)
Creates a (show/hide) link for deleting revisions/log entries.
Definition: Linker.php:2294
static link( $target, $html=null, $customAttribs=[], $query=[], $options=[])
This function returns an HTML link to the given target.
Definition: Linker.php:116
static tocLineEnd()
End a Table Of Contents line.
Definition: Linker.php:1761
static blockLink( $userId, $userText)
Definition: Linker.php:1341
static makeSelfLinkObj( $nt, $html='', $query='', $trail='', $prefix='', $hash='')
Make appropriate markup for a link to the current article.
Definition: Linker.php:192
static getUploadUrl( $destFile, $query='')
Get the URL to upload a certain file.
Definition: Linker.php:972
static makeImageLink(Parser $parser, LinkTarget $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:326
static makeMediaLinkObj( $title, $html='', $time=false)
Create a direct link to a given uploaded file.
Definition: Linker.php:1003
static processResponsiveImages( $file, $thumb, $hp)
Process responsive images: add 1.5x and 2x subimages to the thumbnail, where applicable.
Definition: Linker.php:862
static userTalkLink( $userId, $userText)
Definition: Linker.php:1319
static commentBlock( $comment, $title=null, $local=false, $wikiId=null, $useParentheses=true)
Wrap a comment in standard punctuation and formatting if it's non-empty, otherwise return empty strin...
Definition: Linker.php:1654
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:1518
static normalizeSubpageLink( $contextTitle, $target, &$text)
Definition: Linker.php:1557
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:1064
static userToolLinks( $userId, $userText, $redContribsWhenNoEdits=false, $flags=0, $edits=null, $useParentheses=true)
Generate standard user tool links (talk, contributions, block link, etc.)
Definition: Linker.php:1223
static emailLink( $userId, $userText)
Definition: Linker.php:1362
static formatHiddenCategories( $hiddencats)
Returns HTML for the "hidden categories on this page" list.
Definition: Linker.php:2124
static getInvalidTitleDescription(IContextSource $context, $namespace, $title)
Get a message saying that an invalid title was encountered.
Definition: Linker.php:225
static getRollbackEditCount(RevisionRecord $revRecord, $verify=true)
This function will return the number of revisions which a rollback would revert and will verify that ...
Definition: Linker.php:1982
static makeExternalLink( $url, $text, $escape=true, $linktype='', $attribs=[], $title=null)
Make an external link.
Definition: Linker.php:1111
static getImageLinkMTOParams( $frameParams, $query='', $parser=null)
Get the link parameters for MediaTransformOutput::toHtml() from given frame parameters supplied by th...
Definition: Linker.php:577
static generateTOC(?TOCData $tocData, Language $lang=null, array $options=[])
Definition: Linker.php:1813
static linkKnown( $target, $html=null, $customAttribs=[], $query=[], $options=[ 'known'])
Identical to link(), except $options defaults to 'known'.
Definition: Linker.php:168
static getRevDeleteLink(Authority $performer, RevisionRecord $revRecord, LinkTarget $title)
Get a revision-deletion link, or disabled link, or nothing, depending on user permissions & the setti...
Definition: Linker.php:2242
static makeThumbLink2(LinkTarget $title, $file, $frameParams=[], $handlerParams=[], $time=false, $query='', array $classes=[], ?Parser $parser=null)
Definition: Linker.php:653
static tocList( $toc, Language $lang=null)
Wraps the TOC in a div with ARIA navigation role and provides the hide/collapse JavaScript.
Definition: Linker.php:1773
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
Definition: Linker.php:1867
static makeExternalImage( $url, $alt='')
Return the code for images which were added via external links, via Parser::maybeMakeExternalImage().
Definition: Linker.php:268
static tooltip( $name, $options=null)
Returns raw bits of HTML, use titleAttrib()
Definition: Linker.php:2431
static makeBrokenImageLinkObj( $title, $label='', $query='', $unused1='', $unused2='', $time=false, array $handlerParams=[], bool $currentExists=false)
Make a "broken" link to an image.
Definition: Linker.php:899
static makeMediaLinkFile(LinkTarget $title, $file, $html='')
Create a direct link to a given uploaded file.
Definition: Linker.php:1022
static accesskey( $name, $localizer=null)
Given the id of an interface element, constructs the appropriate accesskey attribute from the system ...
Definition: Linker.php:2217
static titleAttrib( $name, $options=null, array $msgParams=[], $localizer=null)
Given the id of an interface element, constructs the appropriate title attribute from the system mess...
Definition: Linker.php:2169
static userToolLinksRedContribs( $userId, $userText, $edits=null, $useParentheses=true)
Alias for userToolLinks( $userId, $userText, true );.
Definition: Linker.php:1307
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:1888
static tocIndent()
Add another level to the Table of Contents.
Definition: Linker.php:1707
const TOOL_LINKS_NOBLOCK
Flags for userToolLinks()
Definition: Linker.php:71
static revDeleteLinkDisabled( $delete=true)
Creates a dead (show/hide) link for deleting revisions/log entries.
Definition: Linker.php:2318
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[], $options=null, $localizer=null, $user=null, $config=null, $relevantTitle=null)
Returns the attributes for the tooltip and access key.
Definition: Linker.php:2388
static formatRevisionSize( $size)
Definition: Linker.php:1692
static tocUnindent( $level)
Finish one or more sublevels on the Table of Contents.
Definition: Linker.php:1718
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:1544
static makeThumbLinkObj(LinkTarget $title, $file, $label='', $alt='', $align=null, $params=[], $framed=false, $manualthumb='')
Make HTML for a thumbnail including image, border and caption.
Definition: Linker.php:620
static userLink( $userId, $userName, $altUserName=false, $attributes=[])
Make user link (or user contributions for unregistered users)
Definition: Linker.php:1165
static revUserLink(RevisionRecord $revRecord, $isPublic=false)
Generate a user link if the current user is allowed to view it.
Definition: Linker.php:1388
static getRevisionDeletedClass(RevisionRecord $revisionRecord)
Returns css class of a deleted revision.
Definition: Linker.php:1416
static generateRollback(RevisionRecord $revRecord, IContextSource $context=null, $options=[])
Generate a rollback link for a given revision.
Definition: Linker.php:1927
static revUserTools(RevisionRecord $revRecord, $isPublic=false, $useParentheses=true)
Generate a user tool link cluster if the current user is allowed to view it.
Definition: Linker.php:1436
static tocLine( $linkAnchor, $tocline, $tocnumber, $level, $sectionIndex=false)
parameter level defines if we are on an indentation level
Definition: Linker.php:1733
static buildRollbackLink(RevisionRecord $revRecord, IContextSource $context=null, $editCount=false)
Build a raw rollback link, useful for collections of "tool" links.
Definition: Linker.php:2053
A class containing constants representing the names of configuration variables.
const UploadNavigationUrl
Name constant for the UploadNavigationUrl setting, for use with Config::get()
const MaxTocLevel
Name constant for the MaxTocLevel setting, for use with Config::get()
const ThumbUpright
Name constant for the ThumbUpright setting, for use with Config::get()
const EnableUploads
Name constant for the EnableUploads setting, for use with Config::get()
const SVGMaxSize
Name constant for the SVGMaxSize setting, for use with Config::get()
const ResponsiveImages
Name constant for the ResponsiveImages setting, for use with Config::get()
const DisableAnonTalk
Name constant for the DisableAnonTalk setting, for use with Config::get()
const ParserEnableLegacyMediaDOM
Name constant for the ParserEnableLegacyMediaDOM setting, for use with Config::get()
const ThumbLimits
Name constant for the ThumbLimits setting, for use with Config::get()
const UploadMissingFileUrl
Name constant for the UploadMissingFileUrl setting, for use with Config::get()
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
Page revision base class.
getUser( $audience=self::FOR_PUBLIC, Authority $performer=null)
Fetch revision's author's user identity, if it's available to the specified audience.
getVisibility()
Get the deletion bitfield of the revision.
getPageId( $wikiId=self::LOCAL)
Get the page ID.
getTimestamp()
MCR migration note: this replaced Revision::getTimestamp.
getPageAsLinkTarget()
Returns the title of the page this revision is associated with as a LinkTarget object.
userCan( $field, Authority $performer)
Determine if the give authority is allowed to view a particular field of this revision,...
isDeleted( $field)
MCR migration note: this replaced Revision::isDeleted.
getId( $wikiId=self::LOCAL)
Get revision ID.
Represents a title within MediaWiki.
Definition: Title.php:82
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:719
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:315
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition: Message.php:144
static numParam( $num)
Definition: Message.php:1146
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition: Parser.php:107
getTargetLanguage()
Get the target language for the content being parsed.
Definition: Parser.php:1163
static getExternalLinkRel( $url=false, LinkTarget $title=null)
Get the rel attribute for a particular external link.
Definition: Parser.php:2240
Group all the pieces relevant to the context of a request into one instance.
static getMain()
Get the RequestContext object associated with the main request.
Parent class for all special pages.
Definition: SpecialPage.php:45
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,...
static getTitleValueFor( $name, $subpage=false, $fragment='')
Get a localised TitleValue object for a specified special page name.
Represents a page (or page fragment) title within MediaWiki.
Definition: TitleValue.php:40
static tryNew( $namespace, $title, $fragment='', $interwiki='')
Constructs a TitleValue, or returns null if the parameters are not valid.
Definition: TitleValue.php:80
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:71
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:626
Representation of a pair of user and title for watchlist entries.
Definition: WatchedItem.php:36
getExpiry(?int $style=TS_MW)
When the watched item will expire.
Build SELECT queries with a fluent interface.
Module of static functions for generating XML.
Definition: Xml.php:31
static expandAttributes( $attribs)
Given an array of ('attributename' => 'value'), it generates the code to set the XML attributes : att...
Definition: Xml.php:70
static tags( $element, $attribs, $contents)
Same as Xml::element(), but does not escape contents.
Definition: Xml.php:135
Interface for configuration instances.
Definition: Config.php:30
Interface for objects which can provide a MediaWiki context on request.
This interface represents the authority associated the current execution context, such as a web reque...
Definition: Authority.php:37
isAllowed(string $permission)
Checks whether this authority has the given permission in general.
Interface for localizing messages in MediaWiki.
msg( $key,... $params)
This is the method for getting translated interface messages.
const DB_REPLICA
Definition: defines.php:26
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
if(!isset( $args[0])) $lang
$revQuery