3 * Some internal bits split of from Skin.php. These functions are used
4 * for primarily page content: links, embedded images, table of contents. Links
5 * are also used in the skin.
12 * Flags for userToolLinks()
14 const TOOL_LINKS_NOBLOCK
= 1;
15 const TOOL_LINKS_EMAIL
= 2;
18 * Get the appropriate HTML attributes to add to the "a" element of an ex-
19 * ternal link, as created by [wikisyntax].
21 * @param $class String: the contents of the class attribute; if an empty
22 * string is passed, which is the default value, defaults to 'external'.
24 * @deprecated since 1.18 Just pass the external class directly to something using Html::expandAttributes
26 static function getExternalLinkAttributes( $class = 'external' ) {
27 wfDeprecated( __METHOD__
, '1.18' );
28 return self
::getLinkAttributesInternal( '', $class );
32 * Get the appropriate HTML attributes to add to the "a" element of an in-
35 * @param $title String: the title text for the link, URL-encoded (???) but
37 * @param $unused String: unused
38 * @param $class String: the contents of the class attribute; if an empty
39 * string is passed, which is the default value, defaults to 'external'.
42 static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
45 # @todo FIXME: We have a whole bunch of handling here that doesn't happen in
46 # getExternalLinkAttributes, why?
47 $title = urldecode( $title );
48 $title = $wgContLang->checkTitleEncoding( $title );
49 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
51 return self
::getLinkAttributesInternal( $title, $class );
55 * Get the appropriate HTML attributes to add to the "a" element of an in-
58 * @param $title String: the title text for the link, URL-encoded (???) but
60 * @param $unused String: unused
61 * @param $class String: the contents of the class attribute, default none
64 static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
65 $title = urldecode( $title );
66 $title = str_replace( '_', ' ', $title );
67 return self
::getLinkAttributesInternal( $title, $class );
71 * Get the appropriate HTML attributes to add to the "a" element of an in-
72 * ternal link, given the Title object for the page we want to link to.
75 * @param $unused String: unused
76 * @param $class String: the contents of the class attribute, default none
77 * @param $title Mixed: optional (unescaped) string to use in the title
78 * attribute; if false, default to the name of the page we're linking to
81 static function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
82 if ( $title === false ) {
83 $title = $nt->getPrefixedText();
85 return self
::getLinkAttributesInternal( $title, $class );
89 * Common code for getLinkAttributesX functions
91 * @param $title string
92 * @param $class string
96 private static function getLinkAttributesInternal( $title, $class ) {
97 $title = htmlspecialchars( $title );
98 $class = htmlspecialchars( $class );
100 if ( $class != '' ) {
101 $r .= " class=\"$class\"";
103 if ( $title != '' ) {
104 $r .= " title=\"$title\"";
110 * Return the CSS colour of a known link
112 * @param $t Title object
113 * @param $threshold Integer: user defined threshold
114 * @return String: CSS class
116 public static function getLinkColour( $t, $threshold ) {
118 if ( $t->isRedirect() ) {
120 $colour = 'mw-redirect';
121 } elseif ( $threshold > 0 &&
122 $t->exists() && $t->getLength() < $threshold &&
123 $t->isContentPage() ) {
131 * This function returns an HTML link to the given target. It serves a few
133 * 1) If $target is a Title, the correct URL to link to will be figured
135 * 2) It automatically adds the usual classes for various types of link
136 * targets: "new" for red links, "stub" for short articles, etc.
137 * 3) It escapes all attribute values safely so there's no risk of XSS.
138 * 4) It provides a default tooltip if the target is a Title (the page
139 * name of the target).
140 * link() replaces the old functions in the makeLink() family.
142 * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
143 * You can call it using this if you want to keep compat with these:
144 * $linker = class_exists( 'DummyLinker' ) ? new DummyLinker() : new Linker();
145 * $linker->link( ... );
147 * @param $target Title Can currently only be a Title, but this may
148 * change to support Images, literal URLs, etc.
149 * @param $html string The HTML contents of the <a> element, i.e.,
150 * the link text. This is raw HTML and will not be escaped. If null,
151 * defaults to the prefixed text of the Title; or if the Title is just a
152 * fragment, the contents of the fragment.
153 * @param $customAttribs array A key => value array of extra HTML attri-
154 * butes, such as title and class. (href is ignored.) Classes will be
155 * merged with the default classes, while other attributes will replace
156 * default attributes. All passed attribute values will be HTML-escaped.
157 * A false attribute value means to suppress that attribute.
158 * @param $query array The query string to append to the URL
159 * you're linking to, in key => value array form. Query keys and values
160 * will be URL-encoded.
161 * @param $options string|array String or array of strings:
162 * 'known': Page is known to exist, so don't check if it does.
163 * 'broken': Page is known not to exist, so don't check if it does.
164 * 'noclasses': Don't add any classes automatically (includes "new",
165 * "stub", "mw-redirect", "extiw"). Only use the class attribute
166 * provided, if any, so you get a simple blue link with no funny i-
168 * 'forcearticlepath': Use the article path always, even with a querystring.
169 * Has compatibility issues on some setups, so avoid wherever possible.
170 * @return string HTML <a> attribute
172 public static function link(
173 $target, $html = null, $customAttribs = array(), $query = array(), $options = array()
175 wfProfileIn( __METHOD__
);
176 if ( !$target instanceof Title
) {
177 wfProfileOut( __METHOD__
);
178 return "<!-- ERROR -->$html";
180 $options = (array)$options;
182 $dummy = new DummyLinker
; // dummy linker instance for bc on the hooks
185 if ( !wfRunHooks( 'LinkBegin', array( $dummy, $target, &$html,
186 &$customAttribs, &$query, &$options, &$ret ) ) ) {
187 wfProfileOut( __METHOD__
);
191 # Normalize the Title if it's a special page
192 $target = self
::normaliseSpecialPage( $target );
194 # If we don't know whether the page exists, let's find out.
195 wfProfileIn( __METHOD__
. '-checkPageExistence' );
196 if ( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
197 if ( $target->isKnown() ) {
198 $options[] = 'known';
200 $options[] = 'broken';
203 wfProfileOut( __METHOD__
. '-checkPageExistence' );
206 if ( in_array( "forcearticlepath", $options ) && $query ) {
211 # Note: we want the href attribute first, for prettiness.
212 $attribs = array( 'href' => self
::linkUrl( $target, $query, $options ) );
213 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
214 $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
217 $attribs = array_merge(
219 self
::linkAttribs( $target, $customAttribs, $options )
221 if ( is_null( $html ) ) {
222 $html = self
::linkText( $target );
226 if ( wfRunHooks( 'LinkEnd', array( $dummy, $target, $options, &$html, &$attribs, &$ret ) ) ) {
227 $ret = Html
::rawElement( 'a', $attribs, $html );
230 wfProfileOut( __METHOD__
);
235 * Identical to link(), except $options defaults to 'known'.
238 public static function linkKnown(
239 $target, $html = null, $customAttribs = array(),
240 $query = array(), $options = array( 'known', 'noclasses' ) )
242 return self
::link( $target, $html, $customAttribs, $query, $options );
246 * Returns the Url used to link to a Title
248 * @param $target Title
249 * @param $query Array: query parameters
250 * @param $options Array
253 private static function linkUrl( $target, $query, $options ) {
254 wfProfileIn( __METHOD__
);
255 # We don't want to include fragments for broken links, because they
256 # generally make no sense.
257 if ( in_array( 'broken', $options ) && $target->mFragment
!== '' ) {
258 $target = clone $target;
259 $target->mFragment
= '';
262 # If it's a broken link, add the appropriate query pieces, unless
263 # there's already an action specified, or unless 'edit' makes no sense
264 # (i.e., for a nonexistent special page).
265 if ( in_array( 'broken', $options ) && empty( $query['action'] )
266 && !$target->isSpecialPage() ) {
267 $query['action'] = 'edit';
268 $query['redlink'] = '1';
270 $ret = $target->getLinkURL( $query );
271 wfProfileOut( __METHOD__
);
276 * Returns the array of attributes used when linking to the Title $target
278 * @param $target Title
284 private static function linkAttribs( $target, $attribs, $options ) {
285 wfProfileIn( __METHOD__
);
289 if ( !in_array( 'noclasses', $options ) ) {
290 wfProfileIn( __METHOD__
. '-getClasses' );
291 # Now build the classes.
294 if ( in_array( 'broken', $options ) ) {
298 if ( $target->isExternal() ) {
299 $classes[] = 'extiw';
302 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
303 $colour = self
::getLinkColour( $target, $wgUser->getStubThreshold() );
304 if ( $colour !== '' ) {
305 $classes[] = $colour; # mw-redirect or stub
308 if ( $classes != array() ) {
309 $defaults['class'] = implode( ' ', $classes );
311 wfProfileOut( __METHOD__
. '-getClasses' );
314 # Get a default title attribute.
315 if ( $target->getPrefixedText() == '' ) {
316 # A link like [[#Foo]]. This used to mean an empty title
317 # attribute, but that's silly. Just don't output a title.
318 } elseif ( in_array( 'known', $options ) ) {
319 $defaults['title'] = $target->getPrefixedText();
321 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
324 # Finally, merge the custom attribs with the default ones, and iterate
325 # over that, deleting all "false" attributes.
327 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
328 foreach ( $merged as $key => $val ) {
329 # A false value suppresses the attribute, and we don't want the
330 # href attribute to be overridden.
331 if ( $key != 'href' and $val !== false ) {
335 wfProfileOut( __METHOD__
);
340 * Default text of the links to the Title $target
342 * @param $target Title
346 private static function linkText( $target ) {
347 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
348 if ( !$target instanceof Title
) {
352 # If the target is just a fragment, with no title, we return the frag-
353 # ment text. Otherwise, we return the title text itself.
354 if ( $target->getPrefixedText() === '' && $target->getFragment() !== '' ) {
355 return htmlspecialchars( $target->getFragment() );
357 return htmlspecialchars( $target->getPrefixedText() );
361 * Generate either a normal exists-style link or a stub link, depending
362 * on the given page size.
364 * @param $size Integer
365 * @param $nt Title object.
366 * @param $text String
367 * @param $query String
368 * @param $trail String
369 * @param $prefix String
370 * @return string HTML of link
371 * @deprecated since 1.17
373 static function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
375 wfDeprecated( __METHOD__
, '1.17' );
377 $threshold = $wgUser->getStubThreshold();
378 $colour = ( $size < $threshold ) ?
'stub' : '';
379 // @todo FIXME: Replace deprecated makeColouredLinkObj by link()
380 return self
::makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
384 * Make appropriate markup for a link to the current article. This is currently rendered
385 * as the bold link text. The calling sequence is the same as the other make*LinkObj static functions,
386 * despite $query not being used.
392 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
394 $html = htmlspecialchars( $nt->getPrefixedText() );
396 list( $inside, $trail ) = self
::splitTrail( $trail );
397 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
401 * Get a message saying that an invalid title was encountered.
402 * This should be called after a method like Title::makeTitleSafe() returned
403 * a value indicating that the title object is invalid.
405 * @param $context IContextSource context to use to get the messages
406 * @param $namespace int Namespace number
407 * @param $title string Text of the title, without the namespace part
409 public static function getInvalidTitleDescription( IContextSource
$context, $namespace, $title ) {
412 // First we check whether the namespace exists or not.
413 if ( MWNamespace
::exists( $namespace ) ) {
414 if ( $namespace == NS_MAIN
) {
415 $name = $context->msg( 'blanknamespace' )->text();
417 $name = $wgContLang->getFormattedNsText( $namespace );
419 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
421 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
426 * @param $title Title
429 static function normaliseSpecialPage( Title
$title ) {
430 if ( $title->isSpecialPage() ) {
431 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
435 $ret = SpecialPage
::getTitleFor( $name, $subpage );
436 $ret->mFragment
= $title->getFragment();
444 * Returns the filename part of an url.
445 * Used as alternative text for external images.
451 private static function fnamePart( $url ) {
452 $basename = strrchr( $url, '/' );
453 if ( false === $basename ) {
456 $basename = substr( $basename, 1 );
462 * Return the code for images which were added via external links,
463 * via Parser::maybeMakeExternalImage().
470 public static function makeExternalImage( $url, $alt = '' ) {
472 $alt = self
::fnamePart( $url );
475 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
477 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
480 return Html
::element( 'img',
487 * Given parameters derived from [[Image:Foo|options...]], generate the
488 * HTML that that syntax inserts in the page.
490 * @param $title Title object
491 * @param $file File object, or false if it doesn't exist
492 * @param $frameParams Array: associative array of parameters external to the media handler.
493 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
494 * will often be false.
495 * thumbnail If present, downscale and frame
496 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
497 * framed Shows image in original size in a frame
498 * frameless Downscale but don't frame
499 * upright If present, tweak default sizes for portrait orientation
500 * upright_factor Fudge factor for "upright" tweak (default 0.75)
501 * border If present, show a border around the image
502 * align Horizontal alignment (left, right, center, none)
503 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
504 * bottom, text-bottom)
505 * alt Alternate text for image (i.e. alt attribute). Plain text.
506 * caption HTML for image caption.
507 * link-url URL to link to
508 * link-title Title object to link to
509 * link-target Value for the target attribue, only with link-url
510 * no-link Boolean, suppress description link
512 * @param $handlerParams Array: associative array of media handler parameters, to be passed
513 * to transform(). Typical keys are "width" and "page".
514 * @param $time String: timestamp of the file, set as false for current
515 * @param $query String: query params for desc url
516 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
517 * @return String: HTML for an image, with links, wrappers, etc.
519 public static function makeImageLink2( Title
$title, $file, $frameParams = array(),
520 $handlerParams = array(), $time = false, $query = "", $widthOption = null )
523 $dummy = new DummyLinker
;
524 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
525 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
529 if ( $file && !$file->allowInlineDisplay() ) {
530 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
531 return self
::link( $title );
536 $hp =& $handlerParams;
538 // Clean up parameters
539 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
540 if ( !isset( $fp['align'] ) ) {
543 if ( !isset( $fp['alt'] ) ) {
546 if ( !isset( $fp['title'] ) ) {
550 $prefix = $postfix = '';
552 if ( 'center' == $fp['align'] ) {
553 $prefix = '<div class="center">';
555 $fp['align'] = 'none';
557 if ( $file && !isset( $hp['width'] ) ) {
558 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
559 // If its a vector image, and user only specifies height
560 // we don't want it to be limited by its "normal" width.
561 global $wgSVGMaxSize;
562 $hp['width'] = $wgSVGMaxSize;
564 $hp['width'] = $file->getWidth( $page );
567 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
568 global $wgThumbLimits, $wgThumbUpright;
569 if ( !isset( $widthOption ) ||
!isset( $wgThumbLimits[$widthOption] ) ) {
570 $widthOption = User
::getDefaultOption( 'thumbsize' );
573 // Reduce width for upright images when parameter 'upright' is used
574 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
575 $fp['upright'] = $wgThumbUpright;
577 // For caching health: If width scaled down due to upright parameter, round to full __0 pixel to avoid the creation of a lot of odd thumbs
578 $prefWidth = isset( $fp['upright'] ) ?
579 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
580 $wgThumbLimits[$widthOption];
582 // Use width which is smaller: real image width or user preference width
583 // Unless image is scalable vector.
584 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
585 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
586 $hp['width'] = $prefWidth;
591 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
593 # Create a thumbnail. Alignment depends on language
594 # writing direction, # right aligned for left-to-right-
595 # languages ("Western languages"), left-aligned
596 # for right-to-left-languages ("Semitic languages")
598 # If thumbnail width has not been provided, it is set
599 # to the default user option as specified in Language*.php
600 if ( $fp['align'] == '' ) {
601 $fp['align'] = $wgContLang->alignEnd();
603 return $prefix . self
::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
606 if ( $file && isset( $fp['frameless'] ) ) {
607 $srcWidth = $file->getWidth( $page );
608 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
609 # This is the same behaviour as the "thumb" option does it already.
610 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
611 $hp['width'] = $srcWidth;
615 if ( $file && isset( $hp['width'] ) ) {
616 # Create a resized image, without the additional thumbnail features
617 $thumb = $file->transform( $hp );
623 $s = self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
627 'title' => $fp['title'],
628 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
629 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
630 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
632 $s = $thumb->toHtml( $params );
634 if ( $fp['align'] != '' ) {
635 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
637 return str_replace( "\n", ' ', $prefix . $s . $postfix );
641 * Get the link parameters for MediaTransformOutput::toHtml() from given
642 * frame parameters supplied by the Parser.
643 * @param $frameParams array The frame parameters
644 * @param $query string An optional query string to add to description page links
647 private static function getImageLinkMTOParams( $frameParams, $query = '' ) {
648 $mtoParams = array();
649 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
650 $mtoParams['custom-url-link'] = $frameParams['link-url'];
651 if ( isset( $frameParams['link-target'] ) ) {
652 $mtoParams['custom-target-link'] = $frameParams['link-target'];
654 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
655 $mtoParams['custom-title-link'] = self
::normaliseSpecialPage( $frameParams['link-title'] );
656 } elseif ( !empty( $frameParams['no-link'] ) ) {
659 $mtoParams['desc-link'] = true;
660 $mtoParams['desc-query'] = $query;
666 * Make HTML for a thumbnail including image, border and caption
667 * @param $title Title object
668 * @param $file File object or false if it doesn't exist
669 * @param $label String
671 * @param $align String
672 * @param $params Array
673 * @param $framed Boolean
674 * @param $manualthumb String
677 public static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt,
678 $align = 'right', $params = array(), $framed = false , $manualthumb = "" )
680 $frameParams = array(
686 $frameParams['framed'] = true;
688 if ( $manualthumb ) {
689 $frameParams['manualthumb'] = $manualthumb;
691 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
695 * @param $title Title
697 * @param array $frameParams
698 * @param array $handlerParams
700 * @param string $query
703 public static function makeThumbLink2( Title
$title, $file, $frameParams = array(),
704 $handlerParams = array(), $time = false, $query = "" )
706 global $wgStylePath, $wgContLang;
707 $exists = $file && $file->exists();
711 $hp =& $handlerParams;
713 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
714 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
715 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
716 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
717 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
719 if ( empty( $hp['width'] ) ) {
720 // Reduce width for upright images when parameter 'upright' is used
721 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
726 $outerWidth = $hp['width'] +
2;
728 if ( isset( $fp['manualthumb'] ) ) {
729 # Use manually specified thumbnail
730 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
731 if ( $manual_title ) {
732 $manual_img = wfFindFile( $manual_title );
734 $thumb = $manual_img->getUnscaledThumb( $hp );
739 } elseif ( isset( $fp['framed'] ) ) {
740 // Use image dimensions, don't scale
741 $thumb = $file->getUnscaledThumb( $hp );
743 # Do not present an image bigger than the source, for bitmap-style images
744 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
745 $srcWidth = $file->getWidth( $page );
746 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
747 $hp['width'] = $srcWidth;
749 $thumb = $file->transform( $hp );
753 $outerWidth = $thumb->getWidth() +
2;
755 $outerWidth = $hp['width'] +
2;
759 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
760 # So we don't need to pass it here in $query. However, the URL for the
761 # zoom icon still needs it, so we make a unique query for it. See bug 14771
762 $url = $title->getLocalURL( $query );
764 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
767 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
769 $s .= self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
771 } elseif ( !$thumb ) {
772 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
777 'title' => $fp['title'],
778 'img-class' => 'thumbimage' );
779 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
780 $s .= $thumb->toHtml( $params );
781 if ( isset( $fp['framed'] ) ) {
784 $zoomIcon = Html
::rawElement( 'div', array( 'class' => 'magnify' ),
785 Html
::rawElement( 'a', array(
787 'class' => 'internal',
788 'title' => wfMsg( 'thumbnail-more' ) ),
789 Html
::element( 'img', array(
790 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ?
'-rtl' : '' ) . '.png',
796 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
797 return str_replace( "\n", ' ', $s );
801 * Make a "broken" link to an image
803 * @param $title Title object
804 * @param $html String: link label in htmlescaped text form
805 * @param $query String: query string
806 * @param $trail String: link trail (HTML fragment)
807 * @param $prefix String: link prefix (HTML fragment)
808 * @param $time Boolean: a file of a certain timestamp was requested
811 public static function makeBrokenImageLinkObj( $title, $html = '', $query = '', $trail = '', $prefix = '', $time = false ) {
812 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
813 if ( ! $title instanceof Title
) {
814 return "<!-- ERROR -->{$prefix}{$html}{$trail}";
816 wfProfileIn( __METHOD__
);
817 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
819 list( $inside, $trail ) = self
::splitTrail( $trail );
821 $html = htmlspecialchars( $title->getPrefixedText() );
823 if ( ( $wgUploadMissingFileUrl ||
$wgUploadNavigationUrl ||
$wgEnableUploads ) && !$currentExists ) {
824 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
827 wfProfileOut( __METHOD__
);
828 return self
::linkKnown( $title, "$prefix$html$inside", array(), $query ) . $trail;
831 $href = self
::getUploadUrl( $title, $query );
833 wfProfileOut( __METHOD__
);
834 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
835 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
836 "$prefix$html$inside</a>$trail";
838 wfProfileOut( __METHOD__
);
839 return self
::linkKnown( $title, "$prefix$html$inside", array(), $query ) . $trail;
844 * Get the URL to upload a certain file
846 * @param $destFile Title object of the file to upload
847 * @param $query String: urlencoded query string to prepend
848 * @return String: urlencoded URL
850 protected static function getUploadUrl( $destFile, $query = '' ) {
851 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
852 $q = 'wpDestFile=' . $destFile->getPartialUrl();
856 if ( $wgUploadMissingFileUrl ) {
857 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
858 } elseif( $wgUploadNavigationUrl ) {
859 return wfAppendQuery( $wgUploadNavigationUrl, $q );
861 $upload = SpecialPage
::getTitleFor( 'Upload' );
862 return $upload->getLocalUrl( $q );
867 * Create a direct link to a given uploaded file.
869 * @param $title Title object.
870 * @param $html String: pre-sanitized HTML
871 * @param $time string: MW timestamp of file creation time
872 * @return String: HTML
874 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
875 $img = wfFindFile( $title, array( 'time' => $time ) );
876 return self
::makeMediaLinkFile( $title, $img, $html );
880 * Create a direct link to a given uploaded file.
881 * This will make a broken link if $file is false.
883 * @param $title Title object.
884 * @param $file File|bool mixed File object or false
885 * @param $html String: pre-sanitized HTML
886 * @return String: HTML
888 * @todo Handle invalid or missing images better.
890 public static function makeMediaLinkFile( Title
$title, $file, $html = '' ) {
891 if ( $file && $file->exists() ) {
892 $url = $file->getURL();
895 $url = self
::getUploadUrl( $title );
898 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES
);
902 $u = htmlspecialchars( $url );
903 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$html}</a>";
907 * Make a link to a special page given its name and, optionally,
908 * a message key from the link text.
909 * Usage example: Linker::specialLink( 'Recentchanges' )
913 public static function specialLink( $name, $key = '' ) {
915 $key = strtolower( $name );
918 return self
::linkKnown( SpecialPage
::getTitleFor( $name ) , wfMsg( $key ) );
922 * Make an external link
923 * @param $url String: URL to link to
924 * @param $text String: text of link
925 * @param $escape Boolean: do we escape the link text?
926 * @param $linktype String: type of external link. Gets added to the classes
927 * @param $attribs Array of extra attributes to <a>
930 public static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
933 $class .= " $linktype";
935 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
936 $class .= " {$attribs['class']}";
938 $attribs['class'] = $class;
941 $text = htmlspecialchars( $text );
944 $success = wfRunHooks( 'LinkerMakeExternalLink',
945 array( &$url, &$text, &$link, &$attribs, $linktype ) );
947 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
950 $attribs['href'] = $url;
951 return Html
::rawElement( 'a', $attribs, $text );
955 * Make user link (or user contributions for unregistered users)
956 * @param $userId Integer: user id in database.
957 * @param $userName String: user name in database.
958 * @param $altUserName String: text to display instead of the user name (optional)
959 * @return String: HTML fragment
960 * @since 1.19 Method exists for a long time. $displayText was added in 1.19.
962 public static function userLink( $userId, $userName, $altUserName = false ) {
963 if ( $userId == 0 ) {
964 $page = SpecialPage
::getTitleFor( 'Contributions', $userName );
966 $page = Title
::makeTitle( NS_USER
, $userName );
971 htmlspecialchars( $altUserName !== false ?
$altUserName : $userName ),
972 array( 'class' => 'mw-userlink' )
977 * Generate standard user tool links (talk, contributions, block link, etc.)
979 * @param $userId Integer: user identifier
980 * @param $userText String: user name or IP address
981 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
982 * red if the user has no edits?
983 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK and Linker::TOOL_LINKS_EMAIL)
984 * @param $edits Integer: user edit count (optional, for performance)
985 * @return String: HTML fragment
987 public static function userToolLinks(
988 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
990 global $wgUser, $wgDisableAnonTalk, $wgLang;
991 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
992 $blockable = !( $flags & self
::TOOL_LINKS_NOBLOCK
);
993 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
&& $userId;
997 $items[] = self
::userTalkLink( $userId, $userText );
1000 // check if the user has an edit
1002 if ( $redContribsWhenNoEdits ) {
1003 $count = !is_null( $edits ) ?
$edits : User
::edits( $userId );
1004 if ( $count == 0 ) {
1005 $attribs['class'] = 'new';
1008 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
1010 $items[] = self
::link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
1012 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1013 $items[] = self
::blockLink( $userId, $userText );
1016 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1017 $items[] = self
::emailLink( $userId, $userText );
1020 wfRunHooks( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1023 return ' <span class="mw-usertoollinks">' . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped() . '</span>';
1030 * Alias for userToolLinks( $userId, $userText, true );
1031 * @param $userId Integer: user identifier
1032 * @param $userText String: user name or IP address
1033 * @param $edits Integer: user edit count (optional, for performance)
1036 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1037 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
1042 * @param $userId Integer: user id in database.
1043 * @param $userText String: user name in database.
1044 * @return String: HTML fragment with user talk link
1046 public static function userTalkLink( $userId, $userText ) {
1047 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
1048 $userTalkLink = self
::link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
1049 return $userTalkLink;
1053 * @param $userId Integer: userid
1054 * @param $userText String: user name in database.
1055 * @return String: HTML fragment with block link
1057 public static function blockLink( $userId, $userText ) {
1058 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1059 $blockLink = self
::link( $blockPage, wfMsgHtml( 'blocklink' ) );
1064 * @param $userId Integer: userid
1065 * @param $userText String: user name in database.
1066 * @return String: HTML fragment with e-mail user link
1068 public static function emailLink( $userId, $userText ) {
1069 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1070 $emailLink = self
::link( $emailPage, wfMsgHtml( 'emaillink' ) );
1075 * Generate a user link if the current user is allowed to view it
1076 * @param $rev Revision object.
1077 * @param $isPublic Boolean: show only if all users can see it
1078 * @return String: HTML fragment
1080 public static function revUserLink( $rev, $isPublic = false ) {
1081 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1082 $link = wfMsgHtml( 'rev-deleted-user' );
1083 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1084 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1085 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1087 $link = wfMsgHtml( 'rev-deleted-user' );
1089 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1090 return '<span class="history-deleted">' . $link . '</span>';
1096 * Generate a user tool link cluster if the current user is allowed to view it
1097 * @param $rev Revision object.
1098 * @param $isPublic Boolean: show only if all users can see it
1099 * @return string HTML
1101 public static function revUserTools( $rev, $isPublic = false ) {
1102 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1103 $link = wfMsgHtml( 'rev-deleted-user' );
1104 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1105 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1106 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1107 $link = self
::userLink( $userId, $userText ) .
1108 ' ' . self
::userToolLinks( $userId, $userText );
1110 $link = wfMsgHtml( 'rev-deleted-user' );
1112 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1113 return ' <span class="history-deleted">' . $link . '</span>';
1119 * This function is called by all recent changes variants, by the page history,
1120 * and by the user contributions list. It is responsible for formatting edit
1121 * comments. It escapes any HTML in the comment, but adds some CSS to format
1122 * auto-generated comments (from section editing) and formats [[wikilinks]].
1124 * @author Erik Moeller <moeller@scireview.de>
1126 * Note: there's not always a title to pass to this function.
1127 * Since you can't set a default parameter for a reference, I've turned it
1128 * temporarily to a value pass. Should be adjusted further. --brion
1130 * @param $comment String
1131 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1132 * @param $local Boolean: whether section links should refer to local page
1133 * @return mixed|String
1135 public static function formatComment( $comment, $title = null, $local = false ) {
1136 wfProfileIn( __METHOD__
);
1138 # Sanitize text a bit:
1139 $comment = str_replace( "\n", " ", $comment );
1140 # Allow HTML entities (for bug 13815)
1141 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1143 # Render autocomments and make links:
1144 $comment = self
::formatAutocomments( $comment, $title, $local );
1145 $comment = self
::formatLinksInComment( $comment, $title, $local );
1147 wfProfileOut( __METHOD__
);
1154 static $autocommentTitle;
1155 static $autocommentLocal;
1158 * The pattern for autogen comments is / * foo * /, which makes for
1160 * We look for all comments, match any text before and after the comment,
1161 * add a separator where needed and format the comment itself with CSS
1162 * Called by Linker::formatComment.
1164 * @param $comment String: comment text
1165 * @param $title Title|null An optional title object used to links to sections
1166 * @param $local Boolean: whether section links should refer to local page
1167 * @return String: formatted comment
1169 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1171 self
::$autocommentTitle = $title;
1172 self
::$autocommentLocal = $local;
1173 $comment = preg_replace_callback(
1174 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1175 array( 'Linker', 'formatAutocommentsCallback' ),
1177 self
::$autocommentTitle = null;
1178 self
::$autocommentLocal = null;
1186 private static function formatAutocommentsCallback( $match ) {
1188 $title = self
::$autocommentTitle;
1189 $local = self
::$autocommentLocal;
1198 # Remove links that a user may have manually put in the autosummary
1199 # This could be improved by copying as much of Parser::stripSectionName as desired.
1200 $section = str_replace( '[[:', '', $section );
1201 $section = str_replace( '[[', '', $section );
1202 $section = str_replace( ']]', '', $section );
1204 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1206 $sectionTitle = Title
::newFromText( '#' . $section );
1208 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1209 $title->getDBkey(), $section );
1211 if ( $sectionTitle ) {
1212 $link = self
::link( $sectionTitle,
1213 $wgLang->getArrow(), array(), array(),
1220 # written summary $presep autocomment (summary /* section */)
1221 $pre .= wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) );
1224 # autocomment $postsep written summary (/* section */ summary)
1225 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1227 $auto = '<span class="autocomment">' . $auto . '</span>';
1228 $comment = $pre . $link . $wgLang->getDirMark() . '<span dir="auto">' . $auto . $post . '</span>';
1235 static $commentContextTitle;
1236 static $commentLocal;
1239 * Formats wiki links and media links in text; all other wiki formatting
1242 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1243 * @param $comment String: text to format links in
1244 * @param $title Title|null An optional title object used to links to sections
1245 * @param $local Boolean: whether section links should refer to local page
1248 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1249 self
::$commentContextTitle = $title;
1250 self
::$commentLocal = $local;
1251 $html = preg_replace_callback(
1252 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1253 array( 'Linker', 'formatLinksInCommentCallback' ),
1255 self
::$commentContextTitle = null;
1256 self
::$commentLocal = null;
1264 protected static function formatLinksInCommentCallback( $match ) {
1267 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1268 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1270 $comment = $match[0];
1272 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1273 if ( strpos( $match[1], '%' ) !== false ) {
1274 $match[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $match[1] ) );
1277 # Handle link renaming [[foo|text]] will show link as "text"
1278 if ( $match[3] != "" ) {
1283 $submatch = array();
1285 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1286 # Media link; trail not supported.
1287 $linkRegexp = '/\[\[(.*?)\]\]/';
1288 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1290 $thelink = self
::makeMediaLinkObj( $title, $text );
1293 # Other kind of link
1294 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1295 $trail = $submatch[1];
1299 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1300 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1301 $match[1] = substr( $match[1], 1 );
1302 list( $inside, $trail ) = self
::splitTrail( $trail );
1305 $linkTarget = self
::normalizeSubpageLink( self
::$commentContextTitle,
1306 $match[1], $linkText );
1308 $target = Title
::newFromText( $linkTarget );
1310 if ( $target->getText() == '' && $target->getInterwiki() === ''
1311 && !self
::$commentLocal && self
::$commentContextTitle )
1313 $newTarget = clone ( self
::$commentContextTitle );
1314 $newTarget->setFragment( '#' . $target->getFragment() );
1315 $target = $newTarget;
1317 $thelink = self
::link(
1324 // If the link is still valid, go ahead and replace it in!
1325 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1332 * @param $contextTitle Title
1337 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1340 # :Foobar -- override special treatment of prefix (images, language links)
1341 # /Foobar -- convert to CurrentPage/Foobar
1342 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1343 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1344 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1346 wfProfileIn( __METHOD__
);
1347 $ret = $target; # default return value is no change
1349 # Some namespaces don't allow subpages,
1350 # so only perform processing if subpages are allowed
1351 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1352 $hash = strpos( $target, '#' );
1353 if ( $hash !== false ) {
1354 $suffix = substr( $target, $hash );
1355 $target = substr( $target, 0, $hash );
1360 $target = trim( $target );
1361 # Look at the first character
1362 if ( $target != '' && $target[0] === '/' ) {
1363 # / at end means we don't want the slash to be shown
1365 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1366 if ( $trailingSlashes ) {
1367 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1369 $noslash = substr( $target, 1 );
1372 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1373 if ( $text === '' ) {
1374 $text = $target . $suffix;
1375 } # this might be changed for ugliness reasons
1377 # check for .. subpage backlinks
1379 $nodotdot = $target;
1380 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1382 $nodotdot = substr( $nodotdot, 3 );
1384 if ( $dotdotcount > 0 ) {
1385 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1386 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1387 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1388 # / at the end means don't show full path
1389 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1390 $nodotdot = substr( $nodotdot, 0, -1 );
1391 if ( $text === '' ) {
1392 $text = $nodotdot . $suffix;
1395 $nodotdot = trim( $nodotdot );
1396 if ( $nodotdot != '' ) {
1397 $ret .= '/' . $nodotdot;
1405 wfProfileOut( __METHOD__
);
1410 * Wrap a comment in standard punctuation and formatting if
1411 * it's non-empty, otherwise return empty string.
1413 * @param $comment String
1414 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1415 * @param $local Boolean: whether section links should refer to local page
1419 public static function commentBlock( $comment, $title = null, $local = false ) {
1420 // '*' used to be the comment inserted by the software way back
1421 // in antiquity in case none was provided, here for backwards
1422 // compatability, acc. to brion -ævar
1423 if ( $comment == '' ||
$comment == '*' ) {
1426 $formatted = self
::formatComment( $comment, $title, $local );
1427 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1428 return " <span class=\"comment\">$formatted</span>";
1433 * Wrap and format the given revision's comment block, if the current
1434 * user is allowed to view it.
1436 * @param $rev Revision object
1437 * @param $local Boolean: whether section links should refer to local page
1438 * @param $isPublic Boolean: show only if all users can see it
1439 * @return String: HTML fragment
1441 public static function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1442 if ( $rev->getRawComment() == "" ) {
1445 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1446 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1447 } elseif ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1448 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1449 $rev->getTitle(), $local );
1451 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1453 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1454 return " <span class=\"history-deleted\">$block</span>";
1463 public static function formatRevisionSize( $size ) {
1465 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1468 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1469 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1471 $stxt = htmlspecialchars( $stxt );
1472 return "<span class=\"history-size\">$stxt</span>";
1476 * Add another level to the Table of Contents
1480 public static function tocIndent() {
1485 * Finish one or more sublevels on the Table of Contents
1489 public static function tocUnindent( $level ) {
1490 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1494 * parameter level defines if we are on an indentation level
1498 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1499 $classes = "toclevel-$level";
1500 if ( $sectionIndex !== false ) {
1501 $classes .= " tocsection-$sectionIndex";
1503 return "\n<li class=\"$classes\"><a href=\"#" .
1504 $anchor . '"><span class="tocnumber">' .
1505 $tocnumber . '</span> <span class="toctext">' .
1506 $tocline . '</span></a>';
1510 * End a Table Of Contents line.
1511 * tocUnindent() will be used instead if we're ending a line below
1515 public static function tocLineEnd() {
1520 * Wraps the TOC in a table and provides the hide/collapse javascript.
1522 * @param $toc String: html of the Table Of Contents
1523 * @param $lang mixed: Language code for the toc title
1524 * @return String: full html of the TOC
1526 public static function tocList( $toc, $lang = false ) {
1527 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1529 '<table id="toc" class="toc"><tr><td>'
1530 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1532 . "</ul>\n</td></tr></table>\n";
1536 * Generate a table of contents from a section tree
1539 * @param $tree array Return value of ParserOutput::getSections()
1540 * @return String: HTML fragment
1542 public static function generateTOC( $tree ) {
1545 foreach ( $tree as $section ) {
1546 if ( $section['toclevel'] > $lastLevel )
1547 $toc .= self
::tocIndent();
1548 elseif ( $section['toclevel'] < $lastLevel )
1549 $toc .= self
::tocUnindent(
1550 $lastLevel - $section['toclevel'] );
1552 $toc .= self
::tocLineEnd();
1554 $toc .= self
::tocLine( $section['anchor'],
1555 $section['line'], $section['number'],
1556 $section['toclevel'], $section['index'] );
1557 $lastLevel = $section['toclevel'];
1559 $toc .= self
::tocLineEnd();
1560 return self
::tocList( $toc );
1564 * Create a headline for content
1566 * @param $level Integer: the level of the headline (1-6)
1567 * @param $attribs String: any attributes for the headline, starting with
1568 * a space and ending with '>'
1569 * This *must* be at least '>' for no attribs
1570 * @param $anchor String: the anchor to give the headline (the bit after the #)
1571 * @param $html String: html for the text of the header
1572 * @param $link String: HTML to add for the section edit link
1573 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1574 * backward compatibility (false to omit)
1576 * @return String: HTML headline
1578 public static function makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor = false ) {
1579 $ret = "<h$level$attribs"
1581 . " <span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1583 if ( $legacyAnchor !== false ) {
1584 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1590 * Split a link trail, return the "inside" portion and the remainder of the trail
1591 * as a two-element array
1594 static function splitTrail( $trail ) {
1596 $regex = $wgContLang->linkTrail();
1598 if ( $trail !== '' ) {
1600 if ( preg_match( $regex, $trail, $m ) ) {
1605 return array( $inside, $trail );
1609 * Generate a rollback link for a given revision. Currently it's the
1610 * caller's responsibility to ensure that the revision is the top one. If
1611 * it's not, of course, the user will get an error message.
1613 * If the calling page is called with the parameter &bot=1, all rollback
1614 * links also get that parameter. It causes the edit itself and the rollback
1615 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1616 * changes, so this allows sysops to combat a busy vandal without bothering
1619 * @param $rev Revision object
1622 public static function generateRollback( $rev ) {
1623 return '<span class="mw-rollback-link">['
1624 . self
::buildRollbackLink( $rev )
1629 * Build a raw rollback link, useful for collections of "tool" links
1631 * @param $rev Revision object
1632 * @return String: HTML fragment
1634 public static function buildRollbackLink( $rev ) {
1635 global $wgRequest, $wgUser;
1636 $title = $rev->getTitle();
1638 'action' => 'rollback',
1639 'from' => $rev->getUserText(),
1640 'token' => $wgUser->getEditToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1642 if ( $wgRequest->getBool( 'bot' ) ) {
1643 $query['bot'] = '1';
1644 $query['hidediff'] = '1'; // bug 15999
1648 wfMsgHtml( 'rollbacklink' ),
1649 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1651 array( 'known', 'noclasses' )
1656 * Returns HTML for the "templates used on this page" list.
1658 * @param $templates Array of templates from Article::getUsedTemplate
1660 * @param $preview Boolean: whether this is for a preview
1661 * @param $section Boolean: whether this is for a section edit
1662 * @return String: HTML output
1664 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1665 wfProfileIn( __METHOD__
);
1668 if ( count( $templates ) > 0 ) {
1669 # Do a batch existence check
1670 $batch = new LinkBatch
;
1671 foreach ( $templates as $title ) {
1672 $batch->addObj( $title );
1676 # Construct the HTML
1677 $outText = '<div class="mw-templatesUsedExplanation">';
1679 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1680 } elseif ( $section ) {
1681 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1683 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1685 $outText .= "</div><ul>\n";
1687 usort( $templates, array( 'Title', 'compare' ) );
1688 foreach ( $templates as $titleObj ) {
1689 $r = $titleObj->getRestrictions( 'edit' );
1690 if ( in_array( 'sysop', $r ) ) {
1691 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1692 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1693 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1697 if ( $titleObj->quickUserCan( 'edit' ) ) {
1698 $editLink = self
::link(
1700 wfMsg( 'editlink' ),
1702 array( 'action' => 'edit' )
1705 $editLink = self
::link(
1707 wfMsg( 'viewsourcelink' ),
1709 array( 'action' => 'edit' )
1712 $outText .= '<li>' . self
::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1714 $outText .= '</ul>';
1716 wfProfileOut( __METHOD__
);
1721 * Returns HTML for the "hidden categories on this page" list.
1723 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1725 * @return String: HTML output
1727 public static function formatHiddenCategories( $hiddencats ) {
1729 wfProfileIn( __METHOD__
);
1732 if ( count( $hiddencats ) > 0 ) {
1733 # Construct the HTML
1734 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1735 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1736 $outText .= "</div><ul>\n";
1738 foreach ( $hiddencats as $titleObj ) {
1739 $outText .= '<li>' . self
::link( $titleObj, null, array(), array(), 'known' ) . "</li>\n"; # If it's hidden, it must exist - no need to check with a LinkBatch
1741 $outText .= '</ul>';
1743 wfProfileOut( __METHOD__
);
1748 * Format a size in bytes for output, using an appropriate
1749 * unit (B, KB, MB or GB) according to the magnitude in question
1751 * @param $size int Size to format
1754 public static function formatSize( $size ) {
1756 return htmlspecialchars( $wgLang->formatSize( $size ) );
1760 * Given the id of an interface element, constructs the appropriate title
1761 * attribute from the system messages. (Note, this is usually the id but
1762 * isn't always, because sometimes the accesskey needs to go on a different
1763 * element than the id, for reverse-compatibility, etc.)
1765 * @param $name String: id of the element, minus prefixes.
1766 * @param $options Mixed: null or the string 'withaccess' to add an access-
1768 * @return String: contents of the title attribute (which you must HTML-
1769 * escape), or false for no title attribute
1771 public static function titleAttrib( $name, $options = null ) {
1772 wfProfileIn( __METHOD__
);
1774 $message = wfMessage( "tooltip-$name" );
1776 if ( !$message->exists() ) {
1779 $tooltip = $message->text();
1780 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1781 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1782 # Message equal to '-' means suppress it.
1783 if ( $tooltip == '-' ) {
1788 if ( $options == 'withaccess' ) {
1789 $accesskey = self
::accesskey( $name );
1790 if ( $accesskey !== false ) {
1791 if ( $tooltip === false ||
$tooltip === '' ) {
1792 $tooltip = "[$accesskey]";
1794 $tooltip .= " [$accesskey]";
1799 wfProfileOut( __METHOD__
);
1803 static $accesskeycache;
1806 * Given the id of an interface element, constructs the appropriate
1807 * accesskey attribute from the system messages. (Note, this is usually
1808 * the id but isn't always, because sometimes the accesskey needs to go on
1809 * a different element than the id, for reverse-compatibility, etc.)
1811 * @param $name String: id of the element, minus prefixes.
1812 * @return String: contents of the accesskey attribute (which you must HTML-
1813 * escape), or false for no accesskey attribute
1815 public static function accesskey( $name ) {
1816 if ( isset( self
::$accesskeycache[$name] ) ) {
1817 return self
::$accesskeycache[$name];
1819 wfProfileIn( __METHOD__
);
1821 $message = wfMessage( "accesskey-$name" );
1823 if ( !$message->exists() ) {
1826 $accesskey = $message->plain();
1827 if ( $accesskey === '' ||
$accesskey === '-' ) {
1828 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
1829 # attribute, but this is broken for accesskey: that might be a useful
1835 wfProfileOut( __METHOD__
);
1836 return self
::$accesskeycache[$name] = $accesskey;
1840 * Get a revision-deletion link, or disabled link, or nothing, depending
1841 * on user permissions & the settings on the revision.
1843 * Will use forward-compatible revision ID in the Special:RevDelete link
1844 * if possible, otherwise the timestamp-based ID which may break after
1848 * @param Revision $rev
1849 * @param Revision $title
1850 * @return string HTML fragment
1852 public static function getRevDeleteLink( User
$user, Revision
$rev, Title
$title ) {
1853 $canHide = $user->isAllowed( 'deleterevision' );
1854 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
1858 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
1859 return Linker
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
1861 if ( $rev->getId() ) {
1862 // RevDelete links using revision ID are stable across
1863 // page deletion and undeletion; use when possible.
1865 'type' => 'revision',
1866 'target' => $title->getPrefixedDBkey(),
1867 'ids' => $rev->getId()
1870 // Older deleted entries didn't save a revision ID.
1871 // We have to refer to these by timestamp, ick!
1873 'type' => 'archive',
1874 'target' => $title->getPrefixedDBkey(),
1875 'ids' => $rev->getTimestamp()
1878 return Linker
::revDeleteLink( $query,
1879 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
1884 * Creates a (show/hide) link for deleting revisions/log entries
1886 * @param $query Array: query parameters to be passed to link()
1887 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1888 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1890 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1891 * span to allow for customization of appearance with CSS
1893 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1894 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1895 $html = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1896 $tag = $restricted ?
'strong' : 'span';
1897 $link = self
::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
1898 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $link )->escaped() );
1902 * Creates a dead (show/hide) link for deleting revisions/log entries
1904 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1906 * @return string HTML text wrapped in a span to allow for customization
1907 * of appearance with CSS
1909 public static function revDeleteLinkDisabled( $delete = true ) {
1910 $html = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1911 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $html )->escaped() );
1914 /* Deprecated methods */
1917 * @deprecated since 1.16 Use link()
1919 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1920 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1922 * @param $title String: The text of the title
1923 * @param $text String: Link text
1924 * @param $query String: Optional query part
1925 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1926 * be included in the link text. Other characters will be appended after
1927 * the end of the link.
1930 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1931 wfDeprecated( __METHOD__
, '1.16' );
1933 $nt = Title
::newFromText( $title );
1934 if ( $nt instanceof Title
) {
1935 return self
::makeBrokenLinkObj( $nt, $text, $query, $trail );
1937 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
1938 return $text == '' ?
$title : $text;
1943 * @deprecated since 1.16 Use link()
1945 * Make a link for a title which may or may not be in the database. If you need to
1946 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1947 * call to this will result in a DB query.
1949 * @param $nt Title: the title object to make the link from, e.g. from
1950 * Title::newFromText.
1951 * @param $text String: link text
1952 * @param $query String: optional query part
1953 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1954 * be included in the link text. Other characters will be appended after
1955 * the end of the link.
1956 * @param $prefix String: optional prefix. As trail, only before instead of after.
1959 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1960 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
1962 wfProfileIn( __METHOD__
);
1963 $query = wfCgiToArray( $query );
1964 list( $inside, $trail ) = self
::splitTrail( $trail );
1965 if ( $text === '' ) {
1966 $text = self
::linkText( $nt );
1969 $ret = self
::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1971 wfProfileOut( __METHOD__
);
1976 * @deprecated since 1.16 Use link()
1978 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1979 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1982 * @param $title Title object of target page
1983 * @param $text String: text to replace the title
1984 * @param $query String: link target
1985 * @param $trail String: text after link
1986 * @param $prefix String: text before link text
1987 * @param $aprops String: extra attributes to the a-element
1988 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1989 * @return string the a-element
1991 static function makeKnownLinkObj(
1992 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
1994 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
1996 wfProfileIn( __METHOD__
);
1998 if ( $text == '' ) {
1999 $text = self
::linkText( $title );
2001 $attribs = Sanitizer
::mergeAttributes(
2002 Sanitizer
::decodeTagAttributes( $aprops ),
2003 Sanitizer
::decodeTagAttributes( $style )
2005 $query = wfCgiToArray( $query );
2006 list( $inside, $trail ) = self
::splitTrail( $trail );
2008 $ret = self
::link( $title, "$prefix$text$inside", $attribs, $query,
2009 array( 'known', 'noclasses' ) ) . $trail;
2011 wfProfileOut( __METHOD__
);
2016 * @deprecated since 1.16 Use link()
2018 * Make a red link to the edit page of a given title.
2020 * @param $title Title object of the target page
2021 * @param $text String: Link text
2022 * @param $query String: Optional query part
2023 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
2024 * be included in the link text. Other characters will be appended after
2025 * the end of the link.
2026 * @param $prefix String: Optional prefix
2029 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
2030 wfDeprecated( __METHOD__
, '1.16' );
2032 wfProfileIn( __METHOD__
);
2034 list( $inside, $trail ) = self
::splitTrail( $trail );
2035 if ( $text === '' ) {
2036 $text = self
::linkText( $title );
2039 $ret = self
::link( $title, "$prefix$text$inside", array(),
2040 wfCgiToArray( $query ), 'broken' ) . $trail;
2042 wfProfileOut( __METHOD__
);
2047 * @deprecated since 1.16 Use link()
2049 * Make a coloured link.
2051 * @param $nt Title object of the target page
2052 * @param $colour Integer: colour of the link
2053 * @param $text String: link text
2054 * @param $query String: optional query part
2055 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2056 * be included in the link text. Other characters will be appended after
2057 * the end of the link.
2058 * @param $prefix String: Optional prefix
2061 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2062 wfDeprecated( __METHOD__
, '1.16' );
2064 if ( $colour != '' ) {
2065 $style = self
::getInternalLinkAttributesObj( $nt, $text, $colour );
2069 return self
::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2073 * Returns the attributes for the tooltip and access key.
2076 public static function tooltipAndAccesskeyAttribs( $name ) {
2077 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2078 # no attribute" instead of "output '' as value for attribute", this
2079 # would be three lines.
2081 'title' => self
::titleAttrib( $name, 'withaccess' ),
2082 'accesskey' => self
::accesskey( $name )
2084 if ( $attribs['title'] === false ) {
2085 unset( $attribs['title'] );
2087 if ( $attribs['accesskey'] === false ) {
2088 unset( $attribs['accesskey'] );
2094 * Returns raw bits of HTML, use titleAttrib()
2095 * @return null|string
2097 public static function tooltip( $name, $options = null ) {
2098 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2099 # no attribute" instead of "output '' as value for attribute", this
2100 # would be two lines.
2101 $tooltip = self
::titleAttrib( $name, $options );
2102 if ( $tooltip === false ) {
2105 return Xml
::expandAttributes( array(
2117 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2118 * into static calls to the new Linker for backwards compatibility.
2120 * @param $fname String Name of called method
2121 * @param $args Array Arguments to the method
2124 public function __call( $fname, $args ) {
2125 return call_user_func_array( array( 'Linker', $fname ), $args );