MediaWiki  1.27.1
Linker.php
Go to the documentation of this file.
1 <?php
23 
33 class Linker {
37  const TOOL_LINKS_NOBLOCK = 1;
38  const TOOL_LINKS_EMAIL = 2;
39 
52  static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
54 
55  wfDeprecated( __METHOD__, '1.25' );
56 
57  # @todo FIXME: We have a whole bunch of handling here that doesn't happen in
58  # getExternalLinkAttributes, why?
59  $title = urldecode( $title );
60  $title = $wgContLang->checkTitleEncoding( $title );
61  $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
62 
63  return self::getLinkAttributesInternal( $title, $class );
64  }
65 
77  static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
78  wfDeprecated( __METHOD__, '1.25' );
79 
80  $title = urldecode( $title );
81  $title = strtr( $title, '_', ' ' );
82  return self::getLinkAttributesInternal( $title, $class );
83  }
84 
98  static function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
99  wfDeprecated( __METHOD__, '1.25' );
100 
101  if ( $title === false ) {
102  $title = $nt->getPrefixedText();
103  }
104  return self::getLinkAttributesInternal( $title, $class );
105  }
106 
117  private static function getLinkAttributesInternal( $title, $class ) {
118  wfDeprecated( __METHOD__, '1.25' );
119 
120  $title = htmlspecialchars( $title );
121  $class = htmlspecialchars( $class );
122  $r = '';
123  if ( $class != '' ) {
124  $r .= " class=\"$class\"";
125  }
126  if ( $title != '' ) {
127  $r .= " title=\"$title\"";
128  }
129  return $r;
130  }
131 
139  public static function getLinkColour( $t, $threshold ) {
140  $colour = '';
141  if ( $t->isRedirect() ) {
142  # Page is a redirect
143  $colour = 'mw-redirect';
144  } elseif ( $threshold > 0 && $t->isContentPage() &&
145  $t->exists() && $t->getLength() < $threshold
146  ) {
147  # Page is a stub
148  $colour = 'stub';
149  }
150  return $colour;
151  }
152 
195  public static function link(
196  $target, $html = null, $customAttribs = [], $query = [], $options = []
197  ) {
198  if ( !$target instanceof Title ) {
199  wfWarn( __METHOD__ . ': Requires $target to be a Title object.', 2 );
200  return "<!-- ERROR -->$html";
201  }
202 
203  if ( is_string( $query ) ) {
204  // some functions withing core using this still hand over query strings
205  wfDeprecated( __METHOD__ . ' with parameter $query as string (should be array)', '1.20' );
207  }
209 
210  $dummy = new DummyLinker; // dummy linker instance for bc on the hooks
211 
212  $ret = null;
213  if ( !Hooks::run( 'LinkBegin',
214  [ $dummy, $target, &$html, &$customAttribs, &$query, &$options, &$ret ] )
215  ) {
216  return $ret;
217  }
218 
219  # Normalize the Title if it's a special page
220  $target = self::normaliseSpecialPage( $target );
221 
222  # If we don't know whether the page exists, let's find out.
223  if ( !in_array( 'known', $options, true ) && !in_array( 'broken', $options, true ) ) {
224  if ( $target->isKnown() ) {
225  $options[] = 'known';
226  } else {
227  $options[] = 'broken';
228  }
229  }
230 
231  $oldquery = [];
232  if ( in_array( "forcearticlepath", $options, true ) && $query ) {
233  $oldquery = $query;
234  $query = [];
235  }
236 
237  # Note: we want the href attribute first, for prettiness.
238  $attribs = [ 'href' => self::linkUrl( $target, $query, $options ) ];
239  if ( in_array( 'forcearticlepath', $options, true ) && $oldquery ) {
240  $attribs['href'] = wfAppendQuery( $attribs['href'], $oldquery );
241  }
242 
243  $attribs = array_merge(
244  $attribs,
245  self::linkAttribs( $target, $customAttribs, $options )
246  );
247  if ( is_null( $html ) ) {
248  $html = self::linkText( $target );
249  }
250 
251  $ret = null;
252  if ( Hooks::run( 'LinkEnd', [ $dummy, $target, $options, &$html, &$attribs, &$ret ] ) ) {
253  $ret = Html::rawElement( 'a', $attribs, $html );
254  }
255 
256  return $ret;
257  }
258 
264  public static function linkKnown(
265  $target, $html = null, $customAttribs = [],
266  $query = [], $options = [ 'known', 'noclasses' ]
267  ) {
268  return self::link( $target, $html, $customAttribs, $query, $options );
269  }
270 
279  private static function linkUrl( LinkTarget $target, $query, $options ) {
280  # We don't want to include fragments for broken links, because they
281  # generally make no sense.
282  if ( in_array( 'broken', $options, true ) && $target->hasFragment() ) {
283  $target = $target->createFragmentTarget( '' );
284  }
285 
286  # If it's a broken link, add the appropriate query pieces, unless
287  # there's already an action specified, or unless 'edit' makes no sense
288  # (i.e., for a nonexistent special page).
289  if ( in_array( 'broken', $options, true ) && empty( $query['action'] )
290  && $target->getNamespace() !== NS_SPECIAL ) {
291  $query['action'] = 'edit';
292  $query['redlink'] = '1';
293  }
294 
295  if ( in_array( 'http', $options, true ) ) {
296  $proto = PROTO_HTTP;
297  } elseif ( in_array( 'https', $options, true ) ) {
298  $proto = PROTO_HTTPS;
299  } else {
300  $proto = PROTO_RELATIVE;
301  }
302 
303  $title = Title::newFromLinkTarget( $target );
304  $ret = $title->getLinkURL( $query, false, $proto );
305  return $ret;
306  }
307 
317  private static function linkAttribs( $target, $attribs, $options ) {
318  global $wgUser;
319  $defaults = [];
320 
321  if ( !in_array( 'noclasses', $options, true ) ) {
322  # Now build the classes.
323  $classes = [];
324 
325  if ( in_array( 'broken', $options, true ) ) {
326  $classes[] = 'new';
327  }
328 
329  if ( $target->isExternal() ) {
330  $classes[] = 'extiw';
331  }
332 
333  if ( !in_array( 'broken', $options, true ) ) { # Avoid useless calls to LinkCache (see r50387)
334  $colour = self::getLinkColour(
335  $target,
336  isset( $options['stubThreshold'] ) ? $options['stubThreshold'] : $wgUser->getStubThreshold()
337  );
338  if ( $colour !== '' ) {
339  $classes[] = $colour; # mw-redirect or stub
340  }
341  }
342  if ( $classes != [] ) {
343  $defaults['class'] = implode( ' ', $classes );
344  }
345  }
346 
347  # Get a default title attribute.
348  if ( $target->getPrefixedText() == '' ) {
349  # A link like [[#Foo]]. This used to mean an empty title
350  # attribute, but that's silly. Just don't output a title.
351  } elseif ( in_array( 'known', $options, true ) ) {
352  $defaults['title'] = $target->getPrefixedText();
353  } else {
354  // This ends up in parser cache!
355  $defaults['title'] = wfMessage( 'red-link-title', $target->getPrefixedText() )
356  ->inContentLanguage()
357  ->text();
358  }
359 
360  # Finally, merge the custom attribs with the default ones, and iterate
361  # over that, deleting all "false" attributes.
362  $ret = [];
363  $merged = Sanitizer::mergeAttributes( $defaults, $attribs );
364  foreach ( $merged as $key => $val ) {
365  # A false value suppresses the attribute, and we don't want the
366  # href attribute to be overridden.
367  if ( $key != 'href' && $val !== false ) {
368  $ret[$key] = $val;
369  }
370  }
371  return $ret;
372  }
373 
381  private static function linkText( $target ) {
382  if ( !$target instanceof Title ) {
383  wfWarn( __METHOD__ . ': Requires $target to be a Title object.' );
384  return '';
385  }
386  // If the target is just a fragment, with no title, we return the fragment
387  // text. Otherwise, we return the title text itself.
388  if ( $target->getPrefixedText() === '' && $target->hasFragment() ) {
389  return htmlspecialchars( $target->getFragment() );
390  }
391 
392  return htmlspecialchars( $target->getPrefixedText() );
393  }
394 
409  public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
410  $ret = "<strong class=\"selflink\">{$prefix}{$html}</strong>{$trail}";
411  if ( !Hooks::run( 'SelfLinkBegin', [ $nt, &$html, &$trail, &$prefix, &$ret ] ) ) {
412  return $ret;
413  }
414 
415  if ( $html == '' ) {
416  $html = htmlspecialchars( $nt->getPrefixedText() );
417  }
418  list( $inside, $trail ) = self::splitTrail( $trail );
419  return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
420  }
421 
432  public static function getInvalidTitleDescription( IContextSource $context, $namespace, $title ) {
434 
435  // First we check whether the namespace exists or not.
436  if ( MWNamespace::exists( $namespace ) ) {
437  if ( $namespace == NS_MAIN ) {
438  $name = $context->msg( 'blanknamespace' )->text();
439  } else {
440  $name = $wgContLang->getFormattedNsText( $namespace );
441  }
442  return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
443  } else {
444  return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
445  }
446  }
447 
452  static function normaliseSpecialPage( LinkTarget $target ) {
453  if ( $target->getNamespace() == NS_SPECIAL ) {
454  list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $target->getDBkey() );
455  if ( !$name ) {
456  return $target;
457  }
458  $ret = SpecialPage::getTitleFor( $name, $subpage, $target->getFragment() );
459  return $ret;
460  } else {
461  return $target;
462  }
463  }
464 
473  private static function fnamePart( $url ) {
474  $basename = strrchr( $url, '/' );
475  if ( false === $basename ) {
476  $basename = $url;
477  } else {
478  $basename = substr( $basename, 1 );
479  }
480  return $basename;
481  }
482 
492  public static function makeExternalImage( $url, $alt = '' ) {
493  if ( $alt == '' ) {
494  $alt = self::fnamePart( $url );
495  }
496  $img = '';
497  $success = Hooks::run( 'LinkerMakeExternalImage', [ &$url, &$alt, &$img ] );
498  if ( !$success ) {
499  wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
500  . "with url {$url} and alt text {$alt} to {$img}\n", true );
501  return $img;
502  }
503  return Html::element( 'img',
504  [
505  'src' => $url,
506  'alt' => $alt ] );
507  }
508 
545  public static function makeImageLink( Parser $parser, Title $title,
546  $file, $frameParams = [], $handlerParams = [], $time = false,
547  $query = "", $widthOption = null
548  ) {
549  $res = null;
550  $dummy = new DummyLinker;
551  if ( !Hooks::run( 'ImageBeforeProduceHTML', [ &$dummy, &$title,
552  &$file, &$frameParams, &$handlerParams, &$time, &$res ] ) ) {
553  return $res;
554  }
555 
556  if ( $file && !$file->allowInlineDisplay() ) {
557  wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
558  return self::link( $title );
559  }
560 
561  // Shortcuts
562  $fp =& $frameParams;
563  $hp =& $handlerParams;
564 
565  // Clean up parameters
566  $page = isset( $hp['page'] ) ? $hp['page'] : false;
567  if ( !isset( $fp['align'] ) ) {
568  $fp['align'] = '';
569  }
570  if ( !isset( $fp['alt'] ) ) {
571  $fp['alt'] = '';
572  }
573  if ( !isset( $fp['title'] ) ) {
574  $fp['title'] = '';
575  }
576  if ( !isset( $fp['class'] ) ) {
577  $fp['class'] = '';
578  }
579 
580  $prefix = $postfix = '';
581 
582  if ( 'center' == $fp['align'] ) {
583  $prefix = '<div class="center">';
584  $postfix = '</div>';
585  $fp['align'] = 'none';
586  }
587  if ( $file && !isset( $hp['width'] ) ) {
588  if ( isset( $hp['height'] ) && $file->isVectorized() ) {
589  // If its a vector image, and user only specifies height
590  // we don't want it to be limited by its "normal" width.
592  $hp['width'] = $wgSVGMaxSize;
593  } else {
594  $hp['width'] = $file->getWidth( $page );
595  }
596 
597  if ( isset( $fp['thumbnail'] )
598  || isset( $fp['manualthumb'] )
599  || isset( $fp['framed'] )
600  || isset( $fp['frameless'] )
601  || !$hp['width']
602  ) {
604 
605  if ( $widthOption === null || !isset( $wgThumbLimits[$widthOption] ) ) {
606  $widthOption = User::getDefaultOption( 'thumbsize' );
607  }
608 
609  // Reduce width for upright images when parameter 'upright' is used
610  if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
611  $fp['upright'] = $wgThumbUpright;
612  }
613 
614  // For caching health: If width scaled down due to upright
615  // parameter, round to full __0 pixel to avoid the creation of a
616  // lot of odd thumbs.
617  $prefWidth = isset( $fp['upright'] ) ?
618  round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
619  $wgThumbLimits[$widthOption];
620 
621  // Use width which is smaller: real image width or user preference width
622  // Unless image is scalable vector.
623  if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
624  $prefWidth < $hp['width'] || $file->isVectorized() ) ) {
625  $hp['width'] = $prefWidth;
626  }
627  }
628  }
629 
630  if ( isset( $fp['thumbnail'] ) || isset( $fp['manualthumb'] ) || isset( $fp['framed'] ) ) {
631  # Create a thumbnail. Alignment depends on the writing direction of
632  # the page content language (right-aligned for LTR languages,
633  # left-aligned for RTL languages)
634  # If a thumbnail width has not been provided, it is set
635  # to the default user option as specified in Language*.php
636  if ( $fp['align'] == '' ) {
637  $fp['align'] = $parser->getTargetLanguage()->alignEnd();
638  }
639  return $prefix . self::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
640  }
641 
642  if ( $file && isset( $fp['frameless'] ) ) {
643  $srcWidth = $file->getWidth( $page );
644  # For "frameless" option: do not present an image bigger than the
645  # source (for bitmap-style images). This is the same behavior as the
646  # "thumb" option does it already.
647  if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
648  $hp['width'] = $srcWidth;
649  }
650  }
651 
652  if ( $file && isset( $hp['width'] ) ) {
653  # Create a resized image, without the additional thumbnail features
654  $thumb = $file->transform( $hp );
655  } else {
656  $thumb = false;
657  }
658 
659  if ( !$thumb ) {
660  $s = self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
661  } else {
662  self::processResponsiveImages( $file, $thumb, $hp );
663  $params = [
664  'alt' => $fp['alt'],
665  'title' => $fp['title'],
666  'valign' => isset( $fp['valign'] ) ? $fp['valign'] : false,
667  'img-class' => $fp['class'] ];
668  if ( isset( $fp['border'] ) ) {
669  $params['img-class'] .= ( $params['img-class'] !== '' ? ' ' : '' ) . 'thumbborder';
670  }
671  $params = self::getImageLinkMTOParams( $fp, $query, $parser ) + $params;
672 
673  $s = $thumb->toHtml( $params );
674  }
675  if ( $fp['align'] != '' ) {
676  $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
677  }
678  return str_replace( "\n", ' ', $prefix . $s . $postfix );
679  }
680 
689  private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
690  $mtoParams = [];
691  if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
692  $mtoParams['custom-url-link'] = $frameParams['link-url'];
693  if ( isset( $frameParams['link-target'] ) ) {
694  $mtoParams['custom-target-link'] = $frameParams['link-target'];
695  }
696  if ( $parser ) {
697  $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
698  foreach ( $extLinkAttrs as $name => $val ) {
699  // Currently could include 'rel' and 'target'
700  $mtoParams['parser-extlink-' . $name] = $val;
701  }
702  }
703  } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
704  $mtoParams['custom-title-link'] = self::normaliseSpecialPage( $frameParams['link-title'] );
705  } elseif ( !empty( $frameParams['no-link'] ) ) {
706  // No link
707  } else {
708  $mtoParams['desc-link'] = true;
709  $mtoParams['desc-query'] = $query;
710  }
711  return $mtoParams;
712  }
713 
726  public static function makeThumbLinkObj( Title $title, $file, $label = '', $alt,
727  $align = 'right', $params = [], $framed = false, $manualthumb = ""
728  ) {
729  $frameParams = [
730  'alt' => $alt,
731  'caption' => $label,
732  'align' => $align
733  ];
734  if ( $framed ) {
735  $frameParams['framed'] = true;
736  }
737  if ( $manualthumb ) {
738  $frameParams['manualthumb'] = $manualthumb;
739  }
740  return self::makeThumbLink2( $title, $file, $frameParams, $params );
741  }
742 
752  public static function makeThumbLink2( Title $title, $file, $frameParams = [],
753  $handlerParams = [], $time = false, $query = ""
754  ) {
755  $exists = $file && $file->exists();
756 
757  # Shortcuts
758  $fp =& $frameParams;
759  $hp =& $handlerParams;
760 
761  $page = isset( $hp['page'] ) ? $hp['page'] : false;
762  if ( !isset( $fp['align'] ) ) {
763  $fp['align'] = 'right';
764  }
765  if ( !isset( $fp['alt'] ) ) {
766  $fp['alt'] = '';
767  }
768  if ( !isset( $fp['title'] ) ) {
769  $fp['title'] = '';
770  }
771  if ( !isset( $fp['caption'] ) ) {
772  $fp['caption'] = '';
773  }
774 
775  if ( empty( $hp['width'] ) ) {
776  // Reduce width for upright images when parameter 'upright' is used
777  $hp['width'] = isset( $fp['upright'] ) ? 130 : 180;
778  }
779  $thumb = false;
780  $noscale = false;
781  $manualthumb = false;
782 
783  if ( !$exists ) {
784  $outerWidth = $hp['width'] + 2;
785  } else {
786  if ( isset( $fp['manualthumb'] ) ) {
787  # Use manually specified thumbnail
788  $manual_title = Title::makeTitleSafe( NS_FILE, $fp['manualthumb'] );
789  if ( $manual_title ) {
790  $manual_img = wfFindFile( $manual_title );
791  if ( $manual_img ) {
792  $thumb = $manual_img->getUnscaledThumb( $hp );
793  $manualthumb = true;
794  } else {
795  $exists = false;
796  }
797  }
798  } elseif ( isset( $fp['framed'] ) ) {
799  // Use image dimensions, don't scale
800  $thumb = $file->getUnscaledThumb( $hp );
801  $noscale = true;
802  } else {
803  # Do not present an image bigger than the source, for bitmap-style images
804  # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
805  $srcWidth = $file->getWidth( $page );
806  if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
807  $hp['width'] = $srcWidth;
808  }
809  $thumb = $file->transform( $hp );
810  }
811 
812  if ( $thumb ) {
813  $outerWidth = $thumb->getWidth() + 2;
814  } else {
815  $outerWidth = $hp['width'] + 2;
816  }
817  }
818 
819  # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
820  # So we don't need to pass it here in $query. However, the URL for the
821  # zoom icon still needs it, so we make a unique query for it. See bug 14771
822  $url = $title->getLocalURL( $query );
823  if ( $page ) {
824  $url = wfAppendQuery( $url, [ 'page' => $page ] );
825  }
826  if ( $manualthumb
827  && !isset( $fp['link-title'] )
828  && !isset( $fp['link-url'] )
829  && !isset( $fp['no-link'] ) ) {
830  $fp['link-url'] = $url;
831  }
832 
833  $s = "<div class=\"thumb t{$fp['align']}\">"
834  . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
835 
836  if ( !$exists ) {
837  $s .= self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
838  $zoomIcon = '';
839  } elseif ( !$thumb ) {
840  $s .= wfMessage( 'thumbnail_error', '' )->escaped();
841  $zoomIcon = '';
842  } else {
843  if ( !$noscale && !$manualthumb ) {
844  self::processResponsiveImages( $file, $thumb, $hp );
845  }
846  $params = [
847  'alt' => $fp['alt'],
848  'title' => $fp['title'],
849  'img-class' => ( isset( $fp['class'] ) && $fp['class'] !== ''
850  ? $fp['class'] . ' '
851  : '' ) . 'thumbimage'
852  ];
853  $params = self::getImageLinkMTOParams( $fp, $query ) + $params;
854  $s .= $thumb->toHtml( $params );
855  if ( isset( $fp['framed'] ) ) {
856  $zoomIcon = "";
857  } else {
858  $zoomIcon = Html::rawElement( 'div', [ 'class' => 'magnify' ],
859  Html::rawElement( 'a', [
860  'href' => $url,
861  'class' => 'internal',
862  'title' => wfMessage( 'thumbnail-more' )->text() ],
863  "" ) );
864  }
865  }
866  $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
867  return str_replace( "\n", ' ', $s );
868  }
869 
878  public static function processResponsiveImages( $file, $thumb, $hp ) {
880  if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
881  $hp15 = $hp;
882  $hp15['width'] = round( $hp['width'] * 1.5 );
883  $hp20 = $hp;
884  $hp20['width'] = $hp['width'] * 2;
885  if ( isset( $hp['height'] ) ) {
886  $hp15['height'] = round( $hp['height'] * 1.5 );
887  $hp20['height'] = $hp['height'] * 2;
888  }
889 
890  $thumb15 = $file->transform( $hp15 );
891  $thumb20 = $file->transform( $hp20 );
892  if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
893  $thumb->responsiveUrls['1.5'] = $thumb15->getUrl();
894  }
895  if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
896  $thumb->responsiveUrls['2'] = $thumb20->getUrl();
897  }
898  }
899  }
900 
912  public static function makeBrokenImageLinkObj( $title, $label = '',
913  $query = '', $unused1 = '', $unused2 = '', $time = false
914  ) {
915  if ( !$title instanceof Title ) {
916  wfWarn( __METHOD__ . ': Requires $title to be a Title object.' );
917  return "<!-- ERROR -->" . htmlspecialchars( $label );
918  }
919 
921  if ( $label == '' ) {
922  $label = $title->getPrefixedText();
923  }
924  $encLabel = htmlspecialchars( $label );
925  $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
926 
927  if ( ( $wgUploadMissingFileUrl || $wgUploadNavigationUrl || $wgEnableUploads )
928  && !$currentExists
929  ) {
930  $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
931 
932  if ( $redir ) {
933  return self::linkKnown( $title, $encLabel, [], wfCgiToArray( $query ) );
934  }
935 
936  $href = self::getUploadUrl( $title, $query );
937 
938  return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
939  htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES ) . '">' .
940  $encLabel . '</a>';
941  }
942 
943  return self::linkKnown( $title, $encLabel, [], wfCgiToArray( $query ) );
944  }
945 
953  protected static function getUploadUrl( $destFile, $query = '' ) {
955  $q = 'wpDestFile=' . $destFile->getPartialURL();
956  if ( $query != '' ) {
957  $q .= '&' . $query;
958  }
959 
960  if ( $wgUploadMissingFileUrl ) {
961  return wfAppendQuery( $wgUploadMissingFileUrl, $q );
962  } elseif ( $wgUploadNavigationUrl ) {
963  return wfAppendQuery( $wgUploadNavigationUrl, $q );
964  } else {
965  $upload = SpecialPage::getTitleFor( 'Upload' );
966  return $upload->getLocalURL( $q );
967  }
968  }
969 
978  public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
979  $img = wfFindFile( $title, [ 'time' => $time ] );
980  return self::makeMediaLinkFile( $title, $img, $html );
981  }
982 
994  public static function makeMediaLinkFile( Title $title, $file, $html = '' ) {
995  if ( $file && $file->exists() ) {
996  $url = $file->getUrl();
997  $class = 'internal';
998  } else {
999  $url = self::getUploadUrl( $title );
1000  $class = 'new';
1001  }
1002 
1003  $alt = $title->getText();
1004  if ( $html == '' ) {
1005  $html = $alt;
1006  }
1007 
1008  $ret = '';
1009  $attribs = [
1010  'href' => $url,
1011  'class' => $class,
1012  'title' => $alt
1013  ];
1014 
1015  if ( !Hooks::run( 'LinkerMakeMediaLinkFile',
1016  [ $title, $file, &$html, &$attribs, &$ret ] ) ) {
1017  wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
1018  . "with url {$url} and text {$html} to {$ret}\n", true );
1019  return $ret;
1020  }
1021 
1022  return Html::rawElement( 'a', $attribs, $html );
1023  }
1024 
1034  public static function specialLink( $name, $key = '' ) {
1035  if ( $key == '' ) {
1036  $key = strtolower( $name );
1037  }
1038 
1039  return self::linkKnown( SpecialPage::getTitleFor( $name ), wfMessage( $key )->text() );
1040  }
1041 
1052  public static function makeExternalLink( $url, $text, $escape = true,
1053  $linktype = '', $attribs = [], $title = null
1054  ) {
1055  global $wgTitle;
1056  $class = "external";
1057  if ( $linktype ) {
1058  $class .= " $linktype";
1059  }
1060  if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1061  $class .= " {$attribs['class']}";
1062  }
1063  $attribs['class'] = $class;
1064 
1065  if ( $escape ) {
1066  $text = htmlspecialchars( $text );
1067  }
1068 
1069  if ( !$title ) {
1070  $title = $wgTitle;
1071  }
1072  $newRel = Parser::getExternalLinkRel( $url, $title );
1073  if ( !isset( $attribs['rel'] ) || $attribs['rel'] === '' ) {
1074  $attribs['rel'] = $newRel;
1075  } elseif ( $newRel !== '' ) {
1076  // Merge the rel attributes.
1077  $newRels = explode( ' ', $newRel );
1078  $oldRels = explode( ' ', $attribs['rel'] );
1079  $combined = array_unique( array_merge( $newRels, $oldRels ) );
1080  $attribs['rel'] = implode( ' ', $combined );
1081  }
1082  $link = '';
1083  $success = Hooks::run( 'LinkerMakeExternalLink',
1084  [ &$url, &$text, &$link, &$attribs, $linktype ] );
1085  if ( !$success ) {
1086  wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
1087  . "with url {$url} and text {$text} to {$link}\n", true );
1088  return $link;
1089  }
1090  $attribs['href'] = $url;
1091  return Html::rawElement( 'a', $attribs, $text );
1092  }
1093 
1102  public static function userLink( $userId, $userName, $altUserName = false ) {
1103  $classes = 'mw-userlink';
1104  if ( $userId == 0 ) {
1105  $page = SpecialPage::getTitleFor( 'Contributions', $userName );
1106  if ( $altUserName === false ) {
1107  $altUserName = IP::prettifyIP( $userName );
1108  }
1109  $classes .= ' mw-anonuserlink'; // Separate link class for anons (bug 43179)
1110  } else {
1111  $page = Title::makeTitle( NS_USER, $userName );
1112  }
1113 
1114  return self::link(
1115  $page,
1116  htmlspecialchars( $altUserName !== false ? $altUserName : $userName ),
1117  [ 'class' => $classes ]
1118  );
1119  }
1120 
1133  public static function userToolLinks(
1134  $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1135  ) {
1136  global $wgUser, $wgDisableAnonTalk, $wgLang;
1137  $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1138  $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1139  $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1140 
1141  $items = [];
1142  if ( $talkable ) {
1143  $items[] = self::userTalkLink( $userId, $userText );
1144  }
1145  if ( $userId ) {
1146  // check if the user has an edit
1147  $attribs = [];
1148  if ( $redContribsWhenNoEdits ) {
1149  if ( intval( $edits ) === 0 && $edits !== 0 ) {
1150  $user = User::newFromId( $userId );
1151  $edits = $user->getEditCount();
1152  }
1153  if ( $edits === 0 ) {
1154  $attribs['class'] = 'new';
1155  }
1156  }
1157  $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1158 
1159  $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1160  }
1161  if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1162  $items[] = self::blockLink( $userId, $userText );
1163  }
1164 
1165  if ( $addEmailLink && $wgUser->canSendEmail() ) {
1166  $items[] = self::emailLink( $userId, $userText );
1167  }
1168 
1169  Hooks::run( 'UserToolLinksEdit', [ $userId, $userText, &$items ] );
1170 
1171  if ( $items ) {
1172  return wfMessage( 'word-separator' )->escaped()
1173  . '<span class="mw-usertoollinks">'
1174  . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1175  . '</span>';
1176  } else {
1177  return '';
1178  }
1179  }
1180 
1188  public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1189  return self::userToolLinks( $userId, $userText, true, 0, $edits );
1190  }
1191 
1197  public static function userTalkLink( $userId, $userText ) {
1198  $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1199  $userTalkLink = self::link( $userTalkPage, wfMessage( 'talkpagelinktext' )->escaped() );
1200  return $userTalkLink;
1201  }
1202 
1208  public static function blockLink( $userId, $userText ) {
1209  $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1210  $blockLink = self::link( $blockPage, wfMessage( 'blocklink' )->escaped() );
1211  return $blockLink;
1212  }
1213 
1219  public static function emailLink( $userId, $userText ) {
1220  $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1221  $emailLink = self::link( $emailPage, wfMessage( 'emaillink' )->escaped() );
1222  return $emailLink;
1223  }
1224 
1231  public static function revUserLink( $rev, $isPublic = false ) {
1232  if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1233  $link = wfMessage( 'rev-deleted-user' )->escaped();
1234  } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1235  $link = self::userLink( $rev->getUser( Revision::FOR_THIS_USER ),
1236  $rev->getUserText( Revision::FOR_THIS_USER ) );
1237  } else {
1238  $link = wfMessage( 'rev-deleted-user' )->escaped();
1239  }
1240  if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1241  return '<span class="history-deleted">' . $link . '</span>';
1242  }
1243  return $link;
1244  }
1245 
1252  public static function revUserTools( $rev, $isPublic = false ) {
1253  if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1254  $link = wfMessage( 'rev-deleted-user' )->escaped();
1255  } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1256  $userId = $rev->getUser( Revision::FOR_THIS_USER );
1257  $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1258  $link = self::userLink( $userId, $userText )
1259  . self::userToolLinks( $userId, $userText );
1260  } else {
1261  $link = wfMessage( 'rev-deleted-user' )->escaped();
1262  }
1263  if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1264  return ' <span class="history-deleted">' . $link . '</span>';
1265  }
1266  return $link;
1267  }
1268 
1290  public static function formatComment(
1291  $comment, $title = null, $local = false, $wikiId = null
1292  ) {
1293  # Sanitize text a bit:
1294  $comment = str_replace( "\n", " ", $comment );
1295  # Allow HTML entities (for bug 13815)
1297 
1298  # Render autocomments and make links:
1299  $comment = self::formatAutocomments( $comment, $title, $local, $wikiId );
1300  $comment = self::formatLinksInComment( $comment, $title, $local, $wikiId );
1301 
1302  return $comment;
1303  }
1304 
1322  private static function formatAutocomments(
1323  $comment, $title = null, $local = false, $wikiId = null
1324  ) {
1325  // @todo $append here is something of a hack to preserve the status
1326  // quo. Someone who knows more about bidi and such should decide
1327  // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1328  // wiki, both when autocomments exist and when they don't, and
1329  // (2) what markup will make that actually happen.
1330  $append = '';
1331  $comment = preg_replace_callback(
1332  // To detect the presence of content before or after the
1333  // auto-comment, we use capturing groups inside optional zero-width
1334  // assertions. But older versions of PCRE can't directly make
1335  // zero-width assertions optional, so wrap them in a non-capturing
1336  // group.
1337  '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1338  function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1339  global $wgLang;
1340 
1341  // Ensure all match positions are defined
1342  $match += [ '', '', '', '' ];
1343 
1344  $pre = $match[1] !== '';
1345  $auto = $match[2];
1346  $post = $match[3] !== '';
1347  $comment = null;
1348 
1349  Hooks::run(
1350  'FormatAutocomments',
1351  [ &$comment, $pre, $auto, $post, $title, $local, $wikiId ]
1352  );
1353 
1354  if ( $comment === null ) {
1355  $link = '';
1356  if ( $title ) {
1357  $section = $auto;
1358  # Remove links that a user may have manually put in the autosummary
1359  # This could be improved by copying as much of Parser::stripSectionName as desired.
1360  $section = str_replace( '[[:', '', $section );
1361  $section = str_replace( '[[', '', $section );
1362  $section = str_replace( ']]', '', $section );
1363 
1365  if ( $local ) {
1366  $sectionTitle = Title::newFromText( '#' . $section );
1367  } else {
1368  $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1369  $title->getDBkey(), $section );
1370  }
1371  if ( $sectionTitle ) {
1372  $link = Linker::makeCommentLink( $sectionTitle, $wgLang->getArrow(), $wikiId, 'noclasses' );
1373  } else {
1374  $link = '';
1375  }
1376  }
1377  if ( $pre ) {
1378  # written summary $presep autocomment (summary /* section */)
1379  $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1380  }
1381  if ( $post ) {
1382  # autocomment $postsep written summary (/* section */ summary)
1383  $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1384  }
1385  $auto = '<span class="autocomment">' . $auto . '</span>';
1386  $comment = $pre . $link . $wgLang->getDirMark()
1387  . '<span dir="auto">' . $auto;
1388  $append .= '</span>';
1389  }
1390  return $comment;
1391  },
1392  $comment
1393  );
1394  return $comment . $append;
1395  }
1396 
1413  public static function formatLinksInComment(
1414  $comment, $title = null, $local = false, $wikiId = null
1415  ) {
1416  return preg_replace_callback(
1417  '/
1418  \[\[
1419  :? # ignore optional leading colon
1420  ([^\]|]+) # 1. link target; page names cannot include ] or |
1421  (?:\|
1422  # 2. a pipe-separated substring; only the last is captured
1423  # Stop matching at | and ]] without relying on backtracking.
1424  ((?:]?[^\]|])*+)
1425  )*
1426  \]\]
1427  ([^[]*) # 3. link trail (the text up until the next link)
1428  /x',
1429  function ( $match ) use ( $title, $local, $wikiId ) {
1431 
1432  $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1433  $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1434 
1435  $comment = $match[0];
1436 
1437  # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1438  if ( strpos( $match[1], '%' ) !== false ) {
1439  $match[1] = strtr(
1440  rawurldecode( $match[1] ),
1441  [ '<' => '&lt;', '>' => '&gt;' ]
1442  );
1443  }
1444 
1445  # Handle link renaming [[foo|text]] will show link as "text"
1446  if ( $match[2] != "" ) {
1447  $text = $match[2];
1448  } else {
1449  $text = $match[1];
1450  }
1451  $submatch = [];
1452  $thelink = null;
1453  if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1454  # Media link; trail not supported.
1455  $linkRegexp = '/\[\[(.*?)\]\]/';
1456  $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1457  if ( $title ) {
1458  $thelink = Linker::makeMediaLinkObj( $title, $text );
1459  }
1460  } else {
1461  # Other kind of link
1462  # Make sure its target is non-empty
1463  if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1464  $match[1] = substr( $match[1], 1 );
1465  }
1466  if ( $match[1] !== false && $match[1] !== '' ) {
1467  if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1468  $trail = $submatch[1];
1469  } else {
1470  $trail = "";
1471  }
1472  $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1473  list( $inside, $trail ) = Linker::splitTrail( $trail );
1474 
1475  $linkText = $text;
1476  $linkTarget = Linker::normalizeSubpageLink( $title, $match[1], $linkText );
1477 
1478  $target = Title::newFromText( $linkTarget );
1479  if ( $target ) {
1480  if ( $target->getText() == '' && !$target->isExternal()
1481  && !$local && $title
1482  ) {
1483  $newTarget = clone $title;
1484  $newTarget->setFragment( '#' . $target->getFragment() );
1485  $target = $newTarget;
1486  }
1487 
1488  $thelink = Linker::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1489  }
1490  }
1491  }
1492  if ( $thelink ) {
1493  // If the link is still valid, go ahead and replace it in!
1494  $comment = preg_replace(
1495  $linkRegexp,
1497  $comment,
1498  1
1499  );
1500  }
1501 
1502  return $comment;
1503  },
1504  $comment
1505  );
1506  }
1507 
1521  public static function makeCommentLink(
1522  Title $title, $text, $wikiId = null, $options = []
1523  ) {
1524  if ( $wikiId !== null && !$title->isExternal() ) {
1527  $wikiId,
1528  $title->getPrefixedText(),
1529  $title->getFragment()
1530  ),
1531  $text,
1532  /* escape = */ false // Already escaped
1533  );
1534  } else {
1535  $link = Linker::link( $title, $text, [], [], $options );
1536  }
1537 
1538  return $link;
1539  }
1540 
1547  public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1548  # Valid link forms:
1549  # Foobar -- normal
1550  # :Foobar -- override special treatment of prefix (images, language links)
1551  # /Foobar -- convert to CurrentPage/Foobar
1552  # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1553  # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1554  # ../Foobar -- convert to CurrentPage/Foobar,
1555  # (from CurrentPage/CurrentSubPage)
1556  # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1557  # (from CurrentPage/CurrentSubPage)
1558 
1559  $ret = $target; # default return value is no change
1560 
1561  # Some namespaces don't allow subpages,
1562  # so only perform processing if subpages are allowed
1563  if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1564  $hash = strpos( $target, '#' );
1565  if ( $hash !== false ) {
1566  $suffix = substr( $target, $hash );
1567  $target = substr( $target, 0, $hash );
1568  } else {
1569  $suffix = '';
1570  }
1571  # bug 7425
1572  $target = trim( $target );
1573  # Look at the first character
1574  if ( $target != '' && $target[0] === '/' ) {
1575  # / at end means we don't want the slash to be shown
1576  $m = [];
1577  $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1578  if ( $trailingSlashes ) {
1579  $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1580  } else {
1581  $noslash = substr( $target, 1 );
1582  }
1583 
1584  $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1585  if ( $text === '' ) {
1586  $text = $target . $suffix;
1587  } # this might be changed for ugliness reasons
1588  } else {
1589  # check for .. subpage backlinks
1590  $dotdotcount = 0;
1591  $nodotdot = $target;
1592  while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1593  ++$dotdotcount;
1594  $nodotdot = substr( $nodotdot, 3 );
1595  }
1596  if ( $dotdotcount > 0 ) {
1597  $exploded = explode( '/', $contextTitle->getPrefixedText() );
1598  if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1599  $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1600  # / at the end means don't show full path
1601  if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1602  $nodotdot = rtrim( $nodotdot, '/' );
1603  if ( $text === '' ) {
1604  $text = $nodotdot . $suffix;
1605  }
1606  }
1607  $nodotdot = trim( $nodotdot );
1608  if ( $nodotdot != '' ) {
1609  $ret .= '/' . $nodotdot;
1610  }
1611  $ret .= $suffix;
1612  }
1613  }
1614  }
1615  }
1616 
1617  return $ret;
1618  }
1619 
1632  public static function commentBlock(
1633  $comment, $title = null, $local = false, $wikiId = null
1634  ) {
1635  // '*' used to be the comment inserted by the software way back
1636  // in antiquity in case none was provided, here for backwards
1637  // compatibility, acc. to brion -ævar
1638  if ( $comment == '' || $comment == '*' ) {
1639  return '';
1640  } else {
1641  $formatted = self::formatComment( $comment, $title, $local, $wikiId );
1642  $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1643  return " <span class=\"comment\">$formatted</span>";
1644  }
1645  }
1646 
1656  public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1657  if ( $rev->getComment( Revision::RAW ) == "" ) {
1658  return "";
1659  }
1660  if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1661  $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1662  } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1663  $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1664  $rev->getTitle(), $local );
1665  } else {
1666  $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1667  }
1668  if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1669  return " <span class=\"history-deleted\">$block</span>";
1670  }
1671  return $block;
1672  }
1673 
1678  public static function formatRevisionSize( $size ) {
1679  if ( $size == 0 ) {
1680  $stxt = wfMessage( 'historyempty' )->escaped();
1681  } else {
1682  $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1683  $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1684  }
1685  return "<span class=\"history-size\">$stxt</span>";
1686  }
1687 
1693  public static function tocIndent() {
1694  return "\n<ul>";
1695  }
1696 
1703  public static function tocUnindent( $level ) {
1704  return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1705  }
1706 
1717  public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1718  $classes = "toclevel-$level";
1719  if ( $sectionIndex !== false ) {
1720  $classes .= " tocsection-$sectionIndex";
1721  }
1722  return "\n<li class=\"$classes\"><a href=\"#" .
1723  $anchor . '"><span class="tocnumber">' .
1724  $tocnumber . '</span> <span class="toctext">' .
1725  $tocline . '</span></a>';
1726  }
1727 
1734  public static function tocLineEnd() {
1735  return "</li>\n";
1736  }
1737 
1745  public static function tocList( $toc, $lang = false ) {
1746  $lang = wfGetLangObj( $lang );
1747  $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1748 
1749  return '<div id="toc" class="toc">'
1750  . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1751  . $toc
1752  . "</ul>\n</div>\n";
1753  }
1754 
1762  public static function generateTOC( $tree, $lang = false ) {
1763  $toc = '';
1764  $lastLevel = 0;
1765  foreach ( $tree as $section ) {
1766  if ( $section['toclevel'] > $lastLevel ) {
1767  $toc .= self::tocIndent();
1768  } elseif ( $section['toclevel'] < $lastLevel ) {
1769  $toc .= self::tocUnindent(
1770  $lastLevel - $section['toclevel'] );
1771  } else {
1772  $toc .= self::tocLineEnd();
1773  }
1774 
1775  $toc .= self::tocLine( $section['anchor'],
1776  $section['line'], $section['number'],
1777  $section['toclevel'], $section['index'] );
1778  $lastLevel = $section['toclevel'];
1779  }
1780  $toc .= self::tocLineEnd();
1781  return self::tocList( $toc, $lang );
1782  }
1783 
1799  public static function makeHeadline( $level, $attribs, $anchor, $html,
1800  $link, $legacyAnchor = false
1801  ) {
1802  $ret = "<h$level$attribs"
1803  . "<span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1804  . $link
1805  . "</h$level>";
1806  if ( $legacyAnchor !== false ) {
1807  $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1808  }
1809  return $ret;
1810  }
1811 
1818  static function splitTrail( $trail ) {
1820  $regex = $wgContLang->linkTrail();
1821  $inside = '';
1822  if ( $trail !== '' ) {
1823  $m = [];
1824  if ( preg_match( $regex, $trail, $m ) ) {
1825  $inside = $m[1];
1826  $trail = $m[2];
1827  }
1828  }
1829  return [ $inside, $trail ];
1830  }
1831 
1857  public static function generateRollback( $rev, IContextSource $context = null,
1858  $options = [ 'verify' ]
1859  ) {
1860  if ( $context === null ) {
1862  }
1863 
1864  $editCount = false;
1865  if ( in_array( 'verify', $options, true ) ) {
1866  $editCount = self::getRollbackEditCount( $rev, true );
1867  if ( $editCount === false ) {
1868  return '';
1869  }
1870  }
1871 
1872  $inner = self::buildRollbackLink( $rev, $context, $editCount );
1873 
1874  if ( !in_array( 'noBrackets', $options, true ) ) {
1875  $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1876  }
1877 
1878  return '<span class="mw-rollback-link">' . $inner . '</span>';
1879  }
1880 
1896  public static function getRollbackEditCount( $rev, $verify ) {
1898  if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
1899  // Nothing has happened, indicate this by returning 'null'
1900  return null;
1901  }
1902 
1903  $dbr = wfGetDB( DB_SLAVE );
1904 
1905  // Up to the value of $wgShowRollbackEditCount revisions are counted
1906  $res = $dbr->select(
1907  'revision',
1908  [ 'rev_user_text', 'rev_deleted' ],
1909  // $rev->getPage() returns null sometimes
1910  [ 'rev_page' => $rev->getTitle()->getArticleID() ],
1911  __METHOD__,
1912  [
1913  'USE INDEX' => [ 'revision' => 'page_timestamp' ],
1914  'ORDER BY' => 'rev_timestamp DESC',
1915  'LIMIT' => $wgShowRollbackEditCount + 1
1916  ]
1917  );
1918 
1919  $editCount = 0;
1920  $moreRevs = false;
1921  foreach ( $res as $row ) {
1922  if ( $rev->getUserText( Revision::RAW ) != $row->rev_user_text ) {
1923  if ( $verify &&
1924  ( $row->rev_deleted & Revision::DELETED_TEXT
1925  || $row->rev_deleted & Revision::DELETED_USER
1926  ) ) {
1927  // If the user or the text of the revision we might rollback
1928  // to is deleted in some way we can't rollback. Similar to
1929  // the sanity checks in WikiPage::commitRollback.
1930  return false;
1931  }
1932  $moreRevs = true;
1933  break;
1934  }
1935  $editCount++;
1936  }
1937 
1938  if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1939  // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1940  // and there weren't any other revisions. That means that the current user is the only
1941  // editor, so we can't rollback
1942  return false;
1943  }
1944  return $editCount;
1945  }
1946 
1955  public static function buildRollbackLink( $rev, IContextSource $context = null,
1956  $editCount = false
1957  ) {
1959 
1960  // To config which pages are affected by miser mode
1961  $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
1962 
1963  if ( $context === null ) {
1965  }
1966 
1967  $title = $rev->getTitle();
1968  $query = [
1969  'action' => 'rollback',
1970  'from' => $rev->getUserText(),
1971  'token' => $context->getUser()->getEditToken( [
1972  $title->getPrefixedText(),
1973  $rev->getUserText()
1974  ] ),
1975  ];
1976  if ( $context->getRequest()->getBool( 'bot' ) ) {
1977  $query['bot'] = '1';
1978  $query['hidediff'] = '1'; // bug 15999
1979  }
1980 
1981  $disableRollbackEditCount = false;
1982  if ( $wgMiserMode ) {
1983  foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1984  if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1985  $disableRollbackEditCount = true;
1986  break;
1987  }
1988  }
1989  }
1990 
1991  if ( !$disableRollbackEditCount
1992  && is_int( $wgShowRollbackEditCount )
1993  && $wgShowRollbackEditCount > 0
1994  ) {
1995  if ( !is_numeric( $editCount ) ) {
1996  $editCount = self::getRollbackEditCount( $rev, false );
1997  }
1998 
1999  if ( $editCount > $wgShowRollbackEditCount ) {
2000  $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )
2001  ->numParams( $wgShowRollbackEditCount )->parse();
2002  } else {
2003  $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
2004  }
2005 
2006  return self::link(
2007  $title,
2008  $editCount_output,
2009  [ 'title' => $context->msg( 'tooltip-rollback' )->text() ],
2010  $query,
2011  [ 'known', 'noclasses' ]
2012  );
2013  } else {
2014  return self::link(
2015  $title,
2016  $context->msg( 'rollbacklink' )->escaped(),
2017  [ 'title' => $context->msg( 'tooltip-rollback' )->text() ],
2018  $query,
2019  [ 'known', 'noclasses' ]
2020  );
2021  }
2022  }
2023 
2039  public static function formatTemplates( $templates, $preview = false,
2040  $section = false, $more = null
2041  ) {
2042  global $wgLang;
2043 
2044  $outText = '';
2045  if ( count( $templates ) > 0 ) {
2046  # Do a batch existence check
2047  $batch = new LinkBatch;
2048  foreach ( $templates as $title ) {
2049  $batch->addObj( $title );
2050  }
2051  $batch->execute();
2052 
2053  # Construct the HTML
2054  $outText = '<div class="mw-templatesUsedExplanation">';
2055  if ( $preview ) {
2056  $outText .= wfMessage( 'templatesusedpreview' )->numParams( count( $templates ) )
2057  ->parseAsBlock();
2058  } elseif ( $section ) {
2059  $outText .= wfMessage( 'templatesusedsection' )->numParams( count( $templates ) )
2060  ->parseAsBlock();
2061  } else {
2062  $outText .= wfMessage( 'templatesused' )->numParams( count( $templates ) )
2063  ->parseAsBlock();
2064  }
2065  $outText .= "</div><ul>\n";
2066 
2067  usort( $templates, 'Title::compare' );
2068  foreach ( $templates as $titleObj ) {
2069  $protected = '';
2070  $restrictions = $titleObj->getRestrictions( 'edit' );
2071  if ( $restrictions ) {
2072  // Check backwards-compatible messages
2073  $msg = null;
2074  if ( $restrictions === [ 'sysop' ] ) {
2075  $msg = wfMessage( 'template-protected' );
2076  } elseif ( $restrictions === [ 'autoconfirmed' ] ) {
2077  $msg = wfMessage( 'template-semiprotected' );
2078  }
2079  if ( $msg && !$msg->isDisabled() ) {
2080  $protected = $msg->parse();
2081  } else {
2082  // Construct the message from restriction-level-*
2083  // e.g. restriction-level-sysop, restriction-level-autoconfirmed
2084  $msgs = [];
2085  foreach ( $restrictions as $r ) {
2086  $msgs[] = wfMessage( "restriction-level-$r" )->parse();
2087  }
2088  $protected = wfMessage( 'parentheses' )
2089  ->rawParams( $wgLang->commaList( $msgs ) )->escaped();
2090  }
2091  }
2092  if ( $titleObj->quickUserCan( 'edit' ) ) {
2093  $editLink = self::link(
2094  $titleObj,
2095  wfMessage( 'editlink' )->escaped(),
2096  [],
2097  [ 'action' => 'edit' ]
2098  );
2099  } else {
2100  $editLink = self::link(
2101  $titleObj,
2102  wfMessage( 'viewsourcelink' )->escaped(),
2103  [],
2104  [ 'action' => 'edit' ]
2105  );
2106  }
2107  $outText .= '<li>' . self::link( $titleObj )
2108  . wfMessage( 'word-separator' )->escaped()
2109  . wfMessage( 'parentheses' )->rawParams( $editLink )->escaped()
2110  . wfMessage( 'word-separator' )->escaped()
2111  . $protected . '</li>';
2112  }
2113 
2114  if ( $more instanceof Title ) {
2115  $outText .= '<li>' . self::link( $more, wfMessage( 'moredotdotdot' ) ) . '</li>';
2116  } elseif ( $more ) {
2117  $outText .= "<li>$more</li>";
2118  }
2119 
2120  $outText .= '</ul>';
2121  }
2122  return $outText;
2123  }
2124 
2132  public static function formatHiddenCategories( $hiddencats ) {
2133 
2134  $outText = '';
2135  if ( count( $hiddencats ) > 0 ) {
2136  # Construct the HTML
2137  $outText = '<div class="mw-hiddenCategoriesExplanation">';
2138  $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
2139  $outText .= "</div><ul>\n";
2140 
2141  foreach ( $hiddencats as $titleObj ) {
2142  # If it's hidden, it must exist - no need to check with a LinkBatch
2143  $outText .= '<li>'
2144  . self::link( $titleObj, null, [], [], 'known' )
2145  . "</li>\n";
2146  }
2147  $outText .= '</ul>';
2148  }
2149  return $outText;
2150  }
2151 
2159  public static function formatSize( $size ) {
2160  global $wgLang;
2161  return htmlspecialchars( $wgLang->formatSize( $size ) );
2162  }
2163 
2178  public static function titleAttrib( $name, $options = null, array $msgParams = [] ) {
2179  $message = wfMessage( "tooltip-$name", $msgParams );
2180  if ( !$message->exists() ) {
2181  $tooltip = false;
2182  } else {
2183  $tooltip = $message->text();
2184  # Compatibility: formerly some tooltips had [alt-.] hardcoded
2185  $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2186  # Message equal to '-' means suppress it.
2187  if ( $tooltip == '-' ) {
2188  $tooltip = false;
2189  }
2190  }
2191 
2192  if ( $options == 'withaccess' ) {
2193  $accesskey = self::accesskey( $name );
2194  if ( $accesskey !== false ) {
2195  // Should be build the same as in jquery.accessKeyLabel.js
2196  if ( $tooltip === false || $tooltip === '' ) {
2197  $tooltip = wfMessage( 'brackets', $accesskey )->text();
2198  } else {
2199  $tooltip .= wfMessage( 'word-separator' )->text();
2200  $tooltip .= wfMessage( 'brackets', $accesskey )->text();
2201  }
2202  }
2203  }
2204 
2205  return $tooltip;
2206  }
2207 
2208  public static $accesskeycache;
2209 
2220  public static function accesskey( $name ) {
2221  if ( isset( self::$accesskeycache[$name] ) ) {
2222  return self::$accesskeycache[$name];
2223  }
2224 
2225  $message = wfMessage( "accesskey-$name" );
2226 
2227  if ( !$message->exists() ) {
2228  $accesskey = false;
2229  } else {
2230  $accesskey = $message->plain();
2231  if ( $accesskey === '' || $accesskey === '-' ) {
2232  # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2233  # attribute, but this is broken for accesskey: that might be a useful
2234  # value.
2235  $accesskey = false;
2236  }
2237  }
2238 
2239  self::$accesskeycache[$name] = $accesskey;
2240  return self::$accesskeycache[$name];
2241  }
2242 
2256  public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
2257  $canHide = $user->isAllowed( 'deleterevision' );
2258  if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2259  return '';
2260  }
2261 
2262  if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
2263  return Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2264  } else {
2265  if ( $rev->getId() ) {
2266  // RevDelete links using revision ID are stable across
2267  // page deletion and undeletion; use when possible.
2268  $query = [
2269  'type' => 'revision',
2270  'target' => $title->getPrefixedDBkey(),
2271  'ids' => $rev->getId()
2272  ];
2273  } else {
2274  // Older deleted entries didn't save a revision ID.
2275  // We have to refer to these by timestamp, ick!
2276  $query = [
2277  'type' => 'archive',
2278  'target' => $title->getPrefixedDBkey(),
2279  'ids' => $rev->getTimestamp()
2280  ];
2281  }
2282  return Linker::revDeleteLink( $query,
2283  $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2284  }
2285  }
2286 
2297  public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2298  $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2299  $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2300  $html = wfMessage( $msgKey )->escaped();
2301  $tag = $restricted ? 'strong' : 'span';
2302  $link = self::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2303  return Xml::tags(
2304  $tag,
2305  [ 'class' => 'mw-revdelundel-link' ],
2306  wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2307  );
2308  }
2309 
2318  public static function revDeleteLinkDisabled( $delete = true ) {
2319  $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2320  $html = wfMessage( $msgKey )->escaped();
2321  $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2322  return Xml::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2323  }
2324 
2325  /* Deprecated methods */
2326 
2335  public static function tooltipAndAccesskeyAttribs( $name, array $msgParams = [] ) {
2336  # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2337  # no attribute" instead of "output '' as value for attribute", this
2338  # would be three lines.
2339  $attribs = [
2340  'title' => self::titleAttrib( $name, 'withaccess', $msgParams ),
2341  'accesskey' => self::accesskey( $name )
2342  ];
2343  if ( $attribs['title'] === false ) {
2344  unset( $attribs['title'] );
2345  }
2346  if ( $attribs['accesskey'] === false ) {
2347  unset( $attribs['accesskey'] );
2348  }
2349  return $attribs;
2350  }
2351 
2358  public static function tooltip( $name, $options = null ) {
2359  # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2360  # no attribute" instead of "output '' as value for attribute", this
2361  # would be two lines.
2362  $tooltip = self::titleAttrib( $name, $options );
2363  if ( $tooltip === false ) {
2364  return '';
2365  }
2366  return Xml::expandAttributes( [
2367  'title' => $tooltip
2368  ] );
2369  }
2370 
2371 }
2372 
static generateTOC($tree, $lang=false)
Generate a table of contents from a section tree.
Definition: Linker.php:1762
const FOR_THIS_USER
Definition: Revision.php:84
getFragment()
Get the Title fragment (i.e.
Definition: Title.php:1353
static tocLineEnd()
End a Table Of Contents line.
Definition: Linker.php:1734
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition: hooks.txt:1798
Interface for objects which can provide a MediaWiki context on request.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
static revComment(Revision $rev, $local=false, $isPublic=false)
Wrap and format the given revision's comment block, if the current user is allowed to view it...
Definition: Linker.php:1656
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
static tocList($toc, $lang=false)
Wraps the TOC in a table and provides the hide/collapse javascript.
Definition: Linker.php:1745
static formatAutocomments($comment, $title=null, $local=false, $wikiId=null)
Converts autogenerated comments in edit summaries into section links.
Definition: Linker.php:1322
static processResponsiveImages($file, $thumb, $hp)
Process responsive images: add 1.5x and 2x subimages to the thumbnail, where applicable.
Definition: Linker.php:878
the array() calling protocol came about after MediaWiki 1.4rc1.
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1418
static linkKnown($target, $html=null, $customAttribs=[], $query=[], $options=[ 'known', 'noclasses'])
Identical to link(), except $options defaults to 'known'.
Definition: Linker.php:264
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2321
hasFragment()
Whether the link target has a fragment.
$context
Definition: load.php:44
static getRevDeleteLink(User $user, Revision $rev, Title $title)
Get a revision-deletion link, or disabled link, or nothing, depending on user permissions & the setti...
Definition: Linker.php:2256
const NS_MAIN
Definition: Defines.php:69
$success
getText()
Get the text form (spaces not underscores) of the main part.
Definition: Title.php:893
static linkText($target)
Default text of the links to the Title $target.
Definition: Linker.php:381
static buildRollbackLink($rev, IContextSource $context=null, $editCount=false)
Build a raw rollback link, useful for collections of "tool" links.
Definition: Linker.php:1955
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static getTitleFor($name, $subpage=false, $fragment= '')
Get a localised Title object for a specified special page name.
Definition: SpecialPage.php:75
getTimestamp()
Definition: Revision.php:1152
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for except in special pages derived from QueryPage It s a common pitfall for new developers to submit code containing SQL queries which examine huge numbers of rows Remember that COUNT * is(N), counting rows in atable is like counting beans in a bucket.------------------------------------------------------------------------Replication------------------------------------------------------------------------The largest installation of MediaWiki, Wikimedia, uses a large set ofslave MySQL servers replicating writes made to a master MySQL server.Itis important to understand the issues associated with this setup if youwant to write code destined for Wikipedia.It's often the case that the best algorithm to use for a given taskdepends on whether or not replication is in use.Due to our unabashedWikipedia-centrism, we often just use the replication-friendly version, but if you like, you can use wfGetLB() ->getServerCount() > 1 tocheck to see if replication is in use.===Lag===Lag primarily occurs when large write queries are sent to the master.Writes on the master are executed in parallel, but they are executed inserial when they are replicated to the slaves.The master writes thequery to the binlog when the transaction is committed.The slaves pollthe binlog and start executing the query as soon as it appears.They canservice reads while they are performing a write query, but will not readanything more from the binlog and thus will perform no more writes.Thismeans that if the write query runs for a long time, the slaves will lagbehind the master for the time it takes for the write query to complete.Lag can be exacerbated by high read load.MediaWiki's load balancer willstop sending reads to a slave when it is lagged by more than 30 seconds.If the load ratios are set incorrectly, or if there is too much loadgenerally, this may lead to a slave permanently hovering around 30seconds lag.If all slaves are lagged by more than 30 seconds, MediaWiki will stopwriting to the database.All edits and other write operations will berefused, with an error returned to the user.This gives the slaves achance to catch up.Before we had this mechanism, the slaves wouldregularly lag by several minutes, making review of recent editsdifficult.In addition to this, MediaWiki attempts to ensure that the user seesevents occurring on the wiki in chronological order.A few seconds of lagcan be tolerated, as long as the user sees a consistent picture fromsubsequent requests.This is done by saving the master binlog positionin the session, and then at the start of each request, waiting for theslave to catch up to that position before doing any reads from it.Ifthis wait times out, reads are allowed anyway, but the request isconsidered to be in"lagged slave mode".Lagged slave mode can bechecked by calling wfGetLB() ->getLaggedSlaveMode().The onlypractical consequence at present is a warning displayed in the pagefooter.===Lag avoidance===To avoid excessive lag, queries which write large numbers of rows shouldbe split up, generally to write one row at a time.Multi-row INSERT...SELECT queries are the worst offenders should be avoided altogether.Instead do the select first and then the insert.===Working with lag===Despite our best efforts, it's not practical to guarantee a low-lagenvironment.Lag will usually be less than one second, but mayoccasionally be up to 30 seconds.For scalability, it's very importantto keep load on the master low, so simply sending all your queries tothe master is not the answer.So when you have a genuine need forup-to-date data, the following approach is advised:1) Do a quick query to the master for a sequence number or timestamp 2) Run the full query on the slave and check if it matches the data you gotfrom the master 3) If it doesn't, run the full query on the masterTo avoid swamping the master every time the slaves lag, use of thisapproach should be kept to a minimum.In most cases you should just readfrom the slave and let the user deal with the delay.------------------------------------------------------------------------Lock contention------------------------------------------------------------------------Due to the high write rate on Wikipedia(and some other wikis), MediaWiki developers need to be very careful to structure their writesto avoid long-lasting locks.By default, MediaWiki opens a transactionat the first query, and commits it before the output is sent.Locks willbe held from the time when the query is done until the commit.So youcan reduce lock time by doing as much processing as possible before youdo your write queries.Often this approach is not good enough, and it becomes necessary toenclose small groups of queries in their own transaction.Use thefollowing syntax:$dbw=wfGetDB(DB_MASTER
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1798
msg()
Get a Message object with context set.
static rawElement($element, $attribs=[], $contents= '')
Returns an HTML element in a string.
Definition: Html.php:210
static expandAttributes($attribs)
Given an array of ('attributename' => 'value'), it generates the code to set the XML attributes : att...
Definition: Xml.php:67
if(!isset($args[0])) $lang
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
static formatRevisionSize($size)
Definition: Linker.php:1678
static normaliseSpecialPage(LinkTarget $target)
Definition: Linker.php:452
static fnamePart($url)
Returns the filename part of an url.
Definition: Linker.php:473
$comment
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling but I prefer the flexibility This should also do the output encoding The system allocates a global one in $wgOut Title Represents the title of an and does all the work of translating among various forms such as plain database etc For and for historical reasons
Definition: design.txt:25
static makeSelfLinkObj($nt, $html= '', $query= '', $trail= '', $prefix= '')
Make appropriate markup for a link to the current article.
Definition: Linker.php:409
static newFromId($id)
Static factory method for creation from a given user ID.
Definition: User.php:591
const NS_SPECIAL
Definition: Defines.php:58
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2548
static escapeRegexReplacement($string)
Escape a string to make it suitable for inclusion in a preg_replace() replacement parameter...
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1449
static exists($index)
Returns whether the specified namespace exists.
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:277
Represents a title within MediaWiki.
Definition: Title.php:34
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
static newFromLinkTarget(LinkTarget $linkTarget)
Create a new Title from a LinkTarget.
Definition: Title.php:251
magic word & $parser
Definition: hooks.txt:2321
static blockLink($userId, $userText)
Definition: Linker.php:1208
static tooltipAndAccesskeyAttribs($name, array $msgParams=[])
Returns the attributes for the tooltip and access key.
Definition: Linker.php:2335
getNamespace()
Get the namespace index.
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1612
static formatTemplates($templates, $preview=false, $section=false, $more=null)
Returns HTML for the "templates used on this page" list.
Definition: Linker.php:2039
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
Definition: design.txt:56
the value to return A Title object or null for latest to be modified or replaced by the hook handler or if authentication is not possible after cache objects are set for highlighting & $link
Definition: hooks.txt:2581
getFragment()
Get the link fragment (i.e.
$batch
Definition: linkcache.txt:23
static getRollbackEditCount($rev, $verify)
This function will return the number of revisions which a rollback would revert and, if $verify is set it will verify that a revision can be reverted (that the user isn't the only contributor and the revision we might rollback to isn't deleted).
Definition: Linker.php:1896
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:1818
$wgEnableUploads
Uploads have to be specially set up to be secure.
static makeMediaLinkObj($title, $html= '', $time=false)
Create a direct link to a given uploaded file.
Definition: Linker.php:978
static makeBrokenImageLinkObj($title, $label= '', $query= '', $unused1= '', $unused2= '', $time=false)
Make a "broken" link to an image.
Definition: Linker.php:912
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:31
static getLinkAttributesInternal($title, $class)
Common code for getLinkAttributesX functions.
Definition: Linker.php:117
null means default & $customAttribs
Definition: hooks.txt:1798
wfCgiToArray($query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
createFragmentTarget($fragment)
Creates a new LinkTarget for a different fragment of the same page.
isDeleted($field)
Definition: Revision.php:979
static normalizeSectionNameWhitespace($section)
Normalizes whitespace in a section name, such as might be returned by Parser::stripSectionName(), for use in the id's that are used for section links.
Definition: Sanitizer.php:1342
const PROTO_HTTPS
Definition: Defines.php:262
static getForeignURL($wikiID, $page, $fragmentId=null)
Convenience to get a url to a page on a foreign wiki.
Definition: WikiMap.php:160
getTitle()
Returns the title of the page associated with this entry or null.
Definition: Revision.php:773
isExternal()
Is this Title interwiki?
Definition: Title.php:810
static getMain()
Static methods.
$wgUploadMissingFileUrl
Point the upload link for missing files to an external URL, as with $wgUploadNavigationUrl.
static normalizeSubpageLink($contextTitle, $target, &$text)
Definition: Linker.php:1547
static getCanonicalName($index)
Returns the canonical (English) name for a given index.
wfAppendQuery($url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
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:2178
isAllowed($action= '')
Internal mechanics of testing a permission.
Definition: User.php:3410
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:1413
Some internal bits split of from Skin.php.
Definition: Linker.php:33
wfWarn($msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
getId()
Get revision ID.
Definition: Revision.php:716
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1004
$wgThumbUpright
Adjust width of upright images when parameter 'upright' is used This allows a nicer look for upright ...
static escapeHtmlAllowEntities($html)
Given HTML input, escape with htmlspecialchars but un-escape entities.
Definition: Sanitizer.php:1223
const NS_MEDIA
Definition: Defines.php:57
getLocalURL($query= '', $query2=false)
Get a URL with no fragment or server name (relative URL) from a Title object.
Definition: Title.php:1707
$res
Definition: database.txt:21
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:59
$wgMiserMode
Disable database-intensive features.
static accesskey($name)
Given the id of an interface element, constructs the appropriate accesskey attribute from the system ...
Definition: Linker.php:2220
static mergeAttributes($a, $b)
Merge two sets of HTML attributes.
Definition: Sanitizer.php:839
static emailLink($userId, $userText)
Definition: Linker.php:1219
const TOOL_LINKS_NOBLOCK
Flags for userToolLinks()
Definition: Linker.php:37
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock()-offset Set to overwrite offset parameter in $wgRequest set to ''to unsetoffset-wrap String Wrap the message in html(usually something like"&lt
getDBkey()
Get the main part with underscores.
static revDeleteLinkDisabled($delete=true)
Creates a dead (show/hide) link for deleting revisions/log entries.
Definition: Linker.php:2318
$params
static makeHeadline($level, $attribs, $anchor, $html, $link, $legacyAnchor=false)
Create a headline for content.
Definition: Linker.php:1799
$wgThumbLimits
Adjust thumbnails on image pages according to a user setting.
wfDeprecated($function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
userCan($field, User $user=null)
Determine if the current user is allowed to view a particular field of this revision, if it's marked as deleted.
Definition: Revision.php:1692
getComment($audience=self::FOR_PUBLIC, User $user=null)
Fetch revision comment if it's available to the specified audience.
Definition: Revision.php:905
static makeTitleSafe($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:548
Some information about database access in MediaWiki By Tim January Database layout For information about the MediaWiki database such as a description of the tables and their please see
Definition: database.txt:2
const DELETED_RESTRICTED
Definition: Revision.php:79
const DB_SLAVE
Definition: Defines.php:46
getTargetLanguage()
Get the target language for the content being parsed.
Definition: Parser.php:857
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
static hasSubpages($index)
Does the namespace allow subpages?
static tocUnindent($level)
Finish one or more sublevels on the Table of Contents.
Definition: Linker.php:1703
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
static tocLine($anchor, $tocline, $tocnumber, $level, $sectionIndex=false)
parameter level defines if we are on an indentation level
Definition: Linker.php:1717
const PROTO_RELATIVE
Definition: Defines.php:263
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books $tag
Definition: hooks.txt:965
const NS_FILE
Definition: Defines.php:75
static makeImageLink(Parser $parser, Title $title, $file, $frameParams=[], $handlerParams=[], $time=false, $query="", $widthOption=null)
Given parameters derived from [[Image:Foo|options...]], generate the HTML that that syntax inserts in...
Definition: Linker.php:545
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1584
static makeCommentLink(Title $title, $text, $wikiId=null, $options=[])
Generates a link to the given Title.
Definition: Linker.php:1521
static userToolLinksRedContribs($userId, $userText, $edits=null)
Alias for userToolLinks( $userId, $userText, true );.
Definition: Linker.php:1188
const RAW
Definition: Revision.php:85
static revUserLink($rev, $isPublic=false)
Generate a user link if the current user is allowed to view it.
Definition: Linker.php:1231
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers temp or archived zone change it to an object instance and return false override the list derivative used the name of the old file when set the default code will be skipped true if there is text before this autocomment $auto
Definition: hooks.txt:1306
const PROTO_HTTP
Definition: Defines.php:261
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:1290
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
Definition: hooks.txt:2715
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
static link($target, $html=null, $customAttribs=[], $query=[], $options=[])
This function returns an HTML link to the given target.
Definition: Linker.php:195
$wgSVGMaxSize
Don't scale a SVG larger than this.
const DELETED_TEXT
Definition: Revision.php:76
static getImageLinkMTOParams($frameParams, $query= '', $parser=null)
Get the link parameters for MediaTransformOutput::toHtml() from given frame parameters supplied by th...
Definition: Linker.php:689
static tooltip($name, $options=null)
Returns raw bits of HTML, use titleAttrib()
Definition: Linker.php:2358
static userLink($userId, $userName, $altUserName=false)
Make user link (or user contributions for unregistered users)
Definition: Linker.php:1102
static makeExternalLink($url, $text, $escape=true, $linktype= '', $attribs=[], $title=null)
Make an external link.
Definition: Linker.php:1052
static getExternalLinkRel($url=false, $title=null)
Get the rel attribute for a particular external link.
Definition: Parser.php:1857
getVisibility()
Get the deletion bitfield of the revision.
Definition: Revision.php:988
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could change
Definition: distributors.txt:9
static tags($element, $attribs=null, $contents)
Same as Xml::element(), but does not escape contents.
Definition: Xml.php:131
const DELETED_USER
Definition: Revision.php:78
controlled by $wgMainCacheType controlled by $wgParserCacheType controlled by $wgMessageCacheType If you set CACHE_NONE to one of the three control default value for MediaWiki still create a but requests to it are no ops and we always fall through to the database If the cache daemon can t be it should also disable itself fairly smoothly By $wgMemc is used but when it is $parserMemc or $messageMemc this is mentioned below
Definition: memcached.txt:96
static getInternalLinkAttributesObj($nt, $unused=null, $class= '', $title=false)
Get the appropriate HTML attributes to add to the "a" element of an internal link, given the Title object for the page we want to link to.
Definition: Linker.php:98
static resolveAlias($alias)
Given a special page name with a possible subpage, return an array where the first element is the spe...
static generateRollback($rev, IContextSource $context=null, $options=[ 'verify'])
Generate a rollback link for a given revision.
Definition: Linker.php:1857
static formatHiddenCategories($hiddencats)
Returns HTML for the "hidden categories on this page" list.
Definition: Linker.php:2132
static makeThumbLink2(Title $title, $file, $frameParams=[], $handlerParams=[], $time=false, $query="")
Definition: Linker.php:752
static userTalkLink($userId, $userText)
Definition: Linker.php:1197
Cache for article titles (prefixed DB keys) and ids linked from one source.
Definition: LinkCache.php:29
static getUploadUrl($destFile, $query= '')
Get the URL to upload a certain file.
Definition: Linker.php:953
static makeMediaLinkFile(Title $title, $file, $html= '')
Create a direct link to a given uploaded file.
Definition: Linker.php:994
static userToolLinks($userId, $userText, $redContribsWhenNoEdits=false, $flags=0, $edits=null)
Generate standard user tool links (talk, contributions, block link, etc.)
Definition: Linker.php:1133
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template to be included in the link
Definition: hooks.txt:2715
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition: design.txt:56
static formatSize($size)
Format a size in bytes for output, using an appropriate unit (B, KB, MB or GB) according to the magni...
Definition: Linker.php:2159
see documentation in includes Linker php for Linker::makeImageLink & $handlerParams
Definition: hooks.txt:1610
static tocIndent()
Add another level to the Table of Contents.
Definition: Linker.php:1693
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second redirect
static getInterwikiLinkAttributes($title, $unused=null, $class= 'external')
Get the appropriate HTML attributes to add to the "a" element of an interwiki link.
Definition: Linker.php:52
static getInternalLinkAttributes($title, $unused=null, $class= '')
Get the appropriate HTML attributes to add to the "a" element of an internal link.
Definition: Linker.php:77
static getInvalidTitleDescription(IContextSource $context, $namespace, $title)
Get a message saying that an invalid title was encountered.
Definition: Linker.php:432
$wgShowRollbackEditCount
The $wgShowRollbackEditCount variable is used to show how many edits can be rolled back...
if(!$wgRequest->checkUrlExtension()) if(!$wgEnableAPI) $wgTitle
Definition: api.php:57
const DELETED_COMMENT
Definition: Revision.php:77
static commentBlock($comment, $title=null, $local=false, $wikiId=null)
Wrap a comment in standard punctuation and formatting if it's non-empty, otherwise return empty strin...
Definition: Linker.php:1632
static makeThumbLinkObj(Title $title, $file, $label= '', $alt, $align= 'right', $params=[], $framed=false, $manualthumb="")
Make HTML for a thumbnail including image, border and caption.
Definition: Linker.php:726
static getDefaultOption($opt)
Get a given default option value.
Definition: User.php:1547
static $accesskeycache
Definition: Linker.php:2208
$wgUploadNavigationUrl
Point the upload navigation link to an external URL Useful if you want to use a shared repository by ...
$wgResponsiveImages
Generate and use thumbnails suitable for screens with 1.5 and 2.0 pixel densities.
const NS_USER_TALK
Definition: Defines.php:72
static linkAttribs($target, $attribs, $options)
Returns the array of attributes used when linking to the Title $target.
Definition: Linker.php:317
static revUserTools($rev, $isPublic=false)
Generate a user tool link cluster if the current user is allowed to view it.
Definition: Linker.php:1252
return true to allow those checks to and false if checking is done remove or add to the links of a group of changes in EnhancedChangesList Hook subscribers can return false to omit this line from recentchanges use this to change the tables headers temp or archived zone change it to an object instance and return false override the list derivative used the name of the old file when set the default code will be skipped $pre
Definition: hooks.txt:1306
static makeExternalImage($url, $alt= '')
Return the code for images which were added via external links, via Parser::maybeMakeExternalImage()...
Definition: Linker.php:492
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:1034
static element($element, $attribs=[], $contents= '')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:230
wfFindFile($title, $options=[])
Find a file.
static revDeleteLink($query=[], $restricted=false, $delete=true)
Creates a (show/hide) link for deleting revisions/log entries.
Definition: Linker.php:2297
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk page
Definition: hooks.txt:2338
static getLinkColour($t, $threshold)
Return the CSS colour of a known link.
Definition: Linker.php:139
static & makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:524
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing & $attribs
Definition: hooks.txt:1798
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2338
wfGetLangObj($langcode=false)
Return a Language object from $langcode.
getPrefixedDBkey()
Get the prefixed database key form.
Definition: Title.php:1437
const TOOL_LINKS_EMAIL
Definition: Linker.php:38
static prettifyIP($ip)
Prettify an IP for display to end users.
Definition: IP.php:201
$wgUser
Definition: Setup.php:794
static linkUrl(LinkTarget $target, $query, $options)
Returns the Url used to link to a Title.
Definition: Linker.php:279
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310