MediaWiki  master
Linker.php
Go to the documentation of this file.
1 <?php
23 namespace MediaWiki\Linker;
24 
25 use Config;
26 use ContextSource;
28 use DOMXPath;
30 use File;
31 use Hooks;
32 use Html;
33 use HtmlArmor;
34 use HtmlFormatter\HtmlFormatter;
35 use IContextSource;
36 use Language;
42 use Message;
44 use Parser;
45 use RequestContext;
46 use SpecialPage;
47 use Title;
48 use TitleValue;
49 use User;
50 use WatchedItem;
51 use Wikimedia\IPUtils;
52 use Wikimedia\Parsoid\Core\SectionMetadata;
54 use Xml;
55 
65 class Linker {
69  public const TOOL_LINKS_NOBLOCK = 1;
70  public const TOOL_LINKS_EMAIL = 2;
71 
114  public static function link(
115  $target, $html = null, $customAttribs = [], $query = [], $options = []
116  ) {
117  if ( !$target instanceof LinkTarget ) {
118  wfWarn( __METHOD__ . ': Requires $target to be a LinkTarget object.', 2 );
119  return "<!-- ERROR -->$html";
120  }
121 
122  $services = MediaWikiServices::getInstance();
123  $options = (array)$options;
124  if ( $options ) {
125  // Custom options, create new LinkRenderer
126  $linkRenderer = $services->getLinkRendererFactory()
127  ->createFromLegacyOptions( $options );
128  } else {
129  $linkRenderer = $services->getLinkRenderer();
130  }
131 
132  if ( $html !== null ) {
133  $text = new HtmlArmor( $html );
134  } else {
135  $text = null;
136  }
137 
138  if ( in_array( 'known', $options, true ) ) {
139  return $linkRenderer->makeKnownLink( $target, $text, $customAttribs, $query );
140  }
141 
142  if ( in_array( 'broken', $options, true ) ) {
143  return $linkRenderer->makeBrokenLink( $target, $text, $customAttribs, $query );
144  }
145 
146  if ( in_array( 'noclasses', $options, true ) ) {
147  return $linkRenderer->makePreloadedLink( $target, $text, '', $customAttribs, $query );
148  }
149 
150  return $linkRenderer->makeLink( $target, $text, $customAttribs, $query );
151  }
152 
166  public static function linkKnown(
167  $target, $html = null, $customAttribs = [],
168  $query = [], $options = [ 'known' ]
169  ) {
170  return self::link( $target, $html, $customAttribs, $query, $options );
171  }
172 
190  public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '', $hash = '' ) {
191  $nt = Title::newFromLinkTarget( $nt );
192  $attrs = [
193  'class' => 'mw-selflink',
194  ];
195  if ( $hash ) {
196  $attrs['href'] = '#' . $hash;
197  $attrs['class'] = 'mw-selflink-fragment';
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  if ( !Hooks::runner()->onSelfLinkBegin( $nt, $html, $trail, $prefix, $ret ) ) {
204  return $ret;
205  }
206 
207  if ( $html == '' ) {
208  $html = htmlspecialchars( $nt->getPrefixedText() );
209  }
210  [ $inside, $trail ] = self::splitTrail( $trail );
211  return Html::rawElement( 'a', $attrs, $prefix . $html . $inside ) . $trail;
212  }
213 
224  public static function getInvalidTitleDescription( IContextSource $context, $namespace, $title ) {
225  // First we check whether the namespace exists or not.
226  if ( MediaWikiServices::getInstance()->getNamespaceInfo()->exists( $namespace ) ) {
227  if ( $namespace == NS_MAIN ) {
228  $name = $context->msg( 'blanknamespace' )->text();
229  } else {
230  $name = MediaWikiServices::getInstance()->getContentLanguage()->
231  getFormattedNsText( $namespace );
232  }
233  return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
234  }
235 
236  return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
237  }
238 
247  private static function fnamePart( $url ) {
248  $basename = strrchr( $url, '/' );
249  if ( $basename === false ) {
250  $basename = $url;
251  } else {
252  $basename = substr( $basename, 1 );
253  }
254  return $basename;
255  }
256 
267  public static function makeExternalImage( $url, $alt = '' ) {
268  if ( $alt == '' ) {
269  $alt = self::fnamePart( $url );
270  }
271  $img = '';
272  $success = Hooks::runner()->onLinkerMakeExternalImage( $url, $alt, $img );
273  if ( !$success ) {
274  wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
275  . "with url {$url} and alt text {$alt} to {$img}" );
276  return $img;
277  }
278  return Html::element( 'img',
279  [
280  'src' => $url,
281  'alt' => $alt
282  ]
283  );
284  }
285 
324  public static function makeImageLink( Parser $parser, LinkTarget $title,
325  $file, $frameParams = [], $handlerParams = [], $time = false,
326  $query = '', $widthOption = null
327  ) {
329  $res = null;
330  $dummy = new DummyLinker;
331  if ( !Hooks::runner()->onImageBeforeProduceHTML( $dummy, $title,
332  // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
333  $file, $frameParams, $handlerParams, $time, $res,
334  // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
335  $parser, $query, $widthOption )
336  ) {
337  return $res;
338  }
339 
340  if ( $file && !$file->allowInlineDisplay() ) {
341  wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . ' does not allow inline display' );
342  return self::link( $title );
343  }
344 
345  // Clean up parameters
346  $page = $handlerParams['page'] ?? false;
347  if ( !isset( $frameParams['align'] ) ) {
348  $frameParams['align'] = '';
349  }
350  if ( !isset( $frameParams['alt'] ) ) {
351  $frameParams['alt'] = '';
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 ( $file && isset( $frameParams['frameless'] ) ) {
456  $rdfaType .= '/Frameless';
457  $srcWidth = $file->getWidth( $page );
458  # For "frameless" option: do not present an image bigger than the
459  # source (for bitmap-style images). This is the same behavior as the
460  # "thumb" option does it already.
461  if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
462  $handlerParams['width'] = $srcWidth;
463  }
464  }
465 
466  if ( $file && isset( $handlerParams['width'] ) ) {
467  # Create a resized image, without the additional thumbnail features
468  $thumb = $file->transform( $handlerParams );
469  } else {
470  $thumb = false;
471  }
472 
473  if ( !$thumb ) {
474  $rdfaType = 'mw:Error ' . $rdfaType;
475  $label = '';
476  if ( $enableLegacyMediaDOM ) {
477  // This is the information for tooltips for inline images which
478  // Parsoid stores in data-mw. See T273014
479  $label = $frameParams['title'];
480  }
482  $title, $label, '', '', '', (bool)$time, $handlerParams
483  );
484  } else {
485  self::processResponsiveImages( $file, $thumb, $handlerParams );
486  $params = [
487  'alt' => $frameParams['alt'],
488  'title' => $frameParams['title'],
489  ];
490  if ( $enableLegacyMediaDOM ) {
491  $params += [
492  'valign' => $frameParams['valign'] ?? false,
493  'img-class' => $frameParams['class'],
494  ];
495  if ( isset( $frameParams['border'] ) ) {
496  $params['img-class'] .= ( $params['img-class'] !== '' ? ' ' : '' ) . 'thumbborder';
497  }
498  }
499  $params = self::getImageLinkMTOParams( $frameParams, $query, $parser ) + $params;
500  $s = $thumb->toHtml( $params );
501  }
502 
503  if ( $enableLegacyMediaDOM ) {
504  if ( $frameParams['align'] != '' ) {
506  'div',
507  [ 'class' => 'float' . $frameParams['align'] ],
508  $s
509  );
510  }
511  return str_replace( "\n", ' ', $prefix . $s . $postfix );
512  }
513 
514  $wrapper = 'span';
515  $caption = '';
516 
517  if ( $frameParams['align'] != '' ) {
518  $wrapper = 'figure';
519  // Possible values: mw-halign-left mw-halign-center mw-halign-right mw-halign-none
520  $classes[] = "mw-halign-{$frameParams['align']}";
521  $caption = Html::rawElement(
522  'figcaption', [], $frameParams['caption'] ?? ''
523  );
524  } elseif ( isset( $frameParams['valign'] ) ) {
525  // Possible values: mw-valign-middle mw-valign-baseline mw-valign-sub
526  // mw-valign-super mw-valign-top mw-valign-text-top mw-valign-bottom
527  // mw-valign-text-bottom
528  $classes[] = "mw-valign-{$frameParams['valign']}";
529  }
530 
531  if ( isset( $frameParams['border'] ) ) {
532  $classes[] = 'mw-image-border';
533  }
534 
535  if ( isset( $frameParams['class'] ) ) {
536  $classes[] = $frameParams['class'];
537  }
538 
539  $attribs = [
540  'class' => $classes,
541  'typeof' => $rdfaType,
542  ];
543 
544  $s = Html::rawElement( $wrapper, $attribs, $s . $caption );
545 
546  return str_replace( "\n", ' ', $s );
547  }
548 
557  public static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
558  $mtoParams = [];
559  if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
560  $mtoParams['custom-url-link'] = $frameParams['link-url'];
561  if ( isset( $frameParams['link-target'] ) ) {
562  $mtoParams['custom-target-link'] = $frameParams['link-target'];
563  }
564  if ( $parser ) {
565  $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
566  foreach ( $extLinkAttrs as $name => $val ) {
567  // Currently could include 'rel' and 'target'
568  $mtoParams['parser-extlink-' . $name] = $val;
569  }
570  }
571  } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
572  $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
573  $mtoParams['custom-title-link'] = Title::newFromLinkTarget(
574  $linkRenderer->normalizeTarget( $frameParams['link-title'] )
575  );
576  if ( isset( $frameParams['link-title-query'] ) ) {
577  $mtoParams['custom-title-link-query'] = $frameParams['link-title-query'];
578  }
579  } elseif ( !empty( $frameParams['no-link'] ) ) {
580  // No link
581  } else {
582  $mtoParams['desc-link'] = true;
583  $mtoParams['desc-query'] = $query;
584  }
585  return $mtoParams;
586  }
587 
600  public static function makeThumbLinkObj(
601  LinkTarget $title, $file, $label = '', $alt = '', $align = null,
602  $params = [], $framed = false, $manualthumb = ''
603  ) {
604  $frameParams = [
605  'alt' => $alt,
606  'caption' => $label,
607  'align' => $align
608  ];
609  $classes = [];
610  if ( $manualthumb ) {
611  $frameParams['manualthumb'] = $manualthumb;
612  } elseif ( $framed ) {
613  $frameParams['framed'] = true;
614  } elseif ( !isset( $params['width'] ) ) {
615  $classes[] = 'mw-default-size';
616  }
617  return self::makeThumbLink2(
618  $title, $file, $frameParams, $params, false, '', $classes
619  );
620  }
621 
633  public static function makeThumbLink2(
634  LinkTarget $title, $file, $frameParams = [], $handlerParams = [],
635  $time = false, $query = '', array $classes = [], ?Parser $parser = null
636  ) {
637  $exists = $file && $file->exists();
638 
639  $services = MediaWikiServices::getInstance();
640  $enableLegacyMediaDOM = $services->getMainConfig()->get( MainConfigNames::ParserEnableLegacyMediaDOM );
641 
642  $page = $handlerParams['page'] ?? false;
643  if ( !isset( $frameParams['align'] ) ) {
644  $frameParams['align'] = '';
645  if ( $enableLegacyMediaDOM ) {
646  $frameParams['align'] = 'right';
647  }
648  }
649  if ( !isset( $frameParams['alt'] ) ) {
650  $frameParams['alt'] = '';
651  }
652  if ( !isset( $frameParams['caption'] ) ) {
653  $frameParams['caption'] = '';
654  }
655 
656  if ( empty( $handlerParams['width'] ) ) {
657  // Reduce width for upright images when parameter 'upright' is used
658  $handlerParams['width'] = isset( $frameParams['upright'] ) ? 130 : 180;
659  }
660 
661  $thumb = false;
662  $noscale = false;
663  $manualthumb = false;
664  $rdfaType = 'mw:File/Thumb';
665 
666  if ( !$exists ) {
667  $outerWidth = $handlerParams['width'] + 2;
668  } else {
669  if ( isset( $frameParams['manualthumb'] ) ) {
670  # Use manually specified thumbnail
671  $manual_title = Title::makeTitleSafe( NS_FILE, $frameParams['manualthumb'] );
672  if ( $manual_title ) {
673  $manual_img = $services->getRepoGroup()
674  ->findFile( $manual_title );
675  if ( $manual_img ) {
676  $thumb = $manual_img->getUnscaledThumb( $handlerParams );
677  $manualthumb = true;
678  } else {
679  $exists = false;
680  }
681  }
682  } elseif ( isset( $frameParams['framed'] ) ) {
683  // Use image dimensions, don't scale
684  $thumb = $file->getUnscaledThumb( $handlerParams );
685  $noscale = true;
686  $rdfaType = 'mw:File/Frame';
687  } else {
688  # Do not present an image bigger than the source, for bitmap-style images
689  # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
690  $srcWidth = $file->getWidth( $page );
691  if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
692  $handlerParams['width'] = $srcWidth;
693  }
694  $thumb = $file->transform( $handlerParams );
695  }
696 
697  if ( $thumb ) {
698  $outerWidth = $thumb->getWidth() + 2;
699  } else {
700  $outerWidth = $handlerParams['width'] + 2;
701  }
702  }
703 
704  $url = Title::newFromLinkTarget( $title )->getLocalURL( $query );
705  $linkTitleQuery = [];
706 
707  if ( $page ) {
708  $linkTitleQuery['page'] = $page;
709  # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
710  # So we don't need to pass it here in $query. However, the URL for the
711  # zoom icon still needs it, so we make a unique query for it. See T16771
712  # FIXME: What about "lang" and other querystring parameters
713  $url = wfAppendQuery( $url, $linkTitleQuery );
714  }
715 
716  if ( $manualthumb
717  && !isset( $frameParams['link-title'] )
718  && !isset( $frameParams['link-url'] )
719  && !isset( $frameParams['no-link'] ) ) {
720  $frameParams['link-title'] = $title;
721  $frameParams['link-title-query'] = $linkTitleQuery;
722  }
723 
724  if ( $frameParams['align'] != '' ) {
725  // Possible values: mw-halign-left mw-halign-center mw-halign-right mw-halign-none
726  $classes[] = "mw-halign-{$frameParams['align']}";
727  }
728 
729  if ( isset( $frameParams['class'] ) ) {
730  $classes[] = $frameParams['class'];
731  }
732 
733  $s = '';
734 
735  if ( $enableLegacyMediaDOM ) {
736  $s .= "<div class=\"thumb t{$frameParams['align']}\">"
737  . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
738  }
739 
740  if ( !$exists ) {
741  $label = '';
743  $title, $label, '', '', '', (bool)$time, $handlerParams
744  );
745  $zoomIcon = '';
746  } elseif ( !$thumb ) {
747  if ( $enableLegacyMediaDOM ) {
748  $s .= wfMessage( 'thumbnail_error', '' )->escaped();
749  } else {
751  $title, '', '', '', '', (bool)$time, $handlerParams
752  );
753  }
754  $zoomIcon = '';
755  } else {
756  if ( !$noscale && !$manualthumb ) {
757  self::processResponsiveImages( $file, $thumb, $handlerParams );
758  }
759  $params = [
760  'alt' => $frameParams['alt'],
761  ];
762  if ( $enableLegacyMediaDOM ) {
763  $params += [
764  'img-class' => ( isset( $frameParams['class'] ) && $frameParams['class'] !== ''
765  ? $frameParams['class'] . ' '
766  : '' ) . 'thumbimage'
767  ];
768  }
769  $params = self::getImageLinkMTOParams( $frameParams, $query, $parser ) + $params;
770  $s .= $thumb->toHtml( $params );
771  if ( isset( $frameParams['framed'] ) ) {
772  $zoomIcon = '';
773  } else {
774  $zoomIcon = Html::rawElement( 'div', [ 'class' => 'magnify' ],
775  Html::rawElement( 'a', [
776  'href' => $url,
777  'class' => 'internal',
778  'title' => wfMessage( 'thumbnail-more' )->text(),
779  ] )
780  );
781  }
782  }
783 
784  if ( $enableLegacyMediaDOM ) {
785  $s .= ' <div class="thumbcaption">' . $zoomIcon . $frameParams['caption'] . '</div></div></div>';
786  return str_replace( "\n", ' ', $s );
787  }
788 
789  $s .= Html::rawElement(
790  'figcaption', [], $frameParams['caption'] ?? ''
791  );
792 
793  if ( !$exists || !$thumb ) {
794  $rdfaType = 'mw:Error ' . $rdfaType;
795  }
796 
797  $attribs = [
798  'class' => $classes,
799  'typeof' => $rdfaType,
800  ];
801 
802  $s = Html::rawElement( 'figure', $attribs, $s );
803 
804  return str_replace( "\n", ' ', $s );
805  }
806 
815  public static function processResponsiveImages( $file, $thumb, $hp ) {
816  $responsiveImages = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::ResponsiveImages );
817  if ( $responsiveImages && $thumb && !$thumb->isError() ) {
818  $hp15 = $hp;
819  $hp15['width'] = round( $hp['width'] * 1.5 );
820  $hp20 = $hp;
821  $hp20['width'] = $hp['width'] * 2;
822  if ( isset( $hp['height'] ) ) {
823  $hp15['height'] = round( $hp['height'] * 1.5 );
824  $hp20['height'] = $hp['height'] * 2;
825  }
826 
827  $thumb15 = $file->transform( $hp15 );
828  $thumb20 = $file->transform( $hp20 );
829  if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
830  $thumb->responsiveUrls['1.5'] = $thumb15->getUrl();
831  }
832  if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
833  $thumb->responsiveUrls['2'] = $thumb20->getUrl();
834  }
835  }
836  }
837 
851  public static function makeBrokenImageLinkObj(
852  $title, $label = '', $query = '', $unused1 = '', $unused2 = '',
853  $time = false, array $handlerParams = []
854  ) {
855  if ( !$title instanceof LinkTarget ) {
856  wfWarn( __METHOD__ . ': Requires $title to be a LinkTarget object.' );
857  return "<!-- ERROR -->" . htmlspecialchars( $label );
858  }
859 
861  $services = MediaWikiServices::getInstance();
862  $mainConfig = $services->getMainConfig();
863  $enableUploads = $mainConfig->get( MainConfigNames::EnableUploads );
864  $uploadMissingFileUrl = $mainConfig->get( MainConfigNames::UploadMissingFileUrl );
865  $uploadNavigationUrl = $mainConfig->get( MainConfigNames::UploadNavigationUrl );
866  if ( $label == '' ) {
867  $label = $title->getPrefixedText();
868  }
869 
870  $html = Html::element( 'span', [
871  'class' => 'mw-broken-media',
872  // These data attributes are used to dynamically size the span, see T273013
873  'data-width' => $handlerParams['width'] ?? null,
874  'data-height' => $handlerParams['height'] ?? null,
875  ], $label );
876 
877  if ( $mainConfig->get( MainConfigNames::ParserEnableLegacyMediaDOM ) ) {
878  $html = htmlspecialchars( $label, ENT_COMPAT );
879  }
880 
881  $repoGroup = $services->getRepoGroup();
882  $currentExists = $time
883  && $repoGroup->findFile( $title ) !== false;
884 
885  if ( ( $uploadMissingFileUrl || $uploadNavigationUrl || $enableUploads )
886  && !$currentExists
887  ) {
888  if (
889  $title->inNamespace( NS_FILE ) &&
890  $repoGroup->getLocalRepo()->checkRedirect( $title )
891  ) {
892  // We already know it's a redirect, so mark it accordingly
893  return self::link(
894  $title,
895  $html,
896  [ 'class' => 'mw-redirect' ],
897  wfCgiToArray( $query ),
898  [ 'known', 'noclasses' ]
899  );
900  }
901  return Html::rawElement( 'a', [
902  'href' => self::getUploadUrl( $title, $query ),
903  'class' => 'new',
904  'title' => $title->getPrefixedText()
905  ], $html );
906  }
907  return self::link(
908  $title,
909  $html,
910  [],
911  wfCgiToArray( $query ),
912  [ 'known', 'noclasses' ]
913  );
914  }
915 
924  protected static function getUploadUrl( $destFile, $query = '' ) {
925  $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
926  $uploadMissingFileUrl = $mainConfig->get( MainConfigNames::UploadMissingFileUrl );
927  $uploadNavigationUrl = $mainConfig->get( MainConfigNames::UploadNavigationUrl );
928  $q = 'wpDestFile=' . Title::castFromLinkTarget( $destFile )->getPartialURL();
929  if ( $query != '' ) {
930  $q .= '&' . $query;
931  }
932 
933  if ( $uploadMissingFileUrl ) {
934  return wfAppendQuery( $uploadMissingFileUrl, $q );
935  }
936 
937  if ( $uploadNavigationUrl ) {
938  return wfAppendQuery( $uploadNavigationUrl, $q );
939  }
940 
941  $upload = SpecialPage::getTitleFor( 'Upload' );
942 
943  return $upload->getLocalURL( $q );
944  }
945 
955  public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
956  $img = MediaWikiServices::getInstance()->getRepoGroup()->findFile(
957  $title, [ 'time' => $time ]
958  );
959  return self::makeMediaLinkFile( $title, $img, $html );
960  }
961 
974  public static function makeMediaLinkFile( LinkTarget $title, $file, $html = '' ) {
975  if ( $file && $file->exists() ) {
976  $url = $file->getUrl();
977  $class = 'internal';
978  } else {
979  $url = self::getUploadUrl( $title );
980  $class = 'new';
981  }
982 
983  $alt = $title->getText();
984  if ( $html == '' ) {
985  $html = $alt;
986  }
987 
988  $ret = '';
989  $attribs = [
990  'href' => $url,
991  'class' => $class,
992  'title' => $alt
993  ];
994 
995  if ( !Hooks::runner()->onLinkerMakeMediaLinkFile(
996  Title::castFromLinkTarget( $title ), $file, $html, $attribs, $ret )
997  ) {
998  wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
999  . "with url {$url} and text {$html} to {$ret}" );
1000  return $ret;
1001  }
1002 
1003  return Html::rawElement( 'a', $attribs, $html );
1004  }
1005 
1016  public static function specialLink( $name, $key = '' ) {
1017  $queryPos = strpos( $name, '?' );
1018  if ( $queryPos !== false ) {
1019  $getParams = wfCgiToArray( substr( $name, $queryPos + 1 ) );
1020  $name = substr( $name, 0, $queryPos );
1021  } else {
1022  $getParams = [];
1023  }
1024 
1025  $slashPos = strpos( $name, '/' );
1026  if ( $slashPos !== false ) {
1027  $subpage = substr( $name, $slashPos + 1 );
1028  $name = substr( $name, 0, $slashPos );
1029  } else {
1030  $subpage = false;
1031  }
1032 
1033  if ( $key == '' ) {
1034  $key = strtolower( $name );
1035  }
1036 
1037  return self::linkKnown(
1038  SpecialPage::getTitleFor( $name, $subpage ),
1039  wfMessage( $key )->escaped(),
1040  [],
1041  $getParams
1042  );
1043  }
1044 
1063  public static function makeExternalLink( $url, $text, $escape = true,
1064  $linktype = '', $attribs = [], $title = null
1065  ) {
1066  global $wgTitle;
1067  $class = 'external';
1068  if ( $linktype ) {
1069  $class .= " $linktype";
1070  }
1071  if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1072  $class .= " {$attribs['class']}";
1073  }
1074  $attribs['class'] = $class;
1075 
1076  if ( $escape ) {
1077  $text = htmlspecialchars( $text, ENT_COMPAT );
1078  }
1079 
1080  if ( !$title ) {
1081  $title = $wgTitle;
1082  }
1083  $newRel = Parser::getExternalLinkRel( $url, $title );
1084  if ( !isset( $attribs['rel'] ) || $attribs['rel'] === '' ) {
1085  $attribs['rel'] = $newRel;
1086  } elseif ( $newRel !== null ) {
1087  // Merge the rel attributes.
1088  $newRels = explode( ' ', $newRel );
1089  $oldRels = explode( ' ', $attribs['rel'] );
1090  $combined = array_unique( array_merge( $newRels, $oldRels ) );
1091  $attribs['rel'] = implode( ' ', $combined );
1092  }
1093  $link = '';
1094  $success = Hooks::runner()->onLinkerMakeExternalLink(
1095  $url, $text, $link, $attribs, $linktype );
1096  if ( !$success ) {
1097  wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
1098  . "with url {$url} and text {$text} to {$link}" );
1099  return $link;
1100  }
1101  $attribs['href'] = $url;
1102  return Html::rawElement( 'a', $attribs, $text );
1103  }
1104 
1117  public static function userLink(
1118  $userId,
1119  $userName,
1120  $altUserName = false,
1121  $attributes = []
1122  ) {
1123  if ( $userName === '' || $userName === false || $userName === null ) {
1124  wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1125  'that need to be fixed?' );
1126  return wfMessage( 'empty-username' )->parse();
1127  }
1128 
1129  $classes = 'mw-userlink';
1130  if ( $userId == 0 ) {
1131  $page = ExternalUserNames::getUserLinkTitle( $userName );
1132 
1133  if ( ExternalUserNames::isExternal( $userName ) ) {
1134  $classes .= ' mw-extuserlink';
1135  } elseif ( $altUserName === false ) {
1136  $altUserName = IPUtils::prettifyIP( $userName );
1137  }
1138  $classes .= ' mw-anonuserlink'; // Separate link class for anons (T45179)
1139  } else {
1140  $page = TitleValue::tryNew( NS_USER, strtr( $userName, ' ', '_' ) );
1141  if (
1142  MediaWikiServices::getInstance()->getTempUserConfig()->isReservedName( $userName )
1143  ) {
1144  $classes .= ' mw-tempuserlink';
1145  }
1146  }
1147 
1148  // Wrap the output with <bdi> tags for directionality isolation
1149  $linkText =
1150  '<bdi>' . htmlspecialchars( $altUserName !== false ? $altUserName : $userName ) . '</bdi>';
1151 
1152  if ( isset( $attributes['class'] ) ) {
1153  $attributes['class'] .= ' ' . $classes;
1154  } else {
1155  $attributes['class'] = $classes;
1156  }
1157 
1158  return $page
1159  ? self::link( $page, $linkText, $attributes )
1160  : Html::rawElement( 'span', $attributes, $linkText );
1161  }
1162 
1177  public static function userToolLinks(
1178  $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null,
1179  $useParentheses = true
1180  ) {
1181  if ( $userText === '' ) {
1182  wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1183  'that need to be fixed?' );
1184  return ' ' . wfMessage( 'empty-username' )->parse();
1185  }
1186  global $wgLang;
1187  $disableAnonTalk = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::DisableAnonTalk );
1188  $talkable = !( $disableAnonTalk && $userId == 0 );
1189  $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1190  $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1191 
1192  if ( $userId == 0 && ExternalUserNames::isExternal( $userText ) ) {
1193  // No tools for an external user
1194  return '';
1195  }
1196 
1197  $items = [];
1198  if ( $talkable ) {
1199  $items[] = self::userTalkLink( $userId, $userText );
1200  }
1201  if ( $userId ) {
1202  // check if the user has an edit
1203  $attribs = [];
1204  $attribs['class'] = 'mw-usertoollinks-contribs';
1205  if ( $redContribsWhenNoEdits ) {
1206  if ( intval( $edits ) === 0 && $edits !== 0 ) {
1207  $user = User::newFromId( $userId );
1208  $edits = $user->getEditCount();
1209  }
1210  if ( $edits === 0 ) {
1211  // Note: "new" class is inappropriate here, as "new" class
1212  // should only be used for pages that do not exist.
1213  $attribs['class'] .= ' mw-usertoollinks-contribs-no-edits';
1214  }
1215  }
1216  $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1217 
1218  $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1219  }
1220  $userCanBlock = RequestContext::getMain()->getAuthority()->isAllowed( 'block' );
1221  if ( $blockable && $userCanBlock ) {
1222  $items[] = self::blockLink( $userId, $userText );
1223  }
1224 
1225  $user = RequestContext::getMain()->getUser();
1226  if ( $addEmailLink && $user->canSendEmail() ) {
1227  $items[] = self::emailLink( $userId, $userText );
1228  }
1229 
1230  Hooks::runner()->onUserToolLinksEdit( $userId, $userText, $items );
1231 
1232  if ( !$items ) {
1233  return '';
1234  }
1235 
1236  if ( $useParentheses ) {
1237  return wfMessage( 'word-separator' )->escaped()
1238  . '<span class="mw-usertoollinks">'
1239  . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1240  . '</span>';
1241  }
1242 
1243  $tools = [];
1244  foreach ( $items as $tool ) {
1245  $tools[] = Html::rawElement( 'span', [], $tool );
1246  }
1247  return ' <span class="mw-usertoollinks mw-changeslist-links">' .
1248  implode( ' ', $tools ) . '</span>';
1249  }
1250 
1260  public static function userToolLinksRedContribs(
1261  $userId, $userText, $edits = null, $useParentheses = true
1262  ) {
1263  return self::userToolLinks( $userId, $userText, true, 0, $edits, $useParentheses );
1264  }
1265 
1272  public static function userTalkLink( $userId, $userText ) {
1273  if ( $userText === '' ) {
1274  wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1275  'that need to be fixed?' );
1276  return wfMessage( 'empty-username' )->parse();
1277  }
1278 
1279  $userTalkPage = TitleValue::tryNew( NS_USER_TALK, strtr( $userText, ' ', '_' ) );
1280  $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-talk' ];
1281  $linkText = wfMessage( 'talkpagelinktext' )->escaped();
1282 
1283  return $userTalkPage
1284  ? self::link( $userTalkPage, $linkText, $moreLinkAttribs )
1285  : Html::rawElement( 'span', $moreLinkAttribs, $linkText );
1286  }
1287 
1294  public static function blockLink( $userId, $userText ) {
1295  if ( $userText === '' ) {
1296  wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1297  'that need to be fixed?' );
1298  return wfMessage( 'empty-username' )->parse();
1299  }
1300 
1301  $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1302  $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-block' ];
1303 
1304  return self::link( $blockPage,
1305  wfMessage( 'blocklink' )->escaped(),
1306  $moreLinkAttribs
1307  );
1308  }
1309 
1315  public static function emailLink( $userId, $userText ) {
1316  if ( $userText === '' ) {
1317  wfLogWarning( __METHOD__ . ' received an empty username. Are there database errors ' .
1318  'that need to be fixed?' );
1319  return wfMessage( 'empty-username' )->parse();
1320  }
1321 
1322  $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1323  $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-mail' ];
1324  return self::link( $emailPage,
1325  wfMessage( 'emaillink' )->escaped(),
1326  $moreLinkAttribs
1327  );
1328  }
1329 
1341  public static function revUserLink( RevisionRecord $revRecord, $isPublic = false ) {
1342  // TODO inject authority
1343  $authority = RequestContext::getMain()->getAuthority();
1344 
1345  if ( $revRecord->isDeleted( RevisionRecord::DELETED_USER ) && $isPublic ) {
1346  $link = wfMessage( 'rev-deleted-user' )->escaped();
1347  } elseif ( $revRecord->userCan( RevisionRecord::DELETED_USER, $authority ) ) {
1348  $revUser = $revRecord->getUser( RevisionRecord::FOR_THIS_USER, $authority );
1349  $link = self::userLink(
1350  $revUser ? $revUser->getId() : 0,
1351  $revUser ? $revUser->getName() : ''
1352  );
1353  } else {
1354  $link = wfMessage( 'rev-deleted-user' )->escaped();
1355  }
1356  if ( $revRecord->isDeleted( RevisionRecord::DELETED_USER ) ) {
1357  $class = self::getRevisionDeletedClass( $revRecord );
1358  return '<span class="' . $class . '">' . $link . '</span>';
1359  }
1360  return $link;
1361  }
1362 
1369  public static function getRevisionDeletedClass( RevisionRecord $revisionRecord ): string {
1370  $class = 'history-deleted';
1371  if ( $revisionRecord->isDeleted( RevisionRecord::DELETED_RESTRICTED ) ) {
1372  $class .= ' mw-history-suppressed';
1373  }
1374  return $class;
1375  }
1376 
1389  public static function revUserTools(
1390  RevisionRecord $revRecord,
1391  $isPublic = false,
1392  $useParentheses = true
1393  ) {
1394  // TODO inject authority
1395  $authority = RequestContext::getMain()->getAuthority();
1396 
1397  if ( $revRecord->userCan( RevisionRecord::DELETED_USER, $authority ) &&
1398  ( !$revRecord->isDeleted( RevisionRecord::DELETED_USER ) || !$isPublic )
1399  ) {
1400  $revUser = $revRecord->getUser( RevisionRecord::FOR_THIS_USER, $authority );
1401  $userId = $revUser ? $revUser->getId() : 0;
1402  $userText = $revUser ? $revUser->getName() : '';
1403 
1404  if ( $userId || $userText !== '' ) {
1405  $link = self::userLink(
1406  $userId,
1407  $userText,
1408  false,
1409  [ 'data-mw-revid' => $revRecord->getId() ]
1410  ) . self::userToolLinks(
1411  $userId,
1412  $userText,
1413  false,
1414  0,
1415  null,
1416  $useParentheses
1417  );
1418  }
1419  }
1420 
1421  if ( !isset( $link ) ) {
1422  $link = wfMessage( 'rev-deleted-user' )->escaped();
1423  }
1424 
1425  if ( $revRecord->isDeleted( RevisionRecord::DELETED_USER ) ) {
1426  $class = self::getRevisionDeletedClass( $revRecord );
1427  return ' <span class="' . $class . ' mw-userlink">' . $link . '</span>';
1428  }
1429  return $link;
1430  }
1431 
1442  public static function expandLocalLinks( string $html ) {
1443  $formatter = new HtmlFormatter( $html );
1444  $doc = $formatter->getDoc();
1445  $xpath = new DOMXPath( $doc );
1446  $nodes = $xpath->query( '//a[@href]' );
1448  foreach ( $nodes as $node ) {
1449  $node->setAttribute(
1450  'href',
1451  wfExpandUrl( $node->getAttribute( 'href' ), PROTO_RELATIVE )
1452  );
1453  }
1454  return $formatter->getText( 'html' );
1455  }
1456 
1477  public static function formatComment(
1478  $comment, $title = null, $local = false, $wikiId = null
1479  ) {
1480  $formatter = MediaWikiServices::getInstance()->getCommentFormatter();
1481  return $formatter->format( $comment, $title, $local, $wikiId );
1482  }
1483 
1503  public static function formatLinksInComment(
1504  $comment, $title = null, $local = false, $wikiId = null
1505  ) {
1506  $formatter = MediaWikiServices::getInstance()->getCommentFormatter();
1507  return $formatter->formatLinksUnsafe( $comment, $title, $local, $wikiId );
1508  }
1509 
1516  public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1517  # Valid link forms:
1518  # Foobar -- normal
1519  # :Foobar -- override special treatment of prefix (images, language links)
1520  # /Foobar -- convert to CurrentPage/Foobar
1521  # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1522  # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1523  # ../Foobar -- convert to CurrentPage/Foobar,
1524  # (from CurrentPage/CurrentSubPage)
1525  # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1526  # (from CurrentPage/CurrentSubPage)
1527 
1528  $ret = $target; # default return value is no change
1529 
1530  # Some namespaces don't allow subpages,
1531  # so only perform processing if subpages are allowed
1532  if (
1533  $contextTitle && MediaWikiServices::getInstance()->getNamespaceInfo()->
1534  hasSubpages( $contextTitle->getNamespace() )
1535  ) {
1536  $hash = strpos( $target, '#' );
1537  if ( $hash !== false ) {
1538  $suffix = substr( $target, $hash );
1539  $target = substr( $target, 0, $hash );
1540  } else {
1541  $suffix = '';
1542  }
1543  # T9425
1544  $target = trim( $target );
1545  $contextPrefixedText = MediaWikiServices::getInstance()->getTitleFormatter()->
1546  getPrefixedText( $contextTitle );
1547  # Look at the first character
1548  if ( $target != '' && $target[0] === '/' ) {
1549  # / at end means we don't want the slash to be shown
1550  $m = [];
1551  $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1552  if ( $trailingSlashes ) {
1553  $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1554  } else {
1555  $noslash = substr( $target, 1 );
1556  }
1557 
1558  $ret = $contextPrefixedText . '/' . trim( $noslash ) . $suffix;
1559  if ( $text === '' ) {
1560  $text = $target . $suffix;
1561  } # this might be changed for ugliness reasons
1562  } else {
1563  # check for .. subpage backlinks
1564  $dotdotcount = 0;
1565  $nodotdot = $target;
1566  while ( str_starts_with( $nodotdot, '../' ) ) {
1567  ++$dotdotcount;
1568  $nodotdot = substr( $nodotdot, 3 );
1569  }
1570  if ( $dotdotcount > 0 ) {
1571  $exploded = explode( '/', $contextPrefixedText );
1572  if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1573  $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1574  # / at the end means don't show full path
1575  if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1576  $nodotdot = rtrim( $nodotdot, '/' );
1577  if ( $text === '' ) {
1578  $text = $nodotdot . $suffix;
1579  }
1580  }
1581  $nodotdot = trim( $nodotdot );
1582  if ( $nodotdot != '' ) {
1583  $ret .= '/' . $nodotdot;
1584  }
1585  $ret .= $suffix;
1586  }
1587  }
1588  }
1589  }
1590 
1591  return $ret;
1592  }
1593 
1613  public static function commentBlock(
1614  $comment, $title = null, $local = false, $wikiId = null, $useParentheses = true
1615  ) {
1616  return MediaWikiServices::getInstance()->getCommentFormatter()
1617  ->formatBlock( $comment, $title, $local, $wikiId, $useParentheses );
1618  }
1619 
1635  public static function revComment(
1636  RevisionRecord $revRecord,
1637  $local = false,
1638  $isPublic = false,
1639  $useParentheses = true
1640  ) {
1641  $authority = RequestContext::getMain()->getAuthority();
1642  $formatter = MediaWikiServices::getInstance()->getCommentFormatter();
1643  return $formatter->formatRevision( $revRecord, $authority, $local, $isPublic, $useParentheses );
1644  }
1645 
1651  public static function formatRevisionSize( $size ) {
1652  if ( $size == 0 ) {
1653  $stxt = wfMessage( 'historyempty' )->escaped();
1654  } else {
1655  $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1656  }
1657  return "<span class=\"history-size mw-diff-bytes\" data-mw-bytes=\"$size\">$stxt</span>";
1658  }
1659 
1666  public static function tocIndent() {
1667  return "\n<ul>\n";
1668  }
1669 
1677  public static function tocUnindent( $level ) {
1678  return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1679  }
1680 
1692  public static function tocLine( $linkAnchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1693  $classes = "toclevel-$level";
1694 
1695  // Parser.php used to suppress tocLine by setting $sectionindex to false.
1696  // In those circumstances, we can now encounter '' or a "T-" prefixed index
1697  // for when the section comes from templates.
1698  if ( $sectionIndex !== false && $sectionIndex !== '' && !str_starts_with( $sectionIndex, "T-" ) ) {
1699  $classes .= " tocsection-$sectionIndex";
1700  }
1701 
1702  // <li class="$classes"><a href="#$linkAnchor"><span class="tocnumber">
1703  // $tocnumber</span> <span class="toctext">$tocline</span></a>
1704  return Html::openElement( 'li', [ 'class' => $classes ] )
1705  . Html::rawElement( 'a',
1706  [ 'href' => "#$linkAnchor" ],
1707  Html::element( 'span', [ 'class' => 'tocnumber' ], $tocnumber )
1708  . ' '
1709  . Html::rawElement( 'span', [ 'class' => 'toctext' ], $tocline )
1710  );
1711  }
1712 
1720  public static function tocLineEnd() {
1721  return "</li>\n";
1722  }
1723 
1732  public static function tocList( $toc, Language $lang = null ) {
1733  $lang ??= RequestContext::getMain()->getLanguage();
1734 
1735  $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1736 
1737  return '<div id="toc" class="toc" role="navigation" aria-labelledby="mw-toc-heading">'
1738  . Html::element( 'input', [
1739  'type' => 'checkbox',
1740  'role' => 'button',
1741  'id' => 'toctogglecheckbox',
1742  'class' => 'toctogglecheckbox',
1743  'style' => 'display:none',
1744  ] )
1745  . Html::openElement( 'div', [
1746  'class' => 'toctitle',
1747  'lang' => $lang->getHtmlCode(),
1748  'dir' => $lang->getDir(),
1749  ] )
1750  . '<h2 id="mw-toc-heading">' . $title . '</h2>'
1751  . '<span class="toctogglespan">'
1752  . Html::label( '', 'toctogglecheckbox', [
1753  'class' => 'toctogglelabel',
1754  ] )
1755  . '</span>'
1756  . '</div>'
1757  . $toc
1758  . "</ul>\n</div>\n";
1759  }
1760 
1771  public static function generateTOC( $tree, Language $lang = null, array $options = [] ): string {
1772  $toc = '';
1773  $lastLevel = 0;
1774  $maxTocLevel = $options['maxtoclevel'] ?? null;
1775  foreach ( $tree as $section ) {
1776  if ( $section instanceof SectionMetadata ) {
1777  $section = $section->toLegacy();
1778  }
1779  $tocLevel = $section['toclevel'];
1780  if ( $maxTocLevel !== null && $tocLevel < $maxTocLevel ) {
1781  if ( $tocLevel > $lastLevel ) {
1782  $toc .= self::tocIndent();
1783  } elseif ( $tocLevel < $lastLevel ) {
1784  if ( $lastLevel < $maxTocLevel ) {
1785  $toc .= self::tocUnindent(
1786  $lastLevel - $tocLevel );
1787  } else {
1788  $toc .= self::tocLineEnd();
1789  }
1790  } else {
1791  $toc .= self::tocLineEnd();
1792  }
1793 
1794  $toc .= self::tocLine( $section['linkAnchor'],
1795  $section['line'], $section['number'],
1796  $tocLevel, $section['index'] );
1797  $lastLevel = $tocLevel;
1798  }
1799  }
1800  if ( $lastLevel < $maxTocLevel && $lastLevel > 0 ) {
1801  $toc .= self::tocUnindent( $lastLevel - 1 );
1802  }
1803  return self::tocList( $toc, $lang );
1804  }
1805 
1822  public static function makeHeadline( $level, $attribs, $anchor, $html,
1823  $link, $fallbackAnchor = false
1824  ) {
1825  $anchorEscaped = htmlspecialchars( $anchor, ENT_COMPAT );
1826  $fallback = '';
1827  if ( $fallbackAnchor !== false && $fallbackAnchor !== $anchor ) {
1828  $fallbackAnchor = htmlspecialchars( $fallbackAnchor, ENT_COMPAT );
1829  $fallback = "<span id=\"$fallbackAnchor\"></span>";
1830  }
1831  return "<h$level$attribs"
1832  . "$fallback<span class=\"mw-headline\" id=\"$anchorEscaped\">$html</span>"
1833  . $link
1834  . "</h$level>";
1835  }
1836 
1843  public static function splitTrail( $trail ) {
1844  $regex = MediaWikiServices::getInstance()->getContentLanguage()->linkTrail();
1845  $inside = '';
1846  if ( $trail !== '' && preg_match( $regex, $trail, $m ) ) {
1847  [ , $inside, $trail ] = $m;
1848  }
1849  return [ $inside, $trail ];
1850  }
1851 
1882  public static function generateRollback(
1883  RevisionRecord $revRecord,
1884  IContextSource $context = null,
1885  $options = []
1886  ) {
1887  $context ??= RequestContext::getMain();
1888 
1889  $editCount = self::getRollbackEditCount( $revRecord );
1890  if ( $editCount === false ) {
1891  return '';
1892  }
1893 
1894  $inner = self::buildRollbackLink( $revRecord, $context, $editCount );
1895 
1896  // Allow extensions to modify the rollback link.
1897  // Abort further execution if the extension wants full control over the link.
1898  if ( !Hooks::runner()->onLinkerGenerateRollbackLink(
1899  $revRecord, $context, $options, $inner ) ) {
1900  return $inner;
1901  }
1902 
1903  if ( !in_array( 'noBrackets', $options, true ) ) {
1904  $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1905  }
1906 
1907  if ( MediaWikiServices::getInstance()->getUserOptionsLookup()
1908  ->getBoolOption( $context->getUser(), 'showrollbackconfirmation' )
1909  ) {
1910  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1911  $stats->increment( 'rollbackconfirmation.event.load' );
1912  $context->getOutput()->addModules( 'mediawiki.misc-authed-curate' );
1913  }
1914 
1915  return '<span class="mw-rollback-link">' . $inner . '</span>';
1916  }
1917 
1936  public static function getRollbackEditCount( RevisionRecord $revRecord, $verify = true ) {
1937  if ( func_num_args() > 1 ) {
1938  wfDeprecated( __METHOD__ . ' with $verify parameter', '1.40' );
1939  }
1940  $showRollbackEditCount = MediaWikiServices::getInstance()->getMainConfig()
1941  ->get( MainConfigNames::ShowRollbackEditCount );
1942 
1943  if ( !is_int( $showRollbackEditCount ) || !$showRollbackEditCount > 0 ) {
1944  // Nothing has happened, indicate this by returning 'null'
1945  return null;
1946  }
1947 
1948  $dbr = wfGetDB( DB_REPLICA );
1949 
1950  // Up to the value of $wgShowRollbackEditCount revisions are counted
1951  $revQuery = MediaWikiServices::getInstance()->getRevisionStore()->getQueryInfo();
1952  $res = $dbr->newSelectQueryBuilder()
1953  ->select( [ 'rev_user_text' => $revQuery['fields']['rev_user_text'], 'rev_deleted' ] )
1954  ->tables( $revQuery['tables'] )
1955  ->where( [ 'rev_page' => $revRecord->getPageId() ] )
1956  ->joinConds( $revQuery['joins'] )
1957  ->useIndex( [ 'revision' => 'rev_page_timestamp' ] )
1958  ->orderBy( [ 'rev_timestamp', 'rev_id' ], SelectQueryBuilder::SORT_DESC )
1959  ->limit( $showRollbackEditCount + 1 )
1960  ->caller( __METHOD__ )
1961  ->fetchResultSet();
1962 
1963  $revUser = $revRecord->getUser( RevisionRecord::RAW );
1964  $revUserText = $revUser ? $revUser->getName() : '';
1965 
1966  $editCount = 0;
1967  $moreRevs = false;
1968  foreach ( $res as $row ) {
1969  if ( $row->rev_user_text != $revUserText ) {
1970  if ( $row->rev_deleted & RevisionRecord::DELETED_TEXT
1971  || $row->rev_deleted & RevisionRecord::DELETED_USER
1972  ) {
1973  // If the user or the text of the revision we might rollback
1974  // to is deleted in some way we can't rollback. Similar to
1975  // the checks in WikiPage::commitRollback.
1976  return false;
1977  }
1978  $moreRevs = true;
1979  break;
1980  }
1981  $editCount++;
1982  }
1983 
1984  if ( $editCount <= $showRollbackEditCount && !$moreRevs ) {
1985  // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1986  // and there weren't any other revisions. That means that the current user is the only
1987  // editor, so we can't rollback
1988  return false;
1989  }
1990  return $editCount;
1991  }
1992 
2007  public static function buildRollbackLink(
2008  RevisionRecord $revRecord,
2009  IContextSource $context = null,
2010  $editCount = false
2011  ) {
2012  $config = MediaWikiServices::getInstance()->getMainConfig();
2013  $showRollbackEditCount = $config->get( MainConfigNames::ShowRollbackEditCount );
2014  $miserMode = $config->get( MainConfigNames::MiserMode );
2015  // To config which pages are affected by miser mode
2016  $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
2017 
2018  $context ??= RequestContext::getMain();
2019 
2020  $title = $revRecord->getPageAsLinkTarget();
2021  $revUser = $revRecord->getUser();
2022  $revUserText = $revUser ? $revUser->getName() : '';
2023 
2024  $query = [
2025  'action' => 'rollback',
2026  'from' => $revUserText,
2027  'token' => $context->getUser()->getEditToken( 'rollback' ),
2028  ];
2029 
2030  $attrs = [
2031  'data-mw' => 'interface',
2032  'title' => $context->msg( 'tooltip-rollback' )->text()
2033  ];
2034 
2035  $options = [ 'known', 'noclasses' ];
2036 
2037  if ( $context->getRequest()->getBool( 'bot' ) ) {
2038  // T17999
2039  $query['hidediff'] = '1';
2040  $query['bot'] = '1';
2041  }
2042 
2043  if ( $miserMode ) {
2044  foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
2045  if ( $context->getTitle()->isSpecial( $specialPage ) ) {
2046  $showRollbackEditCount = false;
2047  break;
2048  }
2049  }
2050  }
2051 
2052  // The edit count can be 0 on replica lag, fall back to the generic rollbacklink message
2053  $msg = [ 'rollbacklink' ];
2054  if ( is_int( $showRollbackEditCount ) && $showRollbackEditCount > 0 ) {
2055  if ( !is_numeric( $editCount ) ) {
2056  $editCount = self::getRollbackEditCount( $revRecord );
2057  }
2058 
2059  if ( $editCount > $showRollbackEditCount ) {
2060  $msg = [ 'rollbacklinkcount-morethan', Message::numParam( $showRollbackEditCount ) ];
2061  } elseif ( $editCount ) {
2062  $msg = [ 'rollbacklinkcount', Message::numParam( $editCount ) ];
2063  }
2064  }
2065 
2066  $html = $context->msg( ...$msg )->parse();
2067  return self::link( $title, $html, $attrs, $query, $options );
2068  }
2069 
2078  public static function formatHiddenCategories( $hiddencats ) {
2079  $outText = '';
2080  if ( count( $hiddencats ) > 0 ) {
2081  # Construct the HTML
2082  $outText = '<div class="mw-hiddenCategoriesExplanation">';
2083  $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
2084  $outText .= "</div><ul>\n";
2085 
2086  foreach ( $hiddencats as $titleObj ) {
2087  # If it's hidden, it must exist - no need to check with a LinkBatch
2088  $outText .= '<li>'
2089  . self::link( $titleObj, null, [], [], 'known' )
2090  . "</li>\n";
2091  }
2092  $outText .= '</ul>';
2093  }
2094  return $outText;
2095  }
2096 
2100  private static function getContextFromMain() {
2101  $context = RequestContext::getMain();
2102  $context = new DerivativeContext( $context );
2103  return $context;
2104  }
2105 
2123  public static function titleAttrib( $name, $options = null, array $msgParams = [], $localizer = null ) {
2124  if ( !$localizer ) {
2125  $localizer = self::getContextFromMain();
2126  }
2127  $message = $localizer->msg( "tooltip-$name", $msgParams );
2128  if ( $message->isDisabled() ) {
2129  $tooltip = false;
2130  } else {
2131  $tooltip = $message->text();
2132  # Compatibility: formerly some tooltips had [alt-.] hardcoded
2133  $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2134  }
2135 
2136  $options = (array)$options;
2137 
2138  if ( in_array( 'nonexisting', $options ) ) {
2139  $tooltip = $localizer->msg( 'red-link-title', $tooltip ?: '' )->text();
2140  }
2141  if ( in_array( 'withaccess', $options ) ) {
2142  $accesskey = self::accesskey( $name, $localizer );
2143  if ( $accesskey !== false ) {
2144  // Should be build the same as in jquery.accessKeyLabel.js
2145  if ( $tooltip === false || $tooltip === '' ) {
2146  $tooltip = $localizer->msg( 'brackets', $accesskey )->text();
2147  } else {
2148  $tooltip .= $localizer->msg( 'word-separator' )->text();
2149  $tooltip .= $localizer->msg( 'brackets', $accesskey )->text();
2150  }
2151  }
2152  }
2153 
2154  return $tooltip;
2155  }
2156 
2157  public static $accesskeycache;
2158 
2171  public static function accesskey( $name, $localizer = null ) {
2172  if ( !isset( self::$accesskeycache[$name] ) ) {
2173  if ( !$localizer ) {
2174  $localizer = self::getContextFromMain();
2175  }
2176  $msg = $localizer->msg( "accesskey-$name" );
2177  self::$accesskeycache[$name] = $msg->isDisabled() ? false : $msg->plain();
2178  }
2179  return self::$accesskeycache[$name];
2180  }
2181 
2196  public static function getRevDeleteLink(
2197  Authority $performer,
2198  RevisionRecord $revRecord,
2200  ) {
2201  $canHide = $performer->isAllowed( 'deleterevision' );
2202  $canHideHistory = $performer->isAllowed( 'deletedhistory' );
2203  if ( !$canHide && !( $revRecord->getVisibility() && $canHideHistory ) ) {
2204  return '';
2205  }
2206 
2207  if ( !$revRecord->userCan( RevisionRecord::DELETED_RESTRICTED, $performer ) ) {
2208  return self::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2209  }
2210  $prefixedDbKey = MediaWikiServices::getInstance()->getTitleFormatter()->
2211  getPrefixedDBkey( $title );
2212  if ( $revRecord->getId() ) {
2213  // RevDelete links using revision ID are stable across
2214  // page deletion and undeletion; use when possible.
2215  $query = [
2216  'type' => 'revision',
2217  'target' => $prefixedDbKey,
2218  'ids' => $revRecord->getId()
2219  ];
2220  } else {
2221  // Older deleted entries didn't save a revision ID.
2222  // We have to refer to these by timestamp, ick!
2223  $query = [
2224  'type' => 'archive',
2225  'target' => $prefixedDbKey,
2226  'ids' => $revRecord->getTimestamp()
2227  ];
2228  }
2229  return self::revDeleteLink(
2230  $query,
2231  $revRecord->isDeleted( RevisionRecord::DELETED_RESTRICTED ),
2232  $canHide
2233  );
2234  }
2235 
2248  public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2249  $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2250  $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2251  $html = wfMessage( $msgKey )->escaped();
2252  $tag = $restricted ? 'strong' : 'span';
2253  $link = self::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2254  return Xml::tags(
2255  $tag,
2256  [ 'class' => 'mw-revdelundel-link' ],
2257  wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2258  );
2259  }
2260 
2272  public static function revDeleteLinkDisabled( $delete = true ) {
2273  $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2274  $html = wfMessage( $msgKey )->escaped();
2275  $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2276  return Xml::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2277  }
2278 
2290  private static function updateWatchstarTooltipMessage(
2291  string &$tooltip, array &$msgParams, $config, $user, $relevantTitle
2292  ): void {
2293  if ( !$config || !$user || !$relevantTitle ) {
2294  $mainContext = self::getContextFromMain();
2295  if ( !$config ) {
2296  $config = $mainContext->getConfig();
2297  }
2298  if ( !$user ) {
2299  $user = $mainContext->getUser();
2300  }
2301  if ( !$relevantTitle ) {
2302  $relevantTitle = $mainContext->getSkin()->getRelevantTitle();
2303  }
2304  }
2305 
2306  $isWatchlistExpiryEnabled = $config->get( MainConfigNames::WatchlistExpiry );
2307  if ( !$isWatchlistExpiryEnabled || !$relevantTitle || !$relevantTitle->canExist() ) {
2308  return;
2309  }
2310 
2311  $watchStore = MediaWikiServices::getInstance()->getWatchedItemStore();
2312  $watchedItem = $watchStore->getWatchedItem( $user, $relevantTitle );
2313  if ( $watchedItem instanceof WatchedItem && $watchedItem->getExpiry() !== null ) {
2314  $diffInDays = $watchedItem->getExpiryInDays();
2315 
2316  if ( $diffInDays ) {
2317  $msgParams = [ $diffInDays ];
2318  // Resolves to tooltip-ca-unwatch-expiring message
2319  $tooltip = 'ca-unwatch-expiring';
2320  } else { // Resolves to tooltip-ca-unwatch-expiring-hours message
2321  $tooltip = 'ca-unwatch-expiring-hours';
2322  }
2323  }
2324  }
2325 
2342  public static function tooltipAndAccesskeyAttribs(
2343  $name,
2344  array $msgParams = [],
2345  $options = null,
2346  $localizer = null,
2347  $user = null,
2348  $config = null,
2349  $relevantTitle = null
2350  ) {
2351  $options = (array)$options;
2352  $options[] = 'withaccess';
2353  $tooltipTitle = $name;
2354 
2355  // Get optional parameters from global context if any missing.
2356  if ( !$localizer ) {
2357  $localizer = self::getContextFromMain();
2358  }
2359 
2360  // @since 1.35 - add a WatchlistExpiry feature flag to show new watchstar tooltip message
2361  if ( $name === 'ca-unwatch' ) {
2362  self::updateWatchstarTooltipMessage( $tooltipTitle, $msgParams, $config, $user, $relevantTitle );
2363  }
2364 
2365  $attribs = [
2366  'title' => self::titleAttrib( $tooltipTitle, $options, $msgParams, $localizer ),
2367  'accesskey' => self::accesskey( $name, $localizer )
2368  ];
2369  if ( $attribs['title'] === false ) {
2370  unset( $attribs['title'] );
2371  }
2372  if ( $attribs['accesskey'] === false ) {
2373  unset( $attribs['accesskey'] );
2374  }
2375  return $attribs;
2376  }
2377 
2385  public static function tooltip( $name, $options = null ) {
2386  $tooltip = self::titleAttrib( $name, $options );
2387  if ( $tooltip === false ) {
2388  return '';
2389  }
2390  return Xml::expandAttributes( [
2391  'title' => $tooltip
2392  ] );
2393  }
2394 
2395 }
2396 
2397 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.
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:508
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgTitle
Definition: Setup.php:508
if(!defined('MW_SETUP_CALLBACK'))
The persistent session ID (if any) loaded at startup.
Definition: WebStart.php:82
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:67
Hooks class.
Definition: Hooks.php:38
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:173
Marks HTML that shouldn't be escaped.
Definition: HtmlArmor.php:30
This class is a collection of static functions that serve two purposes:
Definition: Html.php:51
static label( $label, $id, array $attribs=[])
Convenience function for generating a label for inputs.
Definition: Html.php:835
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:236
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:214
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:256
Base class for language-specific code.
Definition: Language.php:56
Base class for the output of MediaHandler::doTransform() and File::transform().
Some internal bits split of from Skin.php.
Definition: Linker.php:65
static expandLocalLinks(string $html)
Helper function to expand local links.
Definition: Linker.php:1442
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:1635
static revDeleteLink( $query=[], $restricted=false, $delete=true)
Creates a (show/hide) link for deleting revisions/log entries.
Definition: Linker.php:2248
static link( $target, $html=null, $customAttribs=[], $query=[], $options=[])
This function returns an HTML link to the given target.
Definition: Linker.php:114
static tocLineEnd()
End a Table Of Contents line.
Definition: Linker.php:1720
static blockLink( $userId, $userText)
Definition: Linker.php:1294
static makeSelfLinkObj( $nt, $html='', $query='', $trail='', $prefix='', $hash='')
Make appropriate markup for a link to the current article.
Definition: Linker.php:190
static getUploadUrl( $destFile, $query='')
Get the URL to upload a certain file.
Definition: Linker.php:924
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:324
static makeMediaLinkObj( $title, $html='', $time=false)
Create a direct link to a given uploaded file.
Definition: Linker.php:955
static processResponsiveImages( $file, $thumb, $hp)
Process responsive images: add 1.5x and 2x subimages to the thumbnail, where applicable.
Definition: Linker.php:815
static userTalkLink( $userId, $userText)
Definition: Linker.php:1272
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:1613
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:1477
static normalizeSubpageLink( $contextTitle, $target, &$text)
Definition: Linker.php:1516
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:1016
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:1177
static emailLink( $userId, $userText)
Definition: Linker.php:1315
static formatHiddenCategories( $hiddencats)
Returns HTML for the "hidden categories on this page" list.
Definition: Linker.php:2078
static getInvalidTitleDescription(IContextSource $context, $namespace, $title)
Get a message saying that an invalid title was encountered.
Definition: Linker.php:224
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:1936
static makeExternalLink( $url, $text, $escape=true, $linktype='', $attribs=[], $title=null)
Make an external link.
Definition: Linker.php:1063
static getImageLinkMTOParams( $frameParams, $query='', $parser=null)
Get the link parameters for MediaTransformOutput::toHtml() from given frame parameters supplied by th...
Definition: Linker.php:557
static linkKnown( $target, $html=null, $customAttribs=[], $query=[], $options=[ 'known'])
Identical to link(), except $options defaults to 'known'.
Definition: Linker.php:166
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:2196
static makeThumbLink2(LinkTarget $title, $file, $frameParams=[], $handlerParams=[], $time=false, $query='', array $classes=[], ?Parser $parser=null)
Definition: Linker.php:633
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:1732
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
Definition: Linker.php:1822
static makeExternalImage( $url, $alt='')
Return the code for images which were added via external links, via Parser::maybeMakeExternalImage().
Definition: Linker.php:267
static tooltip( $name, $options=null)
Returns raw bits of HTML, use titleAttrib()
Definition: Linker.php:2385
static makeMediaLinkFile(LinkTarget $title, $file, $html='')
Create a direct link to a given uploaded file.
Definition: Linker.php:974
static accesskey( $name, $localizer=null)
Given the id of an interface element, constructs the appropriate accesskey attribute from the system ...
Definition: Linker.php:2171
static generateTOC( $tree, Language $lang=null, array $options=[])
Definition: Linker.php:1771
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:2123
static userToolLinksRedContribs( $userId, $userText, $edits=null, $useParentheses=true)
Alias for userToolLinks( $userId, $userText, true );.
Definition: Linker.php:1260
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:1843
static tocIndent()
Add another level to the Table of Contents.
Definition: Linker.php:1666
const TOOL_LINKS_NOBLOCK
Flags for userToolLinks()
Definition: Linker.php:69
static revDeleteLinkDisabled( $delete=true)
Creates a dead (show/hide) link for deleting revisions/log entries.
Definition: Linker.php:2272
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:2342
static makeBrokenImageLinkObj( $title, $label='', $query='', $unused1='', $unused2='', $time=false, array $handlerParams=[])
Make a "broken" link to an image.
Definition: Linker.php:851
static formatRevisionSize( $size)
Definition: Linker.php:1651
static tocUnindent( $level)
Finish one or more sublevels on the Table of Contents.
Definition: Linker.php:1677
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:1503
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:600
static userLink( $userId, $userName, $altUserName=false, $attributes=[])
Make user link (or user contributions for unregistered users)
Definition: Linker.php:1117
static revUserLink(RevisionRecord $revRecord, $isPublic=false)
Generate a user link if the current user is allowed to view it.
Definition: Linker.php:1341
static getRevisionDeletedClass(RevisionRecord $revisionRecord)
Returns css class of a deleted revision.
Definition: Linker.php:1369
static generateRollback(RevisionRecord $revRecord, IContextSource $context=null, $options=[])
Generate a rollback link for a given revision.
Definition: Linker.php:1882
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:1389
static tocLine( $linkAnchor, $tocline, $tocnumber, $level, $sectionIndex=false)
parameter level defines if we are on an indentation level
Definition: Linker.php:1692
static buildRollbackLink(RevisionRecord $revRecord, IContextSource $context=null, $editCount=false)
Build a raw rollback link, useful for collections of "tool" links.
Definition: Linker.php:2007
A class containing constants representing the names of configuration variables.
const UploadNavigationUrl
Name constant for the UploadNavigationUrl 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.
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition: Message.php:143
static numParam( $num)
Definition: Message.php:1145
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition: Parser.php:104
getTargetLanguage()
Get the target language for the content being parsed.
Definition: Parser.php:1184
static getExternalLinkRel( $url=false, LinkTarget $title=null)
Get the rel attribute for a particular external link.
Definition: Parser.php:2256
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:44
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,...
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
Represents a title within MediaWiki.
Definition: Title.php:52
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:285
static castFromLinkTarget( $linkTarget)
Same as newFromLinkTarget, but if passed null, returns null.
Definition: Title.php:309
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:667
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:70
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:632
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.
A query builder for SELECT queries with a fluent interface.
Module of static functions for generating XML.
Definition: Xml.php:30
static expandAttributes( $attribs)
Given an array of ('attributename' => 'value'), it generates the code to set the XML attributes : att...
Definition: Xml.php:69
static tags( $element, $attribs, $contents)
Same as Xml::element(), but does not escape contents.
Definition: Xml.php:134
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.
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s
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