MediaWiki  master
Linker.php
Go to the documentation of this file.
1 <?php
26 use Wikimedia\IPUtils;
27 
37 class Linker {
41  public const TOOL_LINKS_NOBLOCK = 1;
42  public const TOOL_LINKS_EMAIL = 2;
43 
87  public static function link(
88  $target, $html = null, $customAttribs = [], $query = [], $options = []
89  ) {
90  if ( !$target instanceof LinkTarget ) {
91  wfWarn( __METHOD__ . ': Requires $target to be a LinkTarget object.', 2 );
92  return "<!-- ERROR -->$html";
93  }
94 
95  $services = MediaWikiServices::getInstance();
96  $options = (array)$options;
97  if ( $options ) {
98  // Custom options, create new LinkRenderer
99  if ( !isset( $options['stubThreshold'] ) ) {
100  $defaultLinkRenderer = $services->getLinkRenderer();
101  $options['stubThreshold'] = $defaultLinkRenderer->getStubThreshold();
102  }
103  $linkRenderer = $services->getLinkRendererFactory()
104  ->createFromLegacyOptions( $options );
105  } else {
106  $linkRenderer = $services->getLinkRenderer();
107  }
108 
109  if ( $html !== null ) {
110  $text = new HtmlArmor( $html );
111  } else {
112  $text = null;
113  }
114 
115  if ( in_array( 'known', $options, true ) ) {
116  return $linkRenderer->makeKnownLink( $target, $text, $customAttribs, $query );
117  }
118 
119  if ( in_array( 'broken', $options, true ) ) {
120  return $linkRenderer->makeBrokenLink( $target, $text, $customAttribs, $query );
121  }
122 
123  if ( in_array( 'noclasses', $options, true ) ) {
124  return $linkRenderer->makePreloadedLink( $target, $text, '', $customAttribs, $query );
125  }
126 
127  return $linkRenderer->makeLink( $target, $text, $customAttribs, $query );
128  }
129 
143  public static function linkKnown(
144  $target, $html = null, $customAttribs = [],
145  $query = [], $options = [ 'known' ]
146  ) {
147  return self::link( $target, $html, $customAttribs, $query, $options );
148  }
149 
165  public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
166  $nt = Title::newFromLinkTarget( $nt );
167  $ret = "<a class=\"mw-selflink selflink\">{$prefix}{$html}</a>{$trail}";
168  if ( !Hooks::runner()->onSelfLinkBegin( $nt, $html, $trail, $prefix, $ret ) ) {
169  return $ret;
170  }
171 
172  if ( $html == '' ) {
173  $html = htmlspecialchars( $nt->getPrefixedText() );
174  }
175  list( $inside, $trail ) = self::splitTrail( $trail );
176  return "<a class=\"mw-selflink selflink\">{$prefix}{$html}{$inside}</a>{$trail}";
177  }
178 
189  public static function getInvalidTitleDescription( IContextSource $context, $namespace, $title ) {
190  // First we check whether the namespace exists or not.
191  if ( MediaWikiServices::getInstance()->getNamespaceInfo()->exists( $namespace ) ) {
192  if ( $namespace == NS_MAIN ) {
193  $name = $context->msg( 'blanknamespace' )->text();
194  } else {
195  $name = MediaWikiServices::getInstance()->getContentLanguage()->
196  getFormattedNsText( $namespace );
197  }
198  return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
199  }
200 
201  return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
202  }
203 
210  public static function normaliseSpecialPage( LinkTarget $target ) {
211  wfDeprecated( __METHOD__, '1.35' );
212  $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
213  return $linkRenderer->normalizeTarget( $target );
214  }
215 
224  private static function fnamePart( $url ) {
225  $basename = strrchr( $url, '/' );
226  if ( $basename === false ) {
227  $basename = $url;
228  } else {
229  $basename = substr( $basename, 1 );
230  }
231  return $basename;
232  }
233 
244  public static function makeExternalImage( $url, $alt = '' ) {
245  if ( $alt == '' ) {
246  $alt = self::fnamePart( $url );
247  }
248  $img = '';
249  $success = Hooks::runner()->onLinkerMakeExternalImage( $url, $alt, $img );
250  if ( !$success ) {
251  wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
252  . "with url {$url} and alt text {$alt} to {$img}" );
253  return $img;
254  }
255  return Html::element( 'img',
256  [
257  'src' => $url,
258  'alt' => $alt
259  ]
260  );
261  }
262 
300  public static function makeImageLink( Parser $parser, LinkTarget $title,
301  $file, $frameParams = [], $handlerParams = [], $time = false,
302  $query = "", $widthOption = null
303  ) {
305  $res = null;
306  $dummy = new DummyLinker;
307  if ( !Hooks::runner()->onImageBeforeProduceHTML( $dummy, $title,
308  $file, $frameParams, $handlerParams, $time, $res,
309  $parser, $query, $widthOption )
310  ) {
311  return $res;
312  }
313 
314  if ( $file && !$file->allowInlineDisplay() ) {
315  wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . " does not allow inline display" );
316  return self::link( $title );
317  }
318 
319  // Clean up parameters
320  $page = $handlerParams['page'] ?? false;
321  if ( !isset( $frameParams['align'] ) ) {
322  $frameParams['align'] = '';
323  }
324  if ( !isset( $frameParams['alt'] ) ) {
325  $frameParams['alt'] = '';
326  }
327  if ( !isset( $frameParams['title'] ) ) {
328  $frameParams['title'] = '';
329  }
330  if ( !isset( $frameParams['class'] ) ) {
331  $frameParams['class'] = '';
332  }
333 
334  $services = MediaWikiServices::getInstance();
335  $enableLegacyMediaDOM = $services->getMainConfig()->get( 'ParserEnableLegacyMediaDOM' );
336 
337  $classes = [];
338  if ( !isset( $handlerParams['width'] ) ) {
339  $classes[] = 'mw-default-size';
340  }
341 
342  $prefix = $postfix = '';
343 
344  if ( $enableLegacyMediaDOM ) {
345  if ( $frameParams['align'] == 'center' ) {
346  $prefix = '<div class="center">';
347  $postfix = '</div>';
348  $frameParams['align'] = 'none';
349  }
350  }
351 
352  if ( $file && !isset( $handlerParams['width'] ) ) {
353  if ( isset( $handlerParams['height'] ) && $file->isVectorized() ) {
354  // If its a vector image, and user only specifies height
355  // we don't want it to be limited by its "normal" width.
356  global $wgSVGMaxSize;
357  $handlerParams['width'] = $wgSVGMaxSize;
358  } else {
359  $handlerParams['width'] = $file->getWidth( $page );
360  }
361 
362  if ( isset( $frameParams['thumbnail'] )
363  || isset( $frameParams['manualthumb'] )
364  || isset( $frameParams['framed'] )
365  || isset( $frameParams['frameless'] )
366  || !$handlerParams['width']
367  ) {
369 
370  if ( $widthOption === null || !isset( $wgThumbLimits[$widthOption] ) ) {
371  $userOptionsLookup = MediaWikiServices::getInstance()->getUserOptionsLookup();
372  $widthOption = $userOptionsLookup->getDefaultOption( 'thumbsize' );
373  }
374 
375  // Reduce width for upright images when parameter 'upright' is used
376  if ( isset( $frameParams['upright'] ) && $frameParams['upright'] == 0 ) {
377  $frameParams['upright'] = $wgThumbUpright;
378  }
379 
380  // For caching health: If width scaled down due to upright
381  // parameter, round to full __0 pixel to avoid the creation of a
382  // lot of odd thumbs.
383  $prefWidth = isset( $frameParams['upright'] ) ?
384  round( $wgThumbLimits[$widthOption] * $frameParams['upright'], -1 ) :
385  $wgThumbLimits[$widthOption];
386 
387  // Use width which is smaller: real image width or user preference width
388  // Unless image is scalable vector.
389  if ( !isset( $handlerParams['height'] ) && ( $handlerParams['width'] <= 0 ||
390  $prefWidth < $handlerParams['width'] || $file->isVectorized() ) ) {
391  $handlerParams['width'] = $prefWidth;
392  }
393  }
394  }
395 
396  if ( isset( $frameParams['thumbnail'] ) || isset( $frameParams['manualthumb'] )
397  || isset( $frameParams['framed'] )
398  ) {
399  if ( $enableLegacyMediaDOM ) {
400  // This is no longer needed in our new media output, since the
401  // default styling in content.media.less takes care of it;
402  // see T269704.
403 
404  # Create a thumbnail. Alignment depends on the writing direction of
405  # the page content language (right-aligned for LTR languages,
406  # left-aligned for RTL languages)
407  # If a thumbnail width has not been provided, it is set
408  # to the default user option as specified in Language*.php
409  if ( $frameParams['align'] == '' ) {
410  $frameParams['align'] = $parser->getTargetLanguage()->alignEnd();
411  }
412  }
413  return $prefix .
414  self::makeThumbLink2( $title, $file, $frameParams, $handlerParams, $time, $query, $classes ) .
415  $postfix;
416  }
417 
418  switch ( $file ? $file->getMediaType() : '' ) {
419  case 'AUDIO':
420  $rdfaType = 'mw:Audio';
421  break;
422  case 'VIDEO':
423  $rdfaType = 'mw:Video';
424  break;
425  default:
426  $rdfaType = 'mw:Image';
427  }
428 
429  if ( $file && isset( $frameParams['frameless'] ) ) {
430  $rdfaType .= '/Frameless';
431  $srcWidth = $file->getWidth( $page );
432  # For "frameless" option: do not present an image bigger than the
433  # source (for bitmap-style images). This is the same behavior as the
434  # "thumb" option does it already.
435  if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
436  $handlerParams['width'] = $srcWidth;
437  }
438  }
439 
440  if ( $file && isset( $handlerParams['width'] ) ) {
441  # Create a resized image, without the additional thumbnail features
442  $thumb = $file->transform( $handlerParams );
443  } else {
444  $thumb = false;
445  }
446 
447  if ( !$thumb ) {
448  $rdfaType = 'mw:Error ' . $rdfaType;
449  $label = '';
450  if ( $enableLegacyMediaDOM ) {
451  // This is the information for tooltips for inline images which
452  // Parsoid stores in data-mw. See T273014
453  $label = $frameParams['title'];
454  }
456  $title, $label, '', '', '', $time == true, $handlerParams
457  );
458  } else {
459  self::processResponsiveImages( $file, $thumb, $handlerParams );
460  $params = [
461  'alt' => $frameParams['alt'],
462  'title' => $frameParams['title'],
463  ];
464  if ( $enableLegacyMediaDOM ) {
465  $params += [
466  'valign' => $frameParams['valign'] ?? false,
467  'img-class' => $frameParams['class'],
468  ];
469  if ( isset( $frameParams['border'] ) ) {
470  $params['img-class'] .= ( $params['img-class'] !== '' ? ' ' : '' ) . 'thumbborder';
471  }
472  }
473  $params = self::getImageLinkMTOParams( $frameParams, $query, $parser ) + $params;
474  $s = $thumb->toHtml( $params );
475  }
476 
477  if ( $enableLegacyMediaDOM ) {
478  if ( $frameParams['align'] != '' ) {
480  'div',
481  [ 'class' => 'float' . $frameParams['align'] ],
482  $s
483  );
484  }
485  return str_replace( "\n", ' ', $prefix . $s . $postfix );
486  }
487 
488  $wrapper = 'span';
489  $caption = '';
490 
491  if ( $frameParams['align'] != '' ) {
492  $wrapper = 'figure';
493  // Possible values: mw-halign-left mw-halign-center mw-halign-right mw-halign-none
494  $classes[] = "mw-halign-{$frameParams['align']}";
495  $caption = Html::rawElement(
496  'figcaption', [], $frameParams['caption'] ?? ''
497  );
498  } elseif ( isset( $frameParams['valign'] ) ) {
499  // Possible values: mw-valign-middle mw-valign-baseline mw-valign-sub
500  // mw-valign-super mw-valign-top mw-valign-text-top mw-valign-bottom
501  // mw-valign-text-bottom
502  $classes[] = "mw-valign-{$frameParams['valign']}";
503  }
504 
505  if ( isset( $frameParams['border'] ) ) {
506  $classes[] = 'mw-image-border';
507  }
508 
509  if ( isset( $frameParams['class'] ) ) {
510  $classes[] = $frameParams['class'];
511  }
512 
513  $attribs = [
514  'class' => $classes,
515  'typeof' => $rdfaType,
516  ];
517 
518  $s = Html::rawElement( $wrapper, $attribs, $s . $caption );
519 
520  return str_replace( "\n", ' ', $s );
521  }
522 
531  private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
532  $mtoParams = [];
533  if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
534  $mtoParams['custom-url-link'] = $frameParams['link-url'];
535  if ( isset( $frameParams['link-target'] ) ) {
536  $mtoParams['custom-target-link'] = $frameParams['link-target'];
537  }
538  if ( $parser ) {
539  $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
540  foreach ( $extLinkAttrs as $name => $val ) {
541  // Currently could include 'rel' and 'target'
542  $mtoParams['parser-extlink-' . $name] = $val;
543  }
544  }
545  } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
546  $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
547  $mtoParams['custom-title-link'] = Title::newFromLinkTarget(
548  $linkRenderer->normalizeTarget( $frameParams['link-title'] )
549  );
550  } elseif ( !empty( $frameParams['no-link'] ) ) {
551  // No link
552  } else {
553  $mtoParams['desc-link'] = true;
554  $mtoParams['desc-query'] = $query;
555  }
556  return $mtoParams;
557  }
558 
571  public static function makeThumbLinkObj(
572  LinkTarget $title, $file, $label = '', $alt = '', $align = null,
573  $params = [], $framed = false, $manualthumb = ""
574  ) {
575  $frameParams = [
576  'alt' => $alt,
577  'caption' => $label,
578  'align' => $align
579  ];
580  if ( $framed ) {
581  $frameParams['framed'] = true;
582  }
583  if ( $manualthumb ) {
584  $frameParams['manualthumb'] = $manualthumb;
585  }
586  $classes = [ 'mw-default-size' ];
587  return self::makeThumbLink2(
588  $title, $file, $frameParams, $params, false, '', $classes
589  );
590  }
591 
602  public static function makeThumbLink2(
603  LinkTarget $title, $file, $frameParams = [], $handlerParams = [],
604  $time = false, $query = "", array $classes = []
605  ) {
606  $exists = $file && $file->exists();
607 
608  $services = MediaWikiServices::getInstance();
609  $enableLegacyMediaDOM = $services->getMainConfig()->get( 'ParserEnableLegacyMediaDOM' );
610 
611  $page = $handlerParams['page'] ?? false;
612  if ( !isset( $frameParams['align'] ) ) {
613  $frameParams['align'] = '';
614  if ( $enableLegacyMediaDOM ) {
615  $frameParams['align'] = 'right';
616  }
617  }
618  if ( !isset( $frameParams['alt'] ) ) {
619  $frameParams['alt'] = '';
620  }
621  if ( !isset( $frameParams['title'] ) ) {
622  $frameParams['title'] = '';
623  }
624  if ( !isset( $frameParams['caption'] ) ) {
625  $frameParams['caption'] = '';
626  }
627 
628  if ( empty( $handlerParams['width'] ) ) {
629  // Reduce width for upright images when parameter 'upright' is used
630  $handlerParams['width'] = isset( $frameParams['upright'] ) ? 130 : 180;
631  }
632 
633  $thumb = false;
634  $noscale = false;
635  $manualthumb = false;
636  $rdfaType = null;
637 
638  if ( !$exists ) {
639  $outerWidth = $handlerParams['width'] + 2;
640  } else {
641  if ( isset( $frameParams['manualthumb'] ) ) {
642  # Use manually specified thumbnail
643  $manual_title = Title::makeTitleSafe( NS_FILE, $frameParams['manualthumb'] );
644  if ( $manual_title ) {
645  $manual_img = $services->getRepoGroup()
646  ->findFile( $manual_title );
647  if ( $manual_img ) {
648  $thumb = $manual_img->getUnscaledThumb( $handlerParams );
649  $manualthumb = true;
650  } else {
651  $exists = false;
652  }
653  }
654  } elseif ( isset( $frameParams['framed'] ) ) {
655  // Use image dimensions, don't scale
656  $thumb = $file->getUnscaledThumb( $handlerParams );
657  $noscale = true;
658  $rdfaType = '/Frame';
659  } else {
660  # Do not present an image bigger than the source, for bitmap-style images
661  # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
662  $srcWidth = $file->getWidth( $page );
663  if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
664  $handlerParams['width'] = $srcWidth;
665  }
666  $thumb = $file->transform( $handlerParams );
667  }
668 
669  if ( $thumb ) {
670  $outerWidth = $thumb->getWidth() + 2;
671  } else {
672  $outerWidth = $handlerParams['width'] + 2;
673  }
674  }
675 
676  $url = Title::newFromLinkTarget( $title )->getLocalURL( $query );
677 
678  if ( $enableLegacyMediaDOM && $page ) {
679  # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
680  # So we don't need to pass it here in $query. However, the URL for the
681  # zoom icon still needs it, so we make a unique query for it. See T16771
682  $url = wfAppendQuery( $url, [ 'page' => $page ] );
683  }
684 
685  if ( $manualthumb
686  && !isset( $frameParams['link-title'] )
687  && !isset( $frameParams['link-url'] )
688  && !isset( $frameParams['no-link'] ) ) {
689  $frameParams['link-url'] = $url;
690  }
691 
692  if ( $frameParams['align'] != '' ) {
693  // Possible values: mw-halign-left mw-halign-center mw-halign-right mw-halign-none
694  $classes[] = "mw-halign-{$frameParams['align']}";
695  }
696 
697  if ( isset( $frameParams['class'] ) ) {
698  $classes[] = $frameParams['class'];
699  }
700 
701  $s = '';
702 
703  if ( $enableLegacyMediaDOM ) {
704  $s .= "<div class=\"thumb t{$frameParams['align']}\">"
705  . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
706  }
707 
708  if ( !$exists ) {
709  $label = '';
710  if ( $enableLegacyMediaDOM ) {
711  // This is the information for tooltips for inline images which
712  // Parsoid stores in data-mw. See T273014
713  $label = $frameParams['title'];
714  }
716  $title, $label, '', '', '', $time == true, $handlerParams
717  );
718  $zoomIcon = '';
719  } elseif ( !$thumb ) {
720  // FIXME(T169975): Add "mw:Error"?
721  $s .= wfMessage( 'thumbnail_error', '' )->escaped();
722  $zoomIcon = '';
723  } else {
724  if ( !$noscale && !$manualthumb ) {
725  self::processResponsiveImages( $file, $thumb, $handlerParams );
726  }
727  $params = [
728  'alt' => $frameParams['alt'],
729  'title' => $frameParams['title'],
730  ];
731  if ( $enableLegacyMediaDOM ) {
732  $params += [
733  'img-class' => ( isset( $frameParams['class'] ) && $frameParams['class'] !== ''
734  ? $frameParams['class'] . ' '
735  : '' ) . 'thumbimage'
736  ];
737  }
738  $params = self::getImageLinkMTOParams( $frameParams, $query ) + $params;
739  $s .= $thumb->toHtml( $params );
740  if ( isset( $frameParams['framed'] ) ) {
741  $zoomIcon = "";
742  } else {
743  $zoomIcon = Html::rawElement( 'div', [ 'class' => 'magnify' ],
744  Html::rawElement( 'a', [
745  'href' => $url,
746  'class' => 'internal',
747  'title' => wfMessage( 'thumbnail-more' )->text() ],
748  "" ) );
749  }
750  }
751 
752  if ( $enableLegacyMediaDOM ) {
753  $s .= ' <div class="thumbcaption">' . $zoomIcon . $frameParams['caption'] . "</div></div></div>";
754  return str_replace( "\n", ' ', $s );
755  }
756 
757  $s .= Html::rawElement(
758  'figcaption', [], $frameParams['caption'] ?? ''
759  );
760 
761  $rdfaType = $rdfaType ?: '/Thumb';
762 
763  switch ( $file ? $file->getMediaType() : '' ) {
764  case 'AUDIO':
765  $rdfaType = 'mw:Audio' . $rdfaType;
766  break;
767  case 'VIDEO':
768  $rdfaType = 'mw:Video' . $rdfaType;
769  break;
770  default:
771  $rdfaType = 'mw:Image' . $rdfaType;
772  }
773 
774  if ( !$exists ) {
775  $rdfaType = 'mw:Error ' . $rdfaType;
776  }
777 
778  $attribs = [
779  'class' => $classes,
780  'typeof' => $rdfaType,
781  ];
782 
783  $s = Html::rawElement( 'figure', $attribs, $s );
784 
785  return str_replace( "\n", ' ', $s );
786  }
787 
796  public static function processResponsiveImages( $file, $thumb, $hp ) {
797  global $wgResponsiveImages;
798  if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
799  $hp15 = $hp;
800  $hp15['width'] = round( $hp['width'] * 1.5 );
801  $hp20 = $hp;
802  $hp20['width'] = $hp['width'] * 2;
803  if ( isset( $hp['height'] ) ) {
804  $hp15['height'] = round( $hp['height'] * 1.5 );
805  $hp20['height'] = $hp['height'] * 2;
806  }
807 
808  $thumb15 = $file->transform( $hp15 );
809  $thumb20 = $file->transform( $hp20 );
810  if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
811  $thumb->responsiveUrls['1.5'] = $thumb15->getUrl();
812  }
813  if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
814  $thumb->responsiveUrls['2'] = $thumb20->getUrl();
815  }
816  }
817  }
818 
832  public static function makeBrokenImageLinkObj(
833  $title, $label = '', $query = '', $unused1 = '', $unused2 = '',
834  $time = false, array $handlerParams = []
835  ) {
836  if ( !$title instanceof LinkTarget ) {
837  wfWarn( __METHOD__ . ': Requires $title to be a LinkTarget object.' );
838  return "<!-- ERROR -->" . htmlspecialchars( $label );
839  }
840 
842 
844  if ( $label == '' ) {
845  $label = $title->getPrefixedText();
846  }
847 
848  $html = Html::element( 'span', [
849  // These data attributes are used to dynamically size the span, see T273013
850  'data-width' => $handlerParams['width'] ?? null,
851  'data-height' => $handlerParams['height'] ?? null,
852  ], $label );
853 
854  $services = MediaWikiServices::getInstance();
855  if ( $services->getMainConfig()->get( 'ParserEnableLegacyMediaDOM' ) ) {
856  $html = htmlspecialchars( $label );
857  }
858 
859  $repoGroup = $services->getRepoGroup();
860  $currentExists = $time
861  && $repoGroup->findFile( $title ) !== false;
862 
864  && !$currentExists
865  ) {
866  if ( $repoGroup->getLocalRepo()->checkRedirect( $title ) ) {
867  // We already know it's a redirect, so mark it accordingly
868  return self::link(
869  $title,
870  $html,
871  [ 'class' => 'mw-redirect' ],
872  wfCgiToArray( $query ),
873  [ 'known', 'noclasses' ]
874  );
875  }
876  return Html::rawElement( 'a', [
877  'href' => self::getUploadUrl( $title, $query ),
878  'class' => 'new',
879  'title' => $title->getPrefixedText()
880  ], $html );
881  }
882  return self::link(
883  $title,
884  $html,
885  [],
886  wfCgiToArray( $query ),
887  [ 'known', 'noclasses' ]
888  );
889  }
890 
899  protected static function getUploadUrl( $destFile, $query = '' ) {
901  $q = 'wpDestFile=' . Title::castFromLinkTarget( $destFile )->getPartialURL();
902  if ( $query != '' ) {
903  $q .= '&' . $query;
904  }
905 
906  if ( $wgUploadMissingFileUrl ) {
908  }
909 
910  if ( $wgUploadNavigationUrl ) {
912  }
913 
914  $upload = SpecialPage::getTitleFor( 'Upload' );
915 
916  return $upload->getLocalURL( $q );
917  }
918 
928  public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
929  $img = MediaWikiServices::getInstance()->getRepoGroup()->findFile(
930  $title, [ 'time' => $time ]
931  );
932  return self::makeMediaLinkFile( $title, $img, $html );
933  }
934 
947  public static function makeMediaLinkFile( LinkTarget $title, $file, $html = '' ) {
948  if ( $file && $file->exists() ) {
949  $url = $file->getUrl();
950  $class = 'internal';
951  } else {
952  $url = self::getUploadUrl( $title );
953  $class = 'new';
954  }
955 
956  $alt = $title->getText();
957  if ( $html == '' ) {
958  $html = $alt;
959  }
960 
961  $ret = '';
962  $attribs = [
963  'href' => $url,
964  'class' => $class,
965  'title' => $alt
966  ];
967 
968  if ( !Hooks::runner()->onLinkerMakeMediaLinkFile(
969  Title::castFromLinkTarget( $title ), $file, $html, $attribs, $ret )
970  ) {
971  wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
972  . "with url {$url} and text {$html} to {$ret}" );
973  return $ret;
974  }
975 
976  return Html::rawElement( 'a', $attribs, $html );
977  }
978 
989  public static function specialLink( $name, $key = '' ) {
990  if ( $key == '' ) {
991  $key = strtolower( $name );
992  }
993 
994  return self::linkKnown( SpecialPage::getTitleFor( $name ), wfMessage( $key )->escaped() );
995  }
996 
1015  public static function makeExternalLink( $url, $text, $escape = true,
1016  $linktype = '', $attribs = [], $title = null
1017  ) {
1018  global $wgTitle;
1019  $class = "external";
1020  if ( $linktype ) {
1021  $class .= " $linktype";
1022  }
1023  if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1024  $class .= " {$attribs['class']}";
1025  }
1026  $attribs['class'] = $class;
1027 
1028  if ( $escape ) {
1029  $text = htmlspecialchars( $text );
1030  }
1031 
1032  if ( !$title ) {
1033  $title = $wgTitle;
1034  }
1035  $newRel = Parser::getExternalLinkRel( $url, $title );
1036  if ( !isset( $attribs['rel'] ) || $attribs['rel'] === '' ) {
1037  $attribs['rel'] = $newRel;
1038  } elseif ( $newRel !== '' ) {
1039  // Merge the rel attributes.
1040  $newRels = explode( ' ', $newRel );
1041  $oldRels = explode( ' ', $attribs['rel'] );
1042  $combined = array_unique( array_merge( $newRels, $oldRels ) );
1043  $attribs['rel'] = implode( ' ', $combined );
1044  }
1045  $link = '';
1046  $success = Hooks::runner()->onLinkerMakeExternalLink(
1047  $url, $text, $link, $attribs, $linktype );
1048  if ( !$success ) {
1049  wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
1050  . "with url {$url} and text {$text} to {$link}" );
1051  return $link;
1052  }
1053  $attribs['href'] = $url;
1054  return Html::rawElement( 'a', $attribs, $text );
1055  }
1056 
1068  public static function userLink( $userId, $userName, $altUserName = false ) {
1069  if ( $userName === '' || $userName === false || $userName === null ) {
1070  wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1071  'that need to be fixed?' );
1072  return wfMessage( 'empty-username' )->parse();
1073  }
1074 
1075  $classes = 'mw-userlink';
1076  $page = null;
1077  if ( $userId == 0 ) {
1078  $page = ExternalUserNames::getUserLinkTitle( $userName );
1079 
1080  if ( ExternalUserNames::isExternal( $userName ) ) {
1081  $classes .= ' mw-extuserlink';
1082  } elseif ( $altUserName === false ) {
1083  $altUserName = IPUtils::prettifyIP( $userName );
1084  }
1085  $classes .= ' mw-anonuserlink'; // Separate link class for anons (T45179)
1086  } else {
1087  $page = TitleValue::tryNew( NS_USER, strtr( $userName, ' ', '_' ) );
1088  }
1089 
1090  // Wrap the output with <bdi> tags for directionality isolation
1091  $linkText =
1092  '<bdi>' . htmlspecialchars( $altUserName !== false ? $altUserName : $userName ) . '</bdi>';
1093 
1094  return $page
1095  ? self::link( $page, $linkText, [ 'class' => $classes ] )
1096  : Html::rawElement( 'span', [ 'class' => $classes ], $linkText );
1097  }
1098 
1113  public static function userToolLinks(
1114  $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null,
1115  $useParentheses = true
1116  ) {
1117  if ( $userText === '' ) {
1118  wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1119  'that need to be fixed?' );
1120  return ' ' . wfMessage( 'empty-username' )->parse();
1121  }
1122 
1123  global $wgDisableAnonTalk, $wgLang;
1124  $talkable = !( $wgDisableAnonTalk && $userId == 0 );
1125  $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1126  $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1127 
1128  if ( $userId == 0 && ExternalUserNames::isExternal( $userText ) ) {
1129  // No tools for an external user
1130  return '';
1131  }
1132 
1133  $items = [];
1134  if ( $talkable ) {
1135  $items[] = self::userTalkLink( $userId, $userText );
1136  }
1137  if ( $userId ) {
1138  // check if the user has an edit
1139  $attribs = [];
1140  $attribs['class'] = 'mw-usertoollinks-contribs';
1141  if ( $redContribsWhenNoEdits ) {
1142  if ( intval( $edits ) === 0 && $edits !== 0 ) {
1143  $user = User::newFromId( $userId );
1144  $edits = $user->getEditCount();
1145  }
1146  if ( $edits === 0 ) {
1147  $attribs['class'] .= ' new';
1148  }
1149  }
1150  $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1151 
1152  $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1153  }
1154  $userCanBlock = RequestContext::getMain()->getAuthority()->isAllowed( 'block' );
1155  if ( $blockable && $userCanBlock ) {
1156  $items[] = self::blockLink( $userId, $userText );
1157  }
1158 
1159  $user = RequestContext::getMain()->getUser();
1160  if ( $addEmailLink && $user->canSendEmail() ) {
1161  $items[] = self::emailLink( $userId, $userText );
1162  }
1163 
1164  Hooks::runner()->onUserToolLinksEdit( $userId, $userText, $items );
1165 
1166  if ( !$items ) {
1167  return '';
1168  }
1169 
1170  if ( $useParentheses ) {
1171  return wfMessage( 'word-separator' )->escaped()
1172  . '<span class="mw-usertoollinks">'
1173  . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1174  . '</span>';
1175  }
1176 
1177  $tools = [];
1178  foreach ( $items as $tool ) {
1179  $tools[] = Html::rawElement( 'span', [], $tool );
1180  }
1181  return ' <span class="mw-usertoollinks mw-changeslist-links">' .
1182  implode( ' ', $tools ) . '</span>';
1183  }
1184 
1194  public static function userToolLinksRedContribs(
1195  $userId, $userText, $edits = null, $useParentheses = true
1196  ) {
1197  return self::userToolLinks( $userId, $userText, true, 0, $edits, $useParentheses );
1198  }
1199 
1206  public static function userTalkLink( $userId, $userText ) {
1207  if ( $userText === '' ) {
1208  wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1209  'that need to be fixed?' );
1210  return wfMessage( 'empty-username' )->parse();
1211  }
1212 
1213  $userTalkPage = TitleValue::tryNew( NS_USER_TALK, strtr( $userText, ' ', '_' ) );
1214  $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-talk' ];
1215  $linkText = wfMessage( 'talkpagelinktext' )->escaped();
1216 
1217  return $userTalkPage
1218  ? self::link( $userTalkPage, $linkText, $moreLinkAttribs )
1219  : Html::rawElement( 'span', $moreLinkAttribs, $linkText );
1220  }
1221 
1228  public static function blockLink( $userId, $userText ) {
1229  if ( $userText === '' ) {
1230  wfDebug( __METHOD__ . ' received an empty username. Are there database errors ' .
1231  'that need to be fixed?' );
1232  return wfMessage( 'empty-username' )->parse();
1233  }
1234 
1235  $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1236  $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-block' ];
1237 
1238  return self::link( $blockPage,
1239  wfMessage( 'blocklink' )->escaped(),
1240  $moreLinkAttribs
1241  );
1242  }
1243 
1249  public static function emailLink( $userId, $userText ) {
1250  if ( $userText === '' ) {
1251  wfLogWarning( __METHOD__ . ' received an empty username. Are there database errors ' .
1252  'that need to be fixed?' );
1253  return wfMessage( 'empty-username' )->parse();
1254  }
1255 
1256  $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1257  $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-mail' ];
1258  return self::link( $emailPage,
1259  wfMessage( 'emaillink' )->escaped(),
1260  $moreLinkAttribs
1261  );
1262  }
1263 
1275  public static function revUserLink( RevisionRecord $revRecord, $isPublic = false ) {
1276  // TODO inject authority
1277  $authority = RequestContext::getMain()->getAuthority();
1278 
1279  if ( $revRecord->isDeleted( RevisionRecord::DELETED_USER ) && $isPublic ) {
1280  $link = wfMessage( 'rev-deleted-user' )->escaped();
1281  } elseif ( $revRecord->userCan( RevisionRecord::DELETED_USER, $authority ) ) {
1282  $revUser = $revRecord->getUser( RevisionRecord::FOR_THIS_USER, $authority );
1283  $link = self::userLink(
1284  $revUser ? $revUser->getId() : 0,
1285  $revUser ? $revUser->getName() : ''
1286  );
1287  } else {
1288  $link = wfMessage( 'rev-deleted-user' )->escaped();
1289  }
1290  if ( $revRecord->isDeleted( RevisionRecord::DELETED_USER ) ) {
1291  $class = self::getRevisionDeletedClass( $revRecord );
1292  return '<span class="' . $class . '">' . $link . '</span>';
1293  }
1294  return $link;
1295  }
1296 
1303  public static function getRevisionDeletedClass( RevisionRecord $revisionRecord ): string {
1304  $class = 'history-deleted';
1305  if ( $revisionRecord->isDeleted( RevisionRecord::DELETED_RESTRICTED ) ) {
1306  $class .= ' mw-history-suppressed';
1307  }
1308  return $class;
1309  }
1310 
1323  public static function revUserTools(
1324  RevisionRecord $revRecord,
1325  $isPublic = false,
1326  $useParentheses = true
1327  ) {
1328  // TODO inject authority
1329  $authority = RequestContext::getMain()->getAuthority();
1330 
1331  if ( $revRecord->userCan( RevisionRecord::DELETED_USER, $authority ) &&
1332  ( !$revRecord->isDeleted( RevisionRecord::DELETED_USER ) || !$isPublic )
1333  ) {
1334  $revUser = $revRecord->getUser( RevisionRecord::FOR_THIS_USER, $authority );
1335  $userId = $revUser ? $revUser->getId() : 0;
1336  $userText = $revUser ? $revUser->getName() : '';
1337 
1338  if ( $userId || $userText !== '' ) {
1339  $link = self::userLink( $userId, $userText )
1340  . self::userToolLinks( $userId, $userText, false, 0, null,
1341  $useParentheses );
1342  }
1343  }
1344 
1345  if ( !isset( $link ) ) {
1346  $link = wfMessage( 'rev-deleted-user' )->escaped();
1347  }
1348 
1349  if ( $revRecord->isDeleted( RevisionRecord::DELETED_USER ) ) {
1350  $class = self::getRevisionDeletedClass( $revRecord );
1351  return ' <span class="' . $class . ' mw-userlink">' . $link . '</span>';
1352  }
1353  return $link;
1354  }
1355 
1376  public static function formatComment(
1377  $comment, $title = null, $local = false, $wikiId = null
1378  ) {
1379  # Sanitize text a bit:
1380  $comment = str_replace( "\n", " ", $comment );
1381  # Allow HTML entities (for T15815)
1382  $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1383 
1384  # Render autocomments and make links:
1385  $comment = self::formatAutocomments( $comment, $title, $local, $wikiId );
1386  return self::formatLinksInComment( $comment, $title, $local, $wikiId );
1387  }
1388 
1406  private static function formatAutocomments(
1407  $comment, $title = null, $local = false, $wikiId = null
1408  ) {
1409  // @todo $append here is something of a hack to preserve the status
1410  // quo. Someone who knows more about bidi and such should decide
1411  // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1412  // wiki, both when autocomments exist and when they don't, and
1413  // (2) what markup will make that actually happen.
1414  $append = '';
1415  $comment = preg_replace_callback(
1416  // To detect the presence of content before or after the
1417  // auto-comment, we use capturing groups inside optional zero-width
1418  // assertions. But older versions of PCRE can't directly make
1419  // zero-width assertions optional, so wrap them in a non-capturing
1420  // group.
1421  '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1422  static function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1423  global $wgLang;
1424 
1425  // Ensure all match positions are defined
1426  $match += [ '', '', '', '' ];
1427 
1428  $pre = $match[1] !== '';
1429  $auto = $match[2];
1430  $post = $match[3] !== '';
1431  $comment = null;
1432 
1433  Hooks::runner()->onFormatAutocomments(
1434  $comment, $pre, $auto, $post, Title::castFromLinkTarget( $title ), $local,
1435  $wikiId );
1436 
1437  if ( $comment === null ) {
1438  if ( $title ) {
1439  $section = $auto;
1440  # Remove links that a user may have manually put in the autosummary
1441  # This could be improved by copying as much of Parser::stripSectionName as desired.
1442  $section = str_replace( [
1443  '[[:',
1444  '[[',
1445  ']]'
1446  ], '', $section );
1447 
1448  // We don't want any links in the auto text to be linked, but we still
1449  // want to show any [[ ]]
1450  $sectionText = str_replace( '[[', '&#91;[', $auto );
1451 
1452  $section = substr( Parser::guessSectionNameFromStrippedText( $section ), 1 );
1453  if ( $section !== '' ) {
1454  if ( $local ) {
1455  $sectionTitle = new TitleValue( NS_MAIN, '', $section );
1456  } else {
1457  $sectionTitle = $title->createFragmentTarget( $section );
1458  }
1459  $auto = Linker::makeCommentLink(
1460  $sectionTitle,
1461  $wgLang->getArrow() . $wgLang->getDirMark() . $sectionText,
1462  $wikiId,
1463  'noclasses'
1464  );
1465  }
1466  }
1467  if ( $pre ) {
1468  # written summary $presep autocomment (summary /* section */)
1469  $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1470  }
1471  if ( $post ) {
1472  # autocomment $postsep written summary (/* section */ summary)
1473  $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1474  }
1475  if ( $auto ) {
1476  $auto = '<span dir="auto"><span class="autocomment">' . $auto . '</span>';
1477  $append .= '</span>';
1478  }
1479  $comment = $pre . $auto;
1480  }
1481  return $comment;
1482  },
1483  $comment
1484  );
1485  return $comment . $append;
1486  }
1487 
1507  public static function formatLinksInComment(
1508  $comment, $title = null, $local = false, $wikiId = null
1509  ) {
1510  return preg_replace_callback(
1511  '/
1512  \[\[
1513  \s*+ # ignore leading whitespace, the *+ quantifier disallows backtracking
1514  :? # ignore optional leading colon
1515  ([^[\]|]+) # 1. link target; page names cannot include [, ] or |
1516  (?:\|
1517  # 2. link text
1518  # Stop matching at ]] without relying on backtracking.
1519  ((?:]?[^\]])*+)
1520  )?
1521  \]\]
1522  ([^[]*) # 3. link trail (the text up until the next link)
1523  /x',
1524  static function ( $match ) use ( $title, $local, $wikiId ) {
1525  $services = MediaWikiServices::getInstance();
1526 
1527  $medians = '(?:';
1528  $medians .= preg_quote(
1529  $services->getNamespaceInfo()->getCanonicalName( NS_MEDIA ), '/' );
1530  $medians .= '|';
1531  $medians .= preg_quote(
1532  $services->getContentLanguage()->getNsText( NS_MEDIA ),
1533  '/'
1534  ) . '):';
1535 
1536  $comment = $match[0];
1537 
1538  # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1539  if ( strpos( $match[1], '%' ) !== false ) {
1540  $match[1] = strtr(
1541  rawurldecode( $match[1] ),
1542  [ '<' => '&lt;', '>' => '&gt;' ]
1543  );
1544  }
1545 
1546  # Handle link renaming [[foo|text]] will show link as "text"
1547  if ( $match[2] != "" ) {
1548  $text = $match[2];
1549  } else {
1550  $text = $match[1];
1551  }
1552  $submatch = [];
1553  $thelink = null;
1554  if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1555  # Media link; trail not supported.
1556  $linkRegexp = '/\[\[(.*?)\]\]/';
1557  $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1558  if ( $title ) {
1559  $thelink = Linker::makeMediaLinkObj( $title, $text );
1560  }
1561  } else {
1562  # Other kind of link
1563  # Make sure its target is non-empty
1564  if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1565  $match[1] = substr( $match[1], 1 );
1566  }
1567  if ( $match[1] !== false && $match[1] !== '' ) {
1568  if ( preg_match(
1569  $services->getContentLanguage()->linkTrail(),
1570  $match[3],
1571  $submatch
1572  ) ) {
1573  $trail = $submatch[1];
1574  } else {
1575  $trail = "";
1576  }
1577  $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1578  list( $inside, $trail ) = Linker::splitTrail( $trail );
1579 
1580  $linkText = $text;
1581  $linkTarget = Linker::normalizeSubpageLink( $title, $match[1], $linkText );
1582 
1583  try {
1584  $target = $services->getTitleParser()->
1585  parseTitle( $linkTarget );
1586 
1587  if ( $target->getText() == '' && !$target->isExternal()
1588  && !$local && $title
1589  ) {
1590  $target = $title->createFragmentTarget( $target->getFragment() );
1591  }
1592 
1593  $thelink = Linker::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1594  } catch ( MalformedTitleException $e ) {
1595  // Fall through
1596  }
1597  }
1598  }
1599  if ( $thelink ) {
1600  // If the link is still valid, go ahead and replace it in!
1601  $comment = preg_replace(
1602  $linkRegexp,
1604  $comment,
1605  1
1606  );
1607  }
1608 
1609  return $comment;
1610  },
1611  $comment
1612  );
1613  }
1614 
1628  public static function makeCommentLink(
1629  LinkTarget $linkTarget, $text, $wikiId = null, $options = []
1630  ) {
1631  if ( $wikiId !== null && !$linkTarget->isExternal() ) {
1632  $link = self::makeExternalLink(
1634  $wikiId,
1635  $linkTarget->getNamespace() === 0
1636  ? $linkTarget->getDBkey()
1637  : MediaWikiServices::getInstance()->getNamespaceInfo()->
1638  getCanonicalName( $linkTarget->getNamespace() ) .
1639  ':' . $linkTarget->getDBkey(),
1640  $linkTarget->getFragment()
1641  ),
1642  $text,
1643  /* escape = */ false // Already escaped
1644  );
1645  } else {
1646  $link = self::link( $linkTarget, $text, [], [], $options );
1647  }
1648 
1649  return $link;
1650  }
1651 
1658  public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1659  # Valid link forms:
1660  # Foobar -- normal
1661  # :Foobar -- override special treatment of prefix (images, language links)
1662  # /Foobar -- convert to CurrentPage/Foobar
1663  # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1664  # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1665  # ../Foobar -- convert to CurrentPage/Foobar,
1666  # (from CurrentPage/CurrentSubPage)
1667  # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1668  # (from CurrentPage/CurrentSubPage)
1669 
1670  $ret = $target; # default return value is no change
1671 
1672  # Some namespaces don't allow subpages,
1673  # so only perform processing if subpages are allowed
1674  if (
1675  $contextTitle && MediaWikiServices::getInstance()->getNamespaceInfo()->
1676  hasSubpages( $contextTitle->getNamespace() )
1677  ) {
1678  $hash = strpos( $target, '#' );
1679  if ( $hash !== false ) {
1680  $suffix = substr( $target, $hash );
1681  $target = substr( $target, 0, $hash );
1682  } else {
1683  $suffix = '';
1684  }
1685  # T9425
1686  $target = trim( $target );
1687  $contextPrefixedText = MediaWikiServices::getInstance()->getTitleFormatter()->
1688  getPrefixedText( $contextTitle );
1689  # Look at the first character
1690  if ( $target != '' && $target[0] === '/' ) {
1691  # / at end means we don't want the slash to be shown
1692  $m = [];
1693  $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1694  if ( $trailingSlashes ) {
1695  $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1696  } else {
1697  $noslash = substr( $target, 1 );
1698  }
1699 
1700  $ret = $contextPrefixedText . '/' . trim( $noslash ) . $suffix;
1701  if ( $text === '' ) {
1702  $text = $target . $suffix;
1703  } # this might be changed for ugliness reasons
1704  } else {
1705  # check for .. subpage backlinks
1706  $dotdotcount = 0;
1707  $nodotdot = $target;
1708  while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1709  ++$dotdotcount;
1710  $nodotdot = substr( $nodotdot, 3 );
1711  }
1712  if ( $dotdotcount > 0 ) {
1713  $exploded = explode( '/', $contextPrefixedText );
1714  if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1715  $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1716  # / at the end means don't show full path
1717  if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1718  $nodotdot = rtrim( $nodotdot, '/' );
1719  if ( $text === '' ) {
1720  $text = $nodotdot . $suffix;
1721  }
1722  }
1723  $nodotdot = trim( $nodotdot );
1724  if ( $nodotdot != '' ) {
1725  $ret .= '/' . $nodotdot;
1726  }
1727  $ret .= $suffix;
1728  }
1729  }
1730  }
1731  }
1732 
1733  return $ret;
1734  }
1735 
1751  public static function commentBlock(
1752  $comment, $title = null, $local = false, $wikiId = null, $useParentheses = true
1753  ) {
1754  // '*' used to be the comment inserted by the software way back
1755  // in antiquity in case none was provided, here for backwards
1756  // compatibility, acc. to brion -√¶var
1757  if ( $comment == '' || $comment == '*' ) {
1758  return '';
1759  }
1760  $formatted = self::formatComment( $comment, $title, $local, $wikiId );
1761  if ( $useParentheses ) {
1762  $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1763  $classNames = 'comment';
1764  } else {
1765  $classNames = 'comment comment--without-parentheses';
1766  }
1767  return " <span class=\"$classNames\">$formatted</span>";
1768  }
1769 
1784  public static function revComment(
1785  RevisionRecord $revRecord,
1786  $local = false,
1787  $isPublic = false,
1788  $useParentheses = true
1789  ) {
1790  // TODO inject authority
1791  $authority = RequestContext::getMain()->getAuthority();
1792 
1793  if ( $revRecord->getComment( RevisionRecord::RAW ) === null ) {
1794  return "";
1795  }
1796  if ( $revRecord->isDeleted( RevisionRecord::DELETED_COMMENT ) && $isPublic ) {
1797  $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1798  } elseif ( $revRecord->userCan( RevisionRecord::DELETED_COMMENT, $authority ) ) {
1799  $comment = $revRecord->getComment( RevisionRecord::FOR_THIS_USER, $authority );
1800  $block = self::commentBlock(
1801  $comment ? $comment->text : null,
1802  $revRecord->getPageAsLinkTarget(),
1803  $local,
1804  null,
1805  $useParentheses
1806  );
1807  } else {
1808  $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1809  }
1810  if ( $revRecord->isDeleted( RevisionRecord::DELETED_COMMENT ) ) {
1811  $class = self::getRevisionDeletedClass( $revRecord );
1812  return " <span class=\"$class comment\">$block</span>";
1813  }
1814  return $block;
1815  }
1816 
1822  public static function formatRevisionSize( $size ) {
1823  if ( $size == 0 ) {
1824  $stxt = wfMessage( 'historyempty' )->escaped();
1825  } else {
1826  $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1827  }
1828  return "<span class=\"history-size mw-diff-bytes\" data-mw-bytes=\"$size\">$stxt</span>";
1829  }
1830 
1837  public static function tocIndent() {
1838  return "\n<ul>\n";
1839  }
1840 
1848  public static function tocUnindent( $level ) {
1849  return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1850  }
1851 
1863  public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1864  $classes = "toclevel-$level";
1865  if ( $sectionIndex !== false ) {
1866  $classes .= " tocsection-$sectionIndex";
1867  }
1868 
1869  // <li class="$classes"><a href="#$anchor"><span class="tocnumber">
1870  // $tocnumber</span> <span class="toctext">$tocline</span></a>
1871  return Html::openElement( 'li', [ 'class' => $classes ] )
1872  . Html::rawElement( 'a',
1873  [ 'href' => "#$anchor" ],
1874  Html::element( 'span', [ 'class' => 'tocnumber' ], $tocnumber )
1875  . ' '
1876  . Html::rawElement( 'span', [ 'class' => 'toctext' ], $tocline )
1877  );
1878  }
1879 
1887  public static function tocLineEnd() {
1888  return "</li>\n";
1889  }
1890 
1899  public static function tocList( $toc, Language $lang = null ) {
1900  $lang = $lang ?? RequestContext::getMain()->getLanguage();
1901 
1902  $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1903 
1904  return '<div id="toc" class="toc" role="navigation" aria-labelledby="mw-toc-heading">'
1905  . Html::element( 'input', [
1906  'type' => 'checkbox',
1907  'role' => 'button',
1908  'id' => 'toctogglecheckbox',
1909  'class' => 'toctogglecheckbox',
1910  'style' => 'display:none',
1911  ] )
1912  . Html::openElement( 'div', [
1913  'class' => 'toctitle',
1914  'lang' => $lang->getHtmlCode(),
1915  'dir' => $lang->getDir(),
1916  ] )
1917  . '<h2 id="mw-toc-heading">' . $title . '</h2>'
1918  . '<span class="toctogglespan">'
1919  . Html::label( '', 'toctogglecheckbox', [
1920  'class' => 'toctogglelabel',
1921  ] )
1922  . '</span>'
1923  . "</div>\n"
1924  . $toc
1925  . "</ul>\n</div>\n";
1926  }
1927 
1936  public static function generateTOC( $tree, Language $lang = null ) {
1937  $toc = '';
1938  $lastLevel = 0;
1939  foreach ( $tree as $section ) {
1940  if ( $section['toclevel'] > $lastLevel ) {
1941  $toc .= self::tocIndent();
1942  } elseif ( $section['toclevel'] < $lastLevel ) {
1943  $toc .= self::tocUnindent(
1944  $lastLevel - $section['toclevel'] );
1945  } else {
1946  $toc .= self::tocLineEnd();
1947  }
1948 
1949  $toc .= self::tocLine( $section['anchor'],
1950  $section['line'], $section['number'],
1951  $section['toclevel'], $section['index'] );
1952  $lastLevel = $section['toclevel'];
1953  }
1954  $toc .= self::tocLineEnd();
1955  return self::tocList( $toc, $lang );
1956  }
1957 
1974  public static function makeHeadline( $level, $attribs, $anchor, $html,
1975  $link, $fallbackAnchor = false
1976  ) {
1977  $anchorEscaped = htmlspecialchars( $anchor );
1978  $fallback = '';
1979  if ( $fallbackAnchor !== false && $fallbackAnchor !== $anchor ) {
1980  $fallbackAnchor = htmlspecialchars( $fallbackAnchor );
1981  $fallback = "<span id=\"$fallbackAnchor\"></span>";
1982  }
1983  return "<h$level$attribs"
1984  . "$fallback<span class=\"mw-headline\" id=\"$anchorEscaped\">$html</span>"
1985  . $link
1986  . "</h$level>";
1987  }
1988 
1995  public static function splitTrail( $trail ) {
1996  $regex = MediaWikiServices::getInstance()->getContentLanguage()->linkTrail();
1997  $inside = '';
1998  if ( $trail !== '' && preg_match( $regex, $trail, $m ) ) {
1999  list( , $inside, $trail ) = $m;
2000  }
2001  return [ $inside, $trail ];
2002  }
2003 
2033  public static function generateRollback(
2034  RevisionRecord $revRecord,
2035  IContextSource $context = null,
2036  $options = [ 'verify' ]
2037  ) {
2038  if ( $context === null ) {
2039  $context = RequestContext::getMain();
2040  }
2041 
2042  $editCount = false;
2043  if ( in_array( 'verify', $options, true ) ) {
2044  $editCount = self::getRollbackEditCount( $revRecord, true );
2045  if ( $editCount === false ) {
2046  return '';
2047  }
2048  }
2049 
2050  $inner = self::buildRollbackLink( $revRecord, $context, $editCount );
2051 
2052  // Allow extensions to modify the rollback link.
2053  // Abort further execution if the extension wants full control over the link.
2054  if ( !Hooks::runner()->onLinkerGenerateRollbackLink(
2055  $revRecord, $context, $options, $inner ) ) {
2056  return $inner;
2057  }
2058 
2059  if ( !in_array( 'noBrackets', $options, true ) ) {
2060  $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
2061  }
2062 
2063  if ( MediaWikiServices::getInstance()->getUserOptionsLookup()
2064  ->getBoolOption( $context->getUser(), 'showrollbackconfirmation' )
2065  ) {
2066  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
2067  $stats->increment( 'rollbackconfirmation.event.load' );
2068  $context->getOutput()->addModules( 'mediawiki.misc-authed-curate' );
2069  }
2070 
2071  return '<span class="mw-rollback-link">' . $inner . '</span>';
2072  }
2073 
2092  public static function getRollbackEditCount( RevisionRecord $revRecord, $verify ) {
2093  global $wgShowRollbackEditCount;
2094 
2095  if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
2096  // Nothing has happened, indicate this by returning 'null'
2097  return null;
2098  }
2099 
2100  $dbr = wfGetDB( DB_REPLICA );
2101 
2102  // Up to the value of $wgShowRollbackEditCount revisions are counted
2103  $revQuery = MediaWikiServices::getInstance()->getRevisionStore()->getQueryInfo();
2104  // T270033 Index renaming
2105  $revIndex = $dbr->indexExists( 'revision', 'page_timestamp', __METHOD__ )
2106  ? 'page_timestamp'
2107  : 'rev_page_timestamp';
2108  $res = $dbr->select(
2109  $revQuery['tables'],
2110  [ 'rev_user_text' => $revQuery['fields']['rev_user_text'], 'rev_deleted' ],
2111  [ 'rev_page' => $revRecord->getPageId() ],
2112  __METHOD__,
2113  [
2114  'USE INDEX' => [ 'revision' => $revIndex ],
2115  'ORDER BY' => 'rev_timestamp DESC',
2116  'LIMIT' => $wgShowRollbackEditCount + 1
2117  ],
2118  $revQuery['joins']
2119  );
2120 
2121  $revUser = $revRecord->getUser( RevisionRecord::RAW );
2122  $revUserText = $revUser ? $revUser->getName() : '';
2123 
2124  $editCount = 0;
2125  $moreRevs = false;
2126  foreach ( $res as $row ) {
2127  if ( $row->rev_user_text != $revUserText ) {
2128  if ( $verify &&
2129  ( $row->rev_deleted & RevisionRecord::DELETED_TEXT
2130  || $row->rev_deleted & RevisionRecord::DELETED_USER
2131  ) ) {
2132  // If the user or the text of the revision we might rollback
2133  // to is deleted in some way we can't rollback. Similar to
2134  // the sanity checks in WikiPage::commitRollback.
2135  return false;
2136  }
2137  $moreRevs = true;
2138  break;
2139  }
2140  $editCount++;
2141  }
2142 
2143  if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
2144  // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
2145  // and there weren't any other revisions. That means that the current user is the only
2146  // editor, so we can't rollback
2147  return false;
2148  }
2149  return $editCount;
2150  }
2151 
2166  public static function buildRollbackLink(
2167  RevisionRecord $revRecord,
2168  IContextSource $context = null,
2169  $editCount = false
2170  ) {
2172 
2173  // To config which pages are affected by miser mode
2174  $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
2175 
2176  if ( $context === null ) {
2177  $context = RequestContext::getMain();
2178  }
2179 
2180  $title = $revRecord->getPageAsLinkTarget();
2181  $revUser = $revRecord->getUser();
2182  $revUserText = $revUser ? $revUser->getName() : '';
2183 
2184  $query = [
2185  'action' => 'rollback',
2186  'from' => $revUserText,
2187  'token' => $context->getCsrfTokenSet()->getToken( 'rollback' )->toString(),
2188  ];
2189 
2190  $attrs = [
2191  'data-mw' => 'interface',
2192  'title' => $context->msg( 'tooltip-rollback' )->text()
2193  ];
2194 
2195  $options = [ 'known', 'noclasses' ];
2196 
2197  if ( $context->getRequest()->getBool( 'bot' ) ) {
2198  // T17999
2199  $query['hidediff'] = '1';
2200  $query['bot'] = '1';
2201  }
2202 
2203  $disableRollbackEditCount = false;
2204  if ( $wgMiserMode ) {
2205  foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
2206  if ( $context->getTitle()->isSpecial( $specialPage ) ) {
2207  $disableRollbackEditCount = true;
2208  break;
2209  }
2210  }
2211  }
2212 
2213  if ( !$disableRollbackEditCount
2214  && is_int( $wgShowRollbackEditCount )
2216  ) {
2217  if ( !is_numeric( $editCount ) ) {
2218  $editCount = self::getRollbackEditCount( $revRecord, false );
2219  }
2220 
2221  if ( $editCount > $wgShowRollbackEditCount ) {
2222  $html = $context->msg( 'rollbacklinkcount-morethan' )
2223  ->numParams( $wgShowRollbackEditCount )->parse();
2224  } else {
2225  $html = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
2226  }
2227 
2228  return self::link( $title, $html, $attrs, $query, $options );
2229  }
2230 
2231  $html = $context->msg( 'rollbacklink' )->escaped();
2232  return self::link( $title, $html, $attrs, $query, $options );
2233  }
2234 
2243  public static function formatHiddenCategories( $hiddencats ) {
2244  $outText = '';
2245  if ( count( $hiddencats ) > 0 ) {
2246  # Construct the HTML
2247  $outText = '<div class="mw-hiddenCategoriesExplanation">';
2248  $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
2249  $outText .= "</div><ul>\n";
2250 
2251  foreach ( $hiddencats as $titleObj ) {
2252  # If it's hidden, it must exist - no need to check with a LinkBatch
2253  $outText .= '<li>'
2254  . self::link( $titleObj, null, [], [], 'known' )
2255  . "</li>\n";
2256  }
2257  $outText .= '</ul>';
2258  }
2259  return $outText;
2260  }
2261 
2278  public static function titleAttrib( $name, $options = null, array $msgParams = [] ) {
2279  $message = wfMessage( "tooltip-$name", $msgParams );
2280  if ( !$message->exists() ) {
2281  $tooltip = false;
2282  } else {
2283  $tooltip = $message->text();
2284  # Compatibility: formerly some tooltips had [alt-.] hardcoded
2285  $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2286  # Message equal to '-' means suppress it.
2287  if ( $tooltip == '-' ) {
2288  $tooltip = false;
2289  }
2290  }
2291 
2292  $options = (array)$options;
2293 
2294  if ( in_array( 'nonexisting', $options ) ) {
2295  $tooltip = wfMessage( 'red-link-title', $tooltip ?: '' )->text();
2296  }
2297  if ( in_array( 'withaccess', $options ) ) {
2298  $accesskey = self::accesskey( $name );
2299  if ( $accesskey !== false ) {
2300  // Should be build the same as in jquery.accessKeyLabel.js
2301  if ( $tooltip === false || $tooltip === '' ) {
2302  $tooltip = wfMessage( 'brackets', $accesskey )->text();
2303  } else {
2304  $tooltip .= wfMessage( 'word-separator' )->text();
2305  $tooltip .= wfMessage( 'brackets', $accesskey )->text();
2306  }
2307  }
2308  }
2309 
2310  return $tooltip;
2311  }
2312 
2313  public static $accesskeycache;
2314 
2326  public static function accesskey( $name ) {
2327  if ( isset( self::$accesskeycache[$name] ) ) {
2328  return self::$accesskeycache[$name];
2329  }
2330 
2331  $message = wfMessage( "accesskey-$name" );
2332 
2333  if ( !$message->exists() ) {
2334  $accesskey = false;
2335  } else {
2336  $accesskey = $message->plain();
2337  if ( $accesskey === '' || $accesskey === '-' ) {
2338  # Per standard MW behavior, a value of '-' means to suppress the
2339  # attribute. It is thus forbidden to use this as an access key.
2340  $accesskey = false;
2341  }
2342  }
2343 
2344  self::$accesskeycache[$name] = $accesskey;
2345  return self::$accesskeycache[$name];
2346  }
2347 
2362  public static function getRevDeleteLink(
2363  Authority $performer,
2364  RevisionRecord $revRecord,
2366  ) {
2367  $canHide = $performer->isAllowed( 'deleterevision' );
2368  $canHideHistory = $performer->isAllowed( 'deletedhistory' );
2369  if ( !$canHide && !( $revRecord->getVisibility() && $canHideHistory ) ) {
2370  return '';
2371  }
2372 
2373  if ( !$revRecord->userCan( RevisionRecord::DELETED_RESTRICTED, $performer ) ) {
2374  return self::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2375  }
2376  $prefixedDbKey = MediaWikiServices::getInstance()->getTitleFormatter()->
2377  getPrefixedDBkey( $title );
2378  if ( $revRecord->getId() ) {
2379  // RevDelete links using revision ID are stable across
2380  // page deletion and undeletion; use when possible.
2381  $query = [
2382  'type' => 'revision',
2383  'target' => $prefixedDbKey,
2384  'ids' => $revRecord->getId()
2385  ];
2386  } else {
2387  // Older deleted entries didn't save a revision ID.
2388  // We have to refer to these by timestamp, ick!
2389  $query = [
2390  'type' => 'archive',
2391  'target' => $prefixedDbKey,
2392  'ids' => $revRecord->getTimestamp()
2393  ];
2394  }
2395  return self::revDeleteLink(
2396  $query,
2397  $revRecord->isDeleted( RevisionRecord::DELETED_RESTRICTED ),
2398  $canHide
2399  );
2400  }
2401 
2414  public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2415  $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2416  $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2417  $html = wfMessage( $msgKey )->escaped();
2418  $tag = $restricted ? 'strong' : 'span';
2419  $link = self::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2420  return Xml::tags(
2421  $tag,
2422  [ 'class' => 'mw-revdelundel-link' ],
2423  wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2424  );
2425  }
2426 
2438  public static function revDeleteLinkDisabled( $delete = true ) {
2439  $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2440  $html = wfMessage( $msgKey )->escaped();
2441  $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2442  return Xml::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2443  }
2444 
2457  public static function tooltipAndAccesskeyAttribs(
2458  $name,
2459  array $msgParams = [],
2460  $options = null
2461  ) {
2462  $options = (array)$options;
2463  $options[] = 'withaccess';
2464  $tooltipTitle = $name;
2465 
2466  // @since 1.35 - add a WatchlistExpiry feature flag to show new watchstar tooltip message
2467  $skin = RequestContext::getMain()->getSkin();
2468  $isWatchlistExpiryEnabled = $skin->getConfig()->get( 'WatchlistExpiry' );
2469  if ( $name === 'ca-unwatch' && $isWatchlistExpiryEnabled ) {
2470  $watchStore = MediaWikiServices::getInstance()->getWatchedItemStore();
2471  $watchedItem = $watchStore->getWatchedItem( $skin->getUser(),
2472  $skin->getRelevantTitle() );
2473  if ( $watchedItem instanceof WatchedItem && $watchedItem->getExpiry() !== null ) {
2474  $diffInDays = $watchedItem->getExpiryInDays();
2475 
2476  if ( $diffInDays ) {
2477  $msgParams = [ $diffInDays ];
2478  // Resolves to tooltip-ca-unwatch-expiring message
2479  $tooltipTitle = 'ca-unwatch-expiring';
2480  } else { // Resolves to tooltip-ca-unwatch-expiring-hours message
2481  $tooltipTitle = 'ca-unwatch-expiring-hours';
2482  }
2483 
2484  }
2485  }
2486 
2487  $attribs = [
2488  'title' => self::titleAttrib( $tooltipTitle, $options, $msgParams ),
2489  'accesskey' => self::accesskey( $name )
2490  ];
2491  if ( $attribs['title'] === false ) {
2492  unset( $attribs['title'] );
2493  }
2494  if ( $attribs['accesskey'] === false ) {
2495  unset( $attribs['accesskey'] );
2496  }
2497  return $attribs;
2498  }
2499 
2507  public static function tooltip( $name, $options = null ) {
2508  $tooltip = self::titleAttrib( $name, $options );
2509  if ( $tooltip === false ) {
2510  return '';
2511  }
2512  return Xml::expandAttributes( [
2513  'title' => $tooltip
2514  ] );
2515  }
2516 
2517 }
Linker\getImageLinkMTOParams
static getImageLinkMTOParams( $frameParams, $query='', $parser=null)
Get the link parameters for MediaTransformOutput::toHtml() from given frame parameters supplied by th...
Definition: Linker.php:531
MediaWiki\Revision\RevisionRecord\getUser
getUser( $audience=self::FOR_PUBLIC, Authority $performer=null)
Fetch revision's author's user identity, if it's available to the specified audience.
Definition: RevisionRecord.php:389
User\newFromId
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:643
Linker\makeThumbLinkObj
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:571
HtmlArmor
Marks HTML that shouldn't be escaped.
Definition: HtmlArmor.php:30
$wgThumbLimits
$wgThumbLimits
Adjust thumbnails on image pages according to a user setting.
Definition: DefaultSettings.php:1638
Linker\formatLinksInComment
static formatLinksInComment( $comment, $title=null, $local=false, $wikiId=null)
Formats wiki links and media links in text; all other wiki formatting is ignored.
Definition: Linker.php:1507
Linker
Some internal bits split of from Skin.php.
Definition: Linker.php:37
MediaWiki\Revision\RevisionRecord
Page revision base class.
Definition: RevisionRecord.php:47
Linker\TOOL_LINKS_NOBLOCK
const TOOL_LINKS_NOBLOCK
Flags for userToolLinks()
Definition: Linker.php:41
Linker\userTalkLink
static userTalkLink( $userId, $userText)
Definition: Linker.php:1206
Xml\expandAttributes
static expandAttributes( $attribs)
Given an array of ('attributename' => 'value'), it generates the code to set the XML attributes : att...
Definition: Xml.php:67
Linker\emailLink
static emailLink( $userId, $userText)
Definition: Linker.php:1249
Linker\generateTOC
static generateTOC( $tree, Language $lang=null)
Generate a table of contents from a section tree.
Definition: Linker.php:1936
$wgResponsiveImages
$wgResponsiveImages
Generate and use thumbnails suitable for screens with 1.5 and 2.0 pixel densities.
Definition: DefaultSettings.php:1756
Linker\makeBrokenImageLinkObj
static makeBrokenImageLinkObj( $title, $label='', $query='', $unused1='', $unused2='', $time=false, array $handlerParams=[])
Make a "broken" link to an image.
Definition: Linker.php:832
Linker\revUserTools
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:1323
Linker\userLink
static userLink( $userId, $userName, $altUserName=false)
Make user link (or user contributions for unregistered users)
Definition: Linker.php:1068
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:186
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
Linker\makeThumbLink2
static makeThumbLink2(LinkTarget $title, $file, $frameParams=[], $handlerParams=[], $time=false, $query="", array $classes=[])
Definition: Linker.php:602
Linker\makeSelfLinkObj
static makeSelfLinkObj( $nt, $html='', $query='', $trail='', $prefix='')
Make appropriate markup for a link to the current article.
Definition: Linker.php:165
Linker\getUploadUrl
static getUploadUrl( $destFile, $query='')
Get the URL to upload a certain file.
Definition: Linker.php:899
Linker\tocIndent
static tocIndent()
Add another level to the Table of Contents.
Definition: Linker.php:1837
$fallback
$fallback
Definition: MessagesAb.php:11
$wgSVGMaxSize
$wgSVGMaxSize
Don't scale a SVG larger than this.
Definition: DefaultSettings.php:1370
Linker\userToolLinks
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:1113
WikiMap\getForeignURL
static getForeignURL( $wikiID, $page, $fragmentId=null)
Convenience to get a url to a page on a foreign wiki.
Definition: WikiMap.php:171
Linker\fnamePart
static fnamePart( $url)
Returns the filename part of an url.
Definition: Linker.php:224
MediaWiki\Revision\RevisionRecord\getPageId
getPageId( $wikiId=self::LOCAL)
Get the page ID.
Definition: RevisionRecord.php:335
Linker\specialLink
static specialLink( $name, $key='')
Make a link to a special page given its name and, optionally, a message key from the link text.
Definition: Linker.php:989
StringUtils\escapeRegexReplacement
static escapeRegexReplacement( $string)
Escape a string to make it suitable for inclusion in a preg_replace() replacement parameter.
Definition: StringUtils.php:314
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
Parser\getTargetLanguage
getTargetLanguage()
Get the target language for the content being parsed.
Definition: Parser.php:1145
Linker\linkKnown
static linkKnown( $target, $html=null, $customAttribs=[], $query=[], $options=[ 'known'])
Identical to link(), except $options defaults to 'known'.
Definition: Linker.php:143
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1182
SpecialPage\getTitleFor
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
Definition: SpecialPage.php:107
Linker\processResponsiveImages
static processResponsiveImages( $file, $thumb, $hp)
Process responsive images: add 1.5x and 2x subimages to the thumbnail, where applicable.
Definition: Linker.php:796
Linker\revUserLink
static revUserLink(RevisionRecord $revRecord, $isPublic=false)
Generate a user link if the current user is allowed to view it.
Definition: Linker.php:1275
wfLogWarning
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
Definition: GlobalFunctions.php:1056
$success
$success
Definition: NoLocalSettings.php:42
Linker\getInvalidTitleDescription
static getInvalidTitleDescription(IContextSource $context, $namespace, $title)
Get a message saying that an invalid title was encountered.
Definition: Linker.php:189
Parser\getExternalLinkRel
static getExternalLinkRel( $url=false, LinkTarget $title=null)
Get the rel attribute for a particular external link.
Definition: Parser.php:2220
MediaWiki\Linker\LinkTarget\isExternal
isExternal()
Whether this LinkTarget has an interwiki component.
$res
$res
Definition: testCompression.php:57
$revQuery
$revQuery
Definition: testCompression.php:56
Linker\tocLine
static tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex=false)
parameter level defines if we are on an indentation level
Definition: Linker.php:1863
$wgLang
$wgLang
Definition: Setup.php:807
Linker\tocList
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:1899
Linker\formatHiddenCategories
static formatHiddenCategories( $hiddencats)
Returns HTML for the "hidden categories on this page" list.
Definition: Linker.php:2243
Linker\tooltipAndAccesskeyAttribs
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[], $options=null)
Returns the attributes for the tooltip and access key.
Definition: Linker.php:2457
NS_MAIN
const NS_MAIN
Definition: Defines.php:64
$dbr
$dbr
Definition: testCompression.php:54
wfAppendQuery
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
Definition: GlobalFunctions.php:422
WatchedItem\getExpiry
getExpiry(?int $style=TS_MW)
When the watched item will expire.
Definition: WatchedItem.php:150
Linker\$accesskeycache
static $accesskeycache
Definition: Linker.php:2313
MediaWiki\Linker\LinkTarget\getNamespace
getNamespace()
Get the namespace index.
Linker\makeMediaLinkObj
static makeMediaLinkObj( $title, $html='', $time=false)
Create a direct link to a given uploaded file.
Definition: Linker.php:928
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:996
MessageLocalizer\msg
msg( $key,... $params)
This is the method for getting translated interface messages.
Linker\buildRollbackLink
static buildRollbackLink(RevisionRecord $revRecord, IContextSource $context=null, $editCount=false)
Build a raw rollback link, useful for collections of "tool" links.
Definition: Linker.php:2166
TitleValue\tryNew
static tryNew( $namespace, $title, $fragment='', $interwiki='')
Constructs a TitleValue, or returns null if the parameters are not valid.
Definition: TitleValue.php:94
Linker\getRevisionDeletedClass
static getRevisionDeletedClass(RevisionRecord $revisionRecord)
Returns css class of a deleted revision.
Definition: Linker.php:1303
Linker\formatAutocomments
static formatAutocomments( $comment, $title=null, $local=false, $wikiId=null)
Converts autogenerated comments in edit summaries into section links.
Definition: Linker.php:1406
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2226
Linker\getRollbackEditCount
static getRollbackEditCount(RevisionRecord $revRecord, $verify)
This function will return the number of revisions which a rollback would revert and,...
Definition: Linker.php:2092
Linker\makeHeadline
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
Definition: Linker.php:1974
Linker\tocLineEnd
static tocLineEnd()
End a Table Of Contents line.
Definition: Linker.php:1887
wfCgiToArray
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
Definition: GlobalFunctions.php:375
Linker\revDeleteLinkDisabled
static revDeleteLinkDisabled( $delete=true)
Creates a dead (show/hide) link for deleting revisions/log entries.
Definition: Linker.php:2438
$title
$title
Definition: testCompression.php:38
Linker\makeExternalLink
static makeExternalLink( $url, $text, $escape=true, $linktype='', $attribs=[], $title=null)
Make an external link.
Definition: Linker.php:1015
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
MediaWiki\Revision\RevisionRecord\getComment
getComment( $audience=self::FOR_PUBLIC, Authority $performer=null)
Fetch revision comment, if it's available to the specified audience.
Definition: RevisionRecord.php:413
Linker\makeCommentLink
static makeCommentLink(LinkTarget $linkTarget, $text, $wikiId=null, $options=[])
Generates a link to the given LinkTarget.
Definition: Linker.php:1628
Html\label
static label( $label, $id, array $attribs=[])
Convenience function for generating a label for inputs.
Definition: Html.php:789
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:894
$wgTitle
$wgTitle
Definition: Setup.php:825
Linker\splitTrail
static splitTrail( $trail)
Split a link trail, return the "inside" portion and the remainder of the trail as a two-element array...
Definition: Linker.php:1995
Linker\generateRollback
static generateRollback(RevisionRecord $revRecord, IContextSource $context=null, $options=[ 'verify'])
Generate a rollback link for a given revision.
Definition: Linker.php:2033
MediaWiki\Permissions\Authority
This interface represents the authority associated the current execution context, such as a web reque...
Definition: Authority.php:37
$wgShowRollbackEditCount
$wgShowRollbackEditCount
The $wgShowRollbackEditCount variable is used to show how many edits can be rolled back.
Definition: DefaultSettings.php:3983
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:706
Linker\revComment
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:1784
Linker\blockLink
static blockLink( $userId, $userText)
Definition: Linker.php:1228
$s
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s
Definition: mergeMessageFileList.php:206
Linker\normaliseSpecialPage
static normaliseSpecialPage(LinkTarget $target)
Definition: Linker.php:210
ExternalUserNames\getUserLinkTitle
static getUserLinkTitle( $userName)
Get a target Title to link a username.
Definition: ExternalUserNames.php:63
NS_MEDIA
const NS_MEDIA
Definition: Defines.php:52
Linker\TOOL_LINKS_EMAIL
const TOOL_LINKS_EMAIL
Definition: Linker.php:42
Linker\commentBlock
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:1751
Linker\userToolLinksRedContribs
static userToolLinksRedContribs( $userId, $userText, $edits=null, $useParentheses=true)
Alias for userToolLinks( $userId, $userText, true );.
Definition: Linker.php:1194
MediaWiki\Revision\RevisionRecord\getPageAsLinkTarget
getPageAsLinkTarget()
Returns the title of the page this revision is associated with as a LinkTarget object.
Definition: RevisionRecord.php:355
Xml\tags
static tags( $element, $attribs, $contents)
Same as Xml::element(), but does not escape contents.
Definition: Xml.php:132
Hooks\runner
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:173
Linker\link
static link( $target, $html=null, $customAttribs=[], $query=[], $options=[])
This function returns an HTML link to the given target.
Definition: Linker.php:87
WatchedItem
Representation of a pair of user and title for watchlist entries.
Definition: WatchedItem.php:36
MediaWiki\Linker\LinkTarget\getDBkey
getDBkey()
Get the main part with underscores.
Linker\formatRevisionSize
static formatRevisionSize( $size)
Definition: Linker.php:1822
MediaWiki\Linker\LinkTarget\getFragment
getFragment()
Get the link fragment (i.e.
NS_USER
const NS_USER
Definition: Defines.php:66
Parser
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition: Parser.php:89
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:484
DummyLinker
Definition: DummyLinker.php:9
Title\newFromLinkTarget
static newFromLinkTarget(LinkTarget $linkTarget, $forceClone='')
Returns a Title given a LinkTarget.
Definition: Title.php:327
Linker\makeMediaLinkFile
static makeMediaLinkFile(LinkTarget $title, $file, $html='')
Create a direct link to a given uploaded file.
Definition: Linker.php:947
$wgUploadNavigationUrl
$wgUploadNavigationUrl
Point the upload navigation link to an external URL Useful if you want to use a shared repository by ...
Definition: DefaultSettings.php:1056
Linker\titleAttrib
static titleAttrib( $name, $options=null, array $msgParams=[])
Given the id of an interface element, constructs the appropriate title attribute from the system mess...
Definition: Linker.php:2278
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:58
Linker\formatComment
static formatComment( $comment, $title=null, $local=false, $wikiId=null)
This function is called by all recent changes variants, by the page history, and by the user contribu...
Definition: Linker.php:1376
$userOptionsLookup
UserOptionsLookup $userOptionsLookup
Definition: ApiWatchlistTrait.php:33
Linker\tooltip
static tooltip( $name, $options=null)
Returns raw bits of HTML, use titleAttrib()
Definition: Linker.php:2507
MediaWiki\Permissions\Authority\isAllowed
isAllowed(string $permission)
Checks whether this authority has the given permission in general.
$wgMiserMode
$wgMiserMode
Disable database-intensive features.
Definition: DefaultSettings.php:2626
MediaWiki\Revision\RevisionRecord\getId
getId( $wikiId=self::LOCAL)
Get revision ID.
Definition: RevisionRecord.php:279
MalformedTitleException
MalformedTitleException is thrown when a TitleParser is unable to parse a title string.
Definition: MalformedTitleException.php:26
MediaWiki\Revision\RevisionRecord\isDeleted
isDeleted( $field)
MCR migration note: this replaced Revision::isDeleted.
Definition: RevisionRecord.php:437
$wgThumbUpright
$wgThumbUpright
Adjust width of upright images when parameter 'upright' is used This allows a nicer look for upright ...
Definition: DefaultSettings.php:1743
Linker\tocUnindent
static tocUnindent( $level)
Finish one or more sublevels on the Table of Contents.
Definition: Linker.php:1848
MediaWiki\Revision\RevisionRecord\userCan
userCan( $field, Authority $performer)
Determine if the give authority is allowed to view a particular field of this revision,...
Definition: RevisionRecord.php:509
Linker\makeImageLink
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:300
Html\openElement
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:254
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:212
Linker\revDeleteLink
static revDeleteLink( $query=[], $restricted=false, $delete=true)
Creates a (show/hide) link for deleting revisions/log entries.
Definition: Linker.php:2414
NS_USER_TALK
const NS_USER_TALK
Definition: Defines.php:67
MediaWiki\Revision\RevisionRecord\getTimestamp
getTimestamp()
MCR migration note: this replaced Revision::getTimestamp.
Definition: RevisionRecord.php:459
$wgEnableUploads
$wgEnableUploads
Allow users to upload files.
Definition: DefaultSettings.php:515
Linker\normalizeSubpageLink
static normalizeSubpageLink( $contextTitle, $target, &$text)
Definition: Linker.php:1658
wfWarn
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
Definition: GlobalFunctions.php:1043
Parser\guessSectionNameFromStrippedText
static guessSectionNameFromStrippedText( $text)
Like guessSectionNameFromWikiText(), but takes already-stripped text as input.
Definition: Parser.php:6089
Title\castFromLinkTarget
static castFromLinkTarget( $linkTarget)
Same as newFromLinkTarget, but if passed null, returns null.
Definition: Title.php:351
Html\element
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:234
$wgUploadMissingFileUrl
$wgUploadMissingFileUrl
Point the upload link for missing files to an external URL, as with $wgUploadNavigationUrl.
Definition: DefaultSettings.php:1063
NS_FILE
const NS_FILE
Definition: Defines.php:70
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:26
Linker\accesskey
static accesskey( $name)
Given the id of an interface element, constructs the appropriate accesskey attribute from the system ...
Definition: Linker.php:2326
Linker\getRevDeleteLink
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:2362
ExternalUserNames\isExternal
static isExternal( $username)
Tells whether the username is external or not.
Definition: ExternalUserNames.php:149
Linker\makeExternalImage
static makeExternalImage( $url, $alt='')
Return the code for images which were added via external links, via Parser::maybeMakeExternalImage().
Definition: Linker.php:244
Language
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
Definition: Language.php:42
MediaWiki\Revision\RevisionRecord\getVisibility
getVisibility()
Get the deletion bitfield of the revision.
Definition: RevisionRecord.php:448
Sanitizer\escapeHtmlAllowEntities
static escapeHtmlAllowEntities( $html)
Given HTML input, escape with htmlspecialchars but un-escape entities.
Definition: Sanitizer.php:987
$wgDisableAnonTalk
$wgDisableAnonTalk
Disable links to talk pages of anonymous users (IPs) in listings on special pages like page history,...
Definition: DefaultSettings.php:8152
TitleValue
Represents a page (or page fragment) title within MediaWiki.
Definition: TitleValue.php:40