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'.
23 * @deprecated since 1.18 Just pass the external class directly to something using Html::expandAttributes
25 static function getExternalLinkAttributes( $class = 'external' ) {
26 wfDeprecated( __METHOD__
, '1.18' );
27 return self
::getLinkAttributesInternal( '', $class );
31 * Get the appropriate HTML attributes to add to the "a" element of an in-
34 * @param $title String: the title text for the link, URL-encoded (???) but
36 * @param $unused String: unused
37 * @param $class String: the contents of the class attribute; if an empty
38 * string is passed, which is the default value, defaults to 'external'.
40 static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
43 # @todo FIXME: We have a whole bunch of handling here that doesn't happen in
44 # getExternalLinkAttributes, why?
45 $title = urldecode( $title );
46 $title = $wgContLang->checkTitleEncoding( $title );
47 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
49 return self
::getLinkAttributesInternal( $title, $class );
53 * Get the appropriate HTML attributes to add to the "a" element of an in-
56 * @param $title String: the title text for the link, URL-encoded (???) but
58 * @param $unused String: unused
59 * @param $class String: the contents of the class attribute, default none
61 static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
62 $title = urldecode( $title );
63 $title = str_replace( '_', ' ', $title );
64 return self
::getLinkAttributesInternal( $title, $class );
68 * Get the appropriate HTML attributes to add to the "a" element of an in-
69 * ternal link, given the Title object for the page we want to link to.
72 * @param $unused String: unused
73 * @param $class String: the contents of the class attribute, default none
74 * @param $title Mixed: optional (unescaped) string to use in the title
75 * attribute; if false, default to the name of the page we're linking to
77 static function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
78 if ( $title === false ) {
79 $title = $nt->getPrefixedText();
81 return self
::getLinkAttributesInternal( $title, $class );
85 * Common code for getLinkAttributesX functions
87 * @param $title string
88 * @param $class string
92 private static function getLinkAttributesInternal( $title, $class ) {
93 $title = htmlspecialchars( $title );
94 $class = htmlspecialchars( $class );
97 $r .= " class=\"$class\"";
100 $r .= " title=\"$title\"";
106 * Return the CSS colour of a known link
108 * @param $t Title object
109 * @param $threshold Integer: user defined threshold
110 * @return String: CSS class
112 public static function getLinkColour( $t, $threshold ) {
114 if ( $t->isRedirect() ) {
116 $colour = 'mw-redirect';
117 } elseif ( $threshold > 0 &&
118 $t->exists() && $t->getLength() < $threshold &&
119 $t->isContentPage() ) {
127 * This function returns an HTML link to the given target. It serves a few
129 * 1) If $target is a Title, the correct URL to link to will be figured
131 * 2) It automatically adds the usual classes for various types of link
132 * targets: "new" for red links, "stub" for short articles, etc.
133 * 3) It escapes all attribute values safely so there's no risk of XSS.
134 * 4) It provides a default tooltip if the target is a Title (the page
135 * name of the target).
136 * link() replaces the old functions in the makeLink() family.
138 * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
139 * You can call it using this if you want to keep compat with these:
140 * $linker = class_exists( 'DummyLinker' ) ? new DummyLinker() : new Linker();
141 * $linker->link( ... );
143 * @param $target Title Can currently only be a Title, but this may
144 * change to support Images, literal URLs, etc.
145 * @param $html string The HTML contents of the <a> element, i.e.,
146 * the link text. This is raw HTML and will not be escaped. If null,
147 * defaults to the prefixed text of the Title; or if the Title is just a
148 * fragment, the contents of the fragment.
149 * @param $customAttribs array A key => value array of extra HTML attri-
150 * butes, such as title and class. (href is ignored.) Classes will be
151 * merged with the default classes, while other attributes will replace
152 * default attributes. All passed attribute values will be HTML-escaped.
153 * A false attribute value means to suppress that attribute.
154 * @param $query array The query string to append to the URL
155 * you're linking to, in key => value array form. Query keys and values
156 * will be URL-encoded.
157 * @param $options string|array String or array of strings:
158 * 'known': Page is known to exist, so don't check if it does.
159 * 'broken': Page is known not to exist, so don't check if it does.
160 * 'noclasses': Don't add any classes automatically (includes "new",
161 * "stub", "mw-redirect", "extiw"). Only use the class attribute
162 * provided, if any, so you get a simple blue link with no funny i-
164 * 'forcearticlepath': Use the article path always, even with a querystring.
165 * Has compatibility issues on some setups, so avoid wherever possible.
166 * @return string HTML <a> attribute
168 public static function link(
169 $target, $html = null, $customAttribs = array(), $query = array(), $options = array()
171 wfProfileIn( __METHOD__
);
172 if ( !$target instanceof Title
) {
173 wfProfileOut( __METHOD__
);
174 return "<!-- ERROR -->$html";
176 $options = (array)$options;
178 $dummy = new DummyLinker
; // dummy linker instance for bc on the hooks
181 if ( !wfRunHooks( 'LinkBegin', array( $dummy, $target, &$html,
182 &$customAttribs, &$query, &$options, &$ret ) ) ) {
183 wfProfileOut( __METHOD__
);
187 # Normalize the Title if it's a special page
188 $target = self
::normaliseSpecialPage( $target );
190 # If we don't know whether the page exists, let's find out.
191 wfProfileIn( __METHOD__
. '-checkPageExistence' );
192 if ( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
193 if ( $target->isKnown() ) {
194 $options[] = 'known';
196 $options[] = 'broken';
199 wfProfileOut( __METHOD__
. '-checkPageExistence' );
202 if ( in_array( "forcearticlepath", $options ) && $query ) {
207 # Note: we want the href attribute first, for prettiness.
208 $attribs = array( 'href' => self
::linkUrl( $target, $query, $options ) );
209 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
210 $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
213 $attribs = array_merge(
215 self
::linkAttribs( $target, $customAttribs, $options )
217 if ( is_null( $html ) ) {
218 $html = self
::linkText( $target );
222 if ( wfRunHooks( 'LinkEnd', array( $dummy, $target, $options, &$html, &$attribs, &$ret ) ) ) {
223 $ret = Html
::rawElement( 'a', $attribs, $html );
226 wfProfileOut( __METHOD__
);
231 * Identical to link(), except $options defaults to 'known'.
233 public static function linkKnown(
234 $target, $html = null, $customAttribs = array(),
235 $query = array(), $options = array( 'known', 'noclasses' ) )
237 return self
::link( $target, $html, $customAttribs, $query, $options );
241 * Returns the Url used to link to a Title
243 * @param $target Title
244 * @param $query Array: query parameters
245 * @param $options Array
247 private static function linkUrl( $target, $query, $options ) {
248 wfProfileIn( __METHOD__
);
249 # We don't want to include fragments for broken links, because they
250 # generally make no sense.
251 if ( in_array( 'broken', $options ) && $target->mFragment
!== '' ) {
252 $target = clone $target;
253 $target->mFragment
= '';
256 # If it's a broken link, add the appropriate query pieces, unless
257 # there's already an action specified, or unless 'edit' makes no sense
258 # (i.e., for a nonexistent special page).
259 if ( in_array( 'broken', $options ) && empty( $query['action'] )
260 && !$target->isSpecialPage() ) {
261 $query['action'] = 'edit';
262 $query['redlink'] = '1';
264 $ret = $target->getLinkURL( $query );
265 wfProfileOut( __METHOD__
);
270 * Returns the array of attributes used when linking to the Title $target
272 * @param $target Title
278 private static function linkAttribs( $target, $attribs, $options ) {
279 wfProfileIn( __METHOD__
);
283 if ( !in_array( 'noclasses', $options ) ) {
284 wfProfileIn( __METHOD__
. '-getClasses' );
285 # Now build the classes.
288 if ( in_array( 'broken', $options ) ) {
292 if ( $target->isExternal() ) {
293 $classes[] = 'extiw';
296 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
297 $colour = self
::getLinkColour( $target, $wgUser->getStubThreshold() );
298 if ( $colour !== '' ) {
299 $classes[] = $colour; # mw-redirect or stub
302 if ( $classes != array() ) {
303 $defaults['class'] = implode( ' ', $classes );
305 wfProfileOut( __METHOD__
. '-getClasses' );
308 # Get a default title attribute.
309 if ( $target->getPrefixedText() == '' ) {
310 # A link like [[#Foo]]. This used to mean an empty title
311 # attribute, but that's silly. Just don't output a title.
312 } elseif ( in_array( 'known', $options ) ) {
313 $defaults['title'] = $target->getPrefixedText();
315 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
318 # Finally, merge the custom attribs with the default ones, and iterate
319 # over that, deleting all "false" attributes.
321 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
322 foreach ( $merged as $key => $val ) {
323 # A false value suppresses the attribute, and we don't want the
324 # href attribute to be overridden.
325 if ( $key != 'href' and $val !== false ) {
329 wfProfileOut( __METHOD__
);
334 * Default text of the links to the Title $target
336 * @param $target Title
340 private static function linkText( $target ) {
341 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
342 if ( !$target instanceof Title
) {
346 # If the target is just a fragment, with no title, we return the frag-
347 # ment text. Otherwise, we return the title text itself.
348 if ( $target->getPrefixedText() === '' && $target->getFragment() !== '' ) {
349 return htmlspecialchars( $target->getFragment() );
351 return htmlspecialchars( $target->getPrefixedText() );
355 * Generate either a normal exists-style link or a stub link, depending
356 * on the given page size.
358 * @param $size Integer
359 * @param $nt Title object.
360 * @param $text String
361 * @param $query String
362 * @param $trail String
363 * @param $prefix String
364 * @return string HTML of link
365 * @deprecated since 1.17
367 static function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
369 wfDeprecated( __METHOD__
, '1.17' );
371 $threshold = $wgUser->getStubThreshold();
372 $colour = ( $size < $threshold ) ?
'stub' : '';
373 // @todo FIXME: Replace deprecated makeColouredLinkObj by link()
374 return self
::makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
378 * Make appropriate markup for a link to the current article. This is currently rendered
379 * as the bold link text. The calling sequence is the same as the other make*LinkObj static functions,
380 * despite $query not being used.
386 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
388 $html = htmlspecialchars( $nt->getPrefixedText() );
390 list( $inside, $trail ) = self
::splitTrail( $trail );
391 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
395 * @param $title Title
398 static function normaliseSpecialPage( Title
$title ) {
399 if ( $title->isSpecialPage() ) {
400 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
404 $ret = SpecialPage
::getTitleFor( $name, $subpage );
405 $ret->mFragment
= $title->getFragment();
413 * Returns the filename part of an url.
414 * Used as alternative text for external images.
420 private static function fnamePart( $url ) {
421 $basename = strrchr( $url, '/' );
422 if ( false === $basename ) {
425 $basename = substr( $basename, 1 );
431 * Return the code for images which were added via external links,
432 * via Parser::maybeMakeExternalImage().
439 public static function makeExternalImage( $url, $alt = '' ) {
441 $alt = self
::fnamePart( $url );
444 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
446 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
449 return Html
::element( 'img',
456 * Given parameters derived from [[Image:Foo|options...]], generate the
457 * HTML that that syntax inserts in the page.
459 * @param $title Title object
460 * @param $file File object, or false if it doesn't exist
461 * @param $frameParams Array: associative array of parameters external to the media handler.
462 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
463 * will often be false.
464 * thumbnail If present, downscale and frame
465 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
466 * framed Shows image in original size in a frame
467 * frameless Downscale but don't frame
468 * upright If present, tweak default sizes for portrait orientation
469 * upright_factor Fudge factor for "upright" tweak (default 0.75)
470 * border If present, show a border around the image
471 * align Horizontal alignment (left, right, center, none)
472 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
473 * bottom, text-bottom)
474 * alt Alternate text for image (i.e. alt attribute). Plain text.
475 * caption HTML for image caption.
476 * link-url URL to link to
477 * link-title Title object to link to
478 * link-target Value for the target attribue, only with link-url
479 * no-link Boolean, suppress description link
481 * @param $handlerParams Array: associative array of media handler parameters, to be passed
482 * to transform(). Typical keys are "width" and "page".
483 * @param $time String: timestamp of the file, set as false for current
484 * @param $query String: query params for desc url
485 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
486 * @return String: HTML for an image, with links, wrappers, etc.
488 public static function makeImageLink2( Title
$title, $file, $frameParams = array(),
489 $handlerParams = array(), $time = false, $query = "", $widthOption = null )
492 $dummy = new DummyLinker
;
493 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
494 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
498 if ( $file && !$file->allowInlineDisplay() ) {
499 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
500 return self
::link( $title );
505 $hp =& $handlerParams;
507 // Clean up parameters
508 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
509 if ( !isset( $fp['align'] ) ) {
512 if ( !isset( $fp['alt'] ) ) {
515 if ( !isset( $fp['title'] ) ) {
519 $prefix = $postfix = '';
521 if ( 'center' == $fp['align'] ) {
522 $prefix = '<div class="center">';
524 $fp['align'] = 'none';
526 if ( $file && !isset( $hp['width'] ) ) {
527 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
528 // If its a vector image, and user only specifies height
529 // we don't want it to be limited by its "normal" width.
530 global $wgSVGMaxSize;
531 $hp['width'] = $wgSVGMaxSize;
533 $hp['width'] = $file->getWidth( $page );
536 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
537 global $wgThumbLimits, $wgThumbUpright;
538 if ( !isset( $widthOption ) ||
!isset( $wgThumbLimits[$widthOption] ) ) {
539 $widthOption = User
::getDefaultOption( 'thumbsize' );
542 // Reduce width for upright images when parameter 'upright' is used
543 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
544 $fp['upright'] = $wgThumbUpright;
546 // 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
547 $prefWidth = isset( $fp['upright'] ) ?
548 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
549 $wgThumbLimits[$widthOption];
551 // Use width which is smaller: real image width or user preference width
552 // Unless image is scalable vector.
553 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
554 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
555 $hp['width'] = $prefWidth;
560 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
562 # Create a thumbnail. Alignment depends on language
563 # writing direction, # right aligned for left-to-right-
564 # languages ("Western languages"), left-aligned
565 # for right-to-left-languages ("Semitic languages")
567 # If thumbnail width has not been provided, it is set
568 # to the default user option as specified in Language*.php
569 if ( $fp['align'] == '' ) {
570 $fp['align'] = $wgContLang->alignEnd();
572 return $prefix . self
::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
575 if ( $file && isset( $fp['frameless'] ) ) {
576 $srcWidth = $file->getWidth( $page );
577 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
578 # This is the same behaviour as the "thumb" option does it already.
579 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
580 $hp['width'] = $srcWidth;
584 if ( $file && isset( $hp['width'] ) ) {
585 # Create a resized image, without the additional thumbnail features
586 $thumb = $file->transform( $hp );
592 $s = self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
596 'title' => $fp['title'],
597 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
598 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
599 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
601 $s = $thumb->toHtml( $params );
603 if ( $fp['align'] != '' ) {
604 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
606 return str_replace( "\n", ' ', $prefix . $s . $postfix );
610 * Get the link parameters for MediaTransformOutput::toHtml() from given
611 * frame parameters supplied by the Parser.
612 * @param $frameParams array The frame parameters
613 * @param $query string An optional query string to add to description page links
616 private static function getImageLinkMTOParams( $frameParams, $query = '' ) {
617 $mtoParams = array();
618 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
619 $mtoParams['custom-url-link'] = $frameParams['link-url'];
620 if ( isset( $frameParams['link-target'] ) ) {
621 $mtoParams['custom-target-link'] = $frameParams['link-target'];
623 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
624 $mtoParams['custom-title-link'] = self
::normaliseSpecialPage( $frameParams['link-title'] );
625 } elseif ( !empty( $frameParams['no-link'] ) ) {
628 $mtoParams['desc-link'] = true;
629 $mtoParams['desc-query'] = $query;
635 * Make HTML for a thumbnail including image, border and caption
636 * @param $title Title object
637 * @param $file File object or false if it doesn't exist
638 * @param $label String
640 * @param $align String
641 * @param $params Array
642 * @param $framed Boolean
643 * @param $manualthumb String
645 public static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt,
646 $align = 'right', $params = array(), $framed = false , $manualthumb = "" )
648 $frameParams = array(
654 $frameParams['framed'] = true;
656 if ( $manualthumb ) {
657 $frameParams['manualthumb'] = $manualthumb;
659 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
663 * @param $title Title
665 * @param array $frameParams
666 * @param array $handlerParams
668 * @param string $query
671 public static function makeThumbLink2( Title
$title, $file, $frameParams = array(),
672 $handlerParams = array(), $time = false, $query = "" )
674 global $wgStylePath, $wgContLang;
675 $exists = $file && $file->exists();
679 $hp =& $handlerParams;
681 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
682 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
683 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
684 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
685 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
687 if ( empty( $hp['width'] ) ) {
688 // Reduce width for upright images when parameter 'upright' is used
689 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
694 $outerWidth = $hp['width'] +
2;
696 if ( isset( $fp['manualthumb'] ) ) {
697 # Use manually specified thumbnail
698 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
699 if ( $manual_title ) {
700 $manual_img = wfFindFile( $manual_title );
702 $thumb = $manual_img->getUnscaledThumb( $hp );
707 } elseif ( isset( $fp['framed'] ) ) {
708 // Use image dimensions, don't scale
709 $thumb = $file->getUnscaledThumb( $hp );
711 # Do not present an image bigger than the source, for bitmap-style images
712 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
713 $srcWidth = $file->getWidth( $page );
714 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
715 $hp['width'] = $srcWidth;
717 $thumb = $file->transform( $hp );
721 $outerWidth = $thumb->getWidth() +
2;
723 $outerWidth = $hp['width'] +
2;
727 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
728 # So we don't need to pass it here in $query. However, the URL for the
729 # zoom icon still needs it, so we make a unique query for it. See bug 14771
730 $url = $title->getLocalURL( $query );
732 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
735 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
737 $s .= self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
739 } elseif ( !$thumb ) {
740 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
745 'title' => $fp['title'],
746 'img-class' => 'thumbimage' );
747 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
748 $s .= $thumb->toHtml( $params );
749 if ( isset( $fp['framed'] ) ) {
752 $zoomIcon = Html
::rawElement( 'div', array( 'class' => 'magnify' ),
753 Html
::rawElement( 'a', array(
755 'class' => 'internal',
756 'title' => wfMsg( 'thumbnail-more' ) ),
757 Html
::element( 'img', array(
758 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ?
'-rtl' : '' ) . '.png',
764 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
765 return str_replace( "\n", ' ', $s );
769 * Make a "broken" link to an image
771 * @param $title Title object
772 * @param $html String: link label in htmlescaped text form
773 * @param $query String: query string
774 * @param $trail String: link trail (HTML fragment)
775 * @param $prefix String: link prefix (HTML fragment)
776 * @param $time Boolean: a file of a certain timestamp was requested
779 public static function makeBrokenImageLinkObj( $title, $html = '', $query = '', $trail = '', $prefix = '', $time = false ) {
780 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
781 if ( ! $title instanceof Title
) {
782 return "<!-- ERROR -->{$prefix}{$html}{$trail}";
784 wfProfileIn( __METHOD__
);
785 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
787 list( $inside, $trail ) = self
::splitTrail( $trail );
789 $html = htmlspecialchars( $title->getPrefixedText() );
791 if ( ( $wgUploadMissingFileUrl ||
$wgUploadNavigationUrl ||
$wgEnableUploads ) && !$currentExists ) {
792 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
795 wfProfileOut( __METHOD__
);
796 return self
::linkKnown( $title, "$prefix$html$inside", array(), $query ) . $trail;
799 $href = self
::getUploadUrl( $title, $query );
801 wfProfileOut( __METHOD__
);
802 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
803 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
804 "$prefix$html$inside</a>$trail";
806 wfProfileOut( __METHOD__
);
807 return self
::linkKnown( $title, "$prefix$html$inside", array(), $query ) . $trail;
812 * Get the URL to upload a certain file
814 * @param $destFile Title object of the file to upload
815 * @param $query String: urlencoded query string to prepend
816 * @return String: urlencoded URL
818 protected static function getUploadUrl( $destFile, $query = '' ) {
819 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
820 $q = 'wpDestFile=' . $destFile->getPartialUrl();
824 if ( $wgUploadMissingFileUrl ) {
825 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
826 } elseif( $wgUploadNavigationUrl ) {
827 return wfAppendQuery( $wgUploadNavigationUrl, $q );
829 $upload = SpecialPage
::getTitleFor( 'Upload' );
830 return $upload->getLocalUrl( $q );
835 * Create a direct link to a given uploaded file.
837 * @param $title Title object.
838 * @param $html String: pre-sanitized HTML
839 * @param $time string: MW timestamp of file creation time
840 * @return String: HTML
842 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
843 $img = wfFindFile( $title, array( 'time' => $time ) );
844 return self
::makeMediaLinkFile( $title, $img, $html );
848 * Create a direct link to a given uploaded file.
849 * This will make a broken link if $file is false.
851 * @param $title Title object.
852 * @param $file File|bool mixed File object or false
853 * @param $html String: pre-sanitized HTML
854 * @return String: HTML
856 * @todo Handle invalid or missing images better.
858 public static function makeMediaLinkFile( Title
$title, $file, $html = '' ) {
859 if ( $file && $file->exists() ) {
860 $url = $file->getURL();
863 $url = self
::getUploadUrl( $title );
866 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES
);
870 $u = htmlspecialchars( $url );
871 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$html}</a>";
875 * Make a link to a special page given its name and, optionally,
876 * a message key from the link text.
877 * Usage example: Linker::specialLink( 'Recentchanges' )
881 public static function specialLink( $name, $key = '' ) {
883 $key = strtolower( $name );
886 return self
::linkKnown( SpecialPage
::getTitleFor( $name ) , wfMsg( $key ) );
890 * Make an external link
891 * @param $url String: URL to link to
892 * @param $text String: text of link
893 * @param $escape Boolean: do we escape the link text?
894 * @param $linktype String: type of external link. Gets added to the classes
895 * @param $attribs Array of extra attributes to <a>
897 public static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
900 $class .= " $linktype";
902 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
903 $class .= " {$attribs['class']}";
905 $attribs['class'] = $class;
908 $text = htmlspecialchars( $text );
911 $success = wfRunHooks( 'LinkerMakeExternalLink',
912 array( &$url, &$text, &$link, &$attribs, $linktype ) );
914 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
917 $attribs['href'] = $url;
918 return Html
::rawElement( 'a', $attribs, $text );
922 * Make user link (or user contributions for unregistered users)
923 * @param $userId Integer: user id in database.
924 * @param $userName String: user name in database.
925 * @param $altUserName String: text to display instead of the user name (optional)
926 * @return String: HTML fragment
927 * @since 1.19 Method exists for a long time. $displayText was added in 1.19.
929 public static function userLink( $userId, $userName, $altUserName = false ) {
930 if ( $userId == 0 ) {
931 $page = SpecialPage
::getTitleFor( 'Contributions', $userName );
933 $page = Title
::makeTitle( NS_USER
, $userName );
938 htmlspecialchars( $altUserName !== false ?
$altUserName : $userName ),
939 array( 'class' => 'mw-userlink' )
944 * Generate standard user tool links (talk, contributions, block link, etc.)
946 * @param $userId Integer: user identifier
947 * @param $userText String: user name or IP address
948 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
949 * red if the user has no edits?
950 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK and Linker::TOOL_LINKS_EMAIL)
951 * @param $edits Integer: user edit count (optional, for performance)
952 * @return String: HTML fragment
954 public static function userToolLinks(
955 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
957 global $wgUser, $wgDisableAnonTalk, $wgLang;
958 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
959 $blockable = !( $flags & self
::TOOL_LINKS_NOBLOCK
);
960 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
&& $userId;
964 $items[] = self
::userTalkLink( $userId, $userText );
967 // check if the user has an edit
969 if ( $redContribsWhenNoEdits ) {
970 $count = !is_null( $edits ) ?
$edits : User
::edits( $userId );
972 $attribs['class'] = 'new';
975 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
977 $items[] = self
::link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
979 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
980 $items[] = self
::blockLink( $userId, $userText );
983 if ( $addEmailLink && $wgUser->canSendEmail() ) {
984 $items[] = self
::emailLink( $userId, $userText );
987 wfRunHooks( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
990 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
997 * Alias for userToolLinks( $userId, $userText, true );
998 * @param $userId Integer: user identifier
999 * @param $userText String: user name or IP address
1000 * @param $edits Integer: user edit count (optional, for performance)
1002 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1003 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
1008 * @param $userId Integer: user id in database.
1009 * @param $userText String: user name in database.
1010 * @return String: HTML fragment with user talk link
1012 public static function userTalkLink( $userId, $userText ) {
1013 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
1014 $userTalkLink = self
::link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
1015 return $userTalkLink;
1019 * @param $userId Integer: userid
1020 * @param $userText String: user name in database.
1021 * @return String: HTML fragment with block link
1023 public static function blockLink( $userId, $userText ) {
1024 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1025 $blockLink = self
::link( $blockPage, wfMsgHtml( 'blocklink' ) );
1030 * @param $userId Integer: userid
1031 * @param $userText String: user name in database.
1032 * @return String: HTML fragment with e-mail user link
1034 public static function emailLink( $userId, $userText ) {
1035 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1036 $emailLink = self
::link( $emailPage, wfMsgHtml( 'emaillink' ) );
1041 * Generate a user link if the current user is allowed to view it
1042 * @param $rev Revision object.
1043 * @param $isPublic Boolean: show only if all users can see it
1044 * @return String: HTML fragment
1046 public static function revUserLink( $rev, $isPublic = false ) {
1047 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1048 $link = wfMsgHtml( 'rev-deleted-user' );
1049 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1050 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1051 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1053 $link = wfMsgHtml( 'rev-deleted-user' );
1055 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1056 return '<span class="history-deleted">' . $link . '</span>';
1062 * Generate a user tool link cluster if the current user is allowed to view it
1063 * @param $rev Revision object.
1064 * @param $isPublic Boolean: show only if all users can see it
1065 * @return string HTML
1067 public static function revUserTools( $rev, $isPublic = false ) {
1068 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1069 $link = wfMsgHtml( 'rev-deleted-user' );
1070 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1071 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1072 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1073 $link = self
::userLink( $userId, $userText ) .
1074 ' ' . self
::userToolLinks( $userId, $userText );
1076 $link = wfMsgHtml( 'rev-deleted-user' );
1078 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1079 return ' <span class="history-deleted">' . $link . '</span>';
1085 * This function is called by all recent changes variants, by the page history,
1086 * and by the user contributions list. It is responsible for formatting edit
1087 * comments. It escapes any HTML in the comment, but adds some CSS to format
1088 * auto-generated comments (from section editing) and formats [[wikilinks]].
1090 * @author Erik Moeller <moeller@scireview.de>
1092 * Note: there's not always a title to pass to this function.
1093 * Since you can't set a default parameter for a reference, I've turned it
1094 * temporarily to a value pass. Should be adjusted further. --brion
1096 * @param $comment String
1097 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1098 * @param $local Boolean: whether section links should refer to local page
1100 public static function formatComment( $comment, $title = null, $local = false ) {
1101 wfProfileIn( __METHOD__
);
1103 # Sanitize text a bit:
1104 $comment = str_replace( "\n", " ", $comment );
1105 # Allow HTML entities (for bug 13815)
1106 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1108 # Render autocomments and make links:
1109 $comment = self
::formatAutocomments( $comment, $title, $local );
1110 $comment = self
::formatLinksInComment( $comment, $title, $local );
1112 wfProfileOut( __METHOD__
);
1119 static $autocommentTitle;
1120 static $autocommentLocal;
1123 * The pattern for autogen comments is / * foo * /, which makes for
1125 * We look for all comments, match any text before and after the comment,
1126 * add a separator where needed and format the comment itself with CSS
1127 * Called by Linker::formatComment.
1129 * @param $comment String: comment text
1130 * @param $title Title|null An optional title object used to links to sections
1131 * @param $local Boolean: whether section links should refer to local page
1132 * @return String: formatted comment
1134 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1136 self
::$autocommentTitle = $title;
1137 self
::$autocommentLocal = $local;
1138 $comment = preg_replace_callback(
1139 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1140 array( 'Linker', 'formatAutocommentsCallback' ),
1142 self
::$autocommentTitle = null;
1143 self
::$autocommentLocal = null;
1151 private static function formatAutocommentsCallback( $match ) {
1153 $title = self
::$autocommentTitle;
1154 $local = self
::$autocommentLocal;
1163 # Remove links that a user may have manually put in the autosummary
1164 # This could be improved by copying as much of Parser::stripSectionName as desired.
1165 $section = str_replace( '[[:', '', $section );
1166 $section = str_replace( '[[', '', $section );
1167 $section = str_replace( ']]', '', $section );
1169 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1171 $sectionTitle = Title
::newFromText( '#' . $section );
1173 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1174 $title->getDBkey(), $section );
1176 if ( $sectionTitle ) {
1177 $link = self
::link( $sectionTitle,
1178 $wgLang->getArrow(), array(), array(),
1185 # written summary $presep autocomment (summary /* section */)
1186 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1189 # autocomment $postsep written summary (/* section */ summary)
1190 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1192 $auto = '<span class="autocomment">' . $auto . '</span>';
1193 $comment = $pre . $link . $wgLang->getDirMark() . '<span dir="auto">' . $auto . $post . '</span>';
1200 static $commentContextTitle;
1201 static $commentLocal;
1204 * Formats wiki links and media links in text; all other wiki formatting
1207 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1208 * @param $comment String: text to format links in
1209 * @param $title Title|null An optional title object used to links to sections
1210 * @param $local Boolean: whether section links should refer to local page
1213 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1214 self
::$commentContextTitle = $title;
1215 self
::$commentLocal = $local;
1216 $html = preg_replace_callback(
1217 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1218 array( 'Linker', 'formatLinksInCommentCallback' ),
1220 self
::$commentContextTitle = null;
1221 self
::$commentLocal = null;
1229 protected static function formatLinksInCommentCallback( $match ) {
1232 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1233 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1235 $comment = $match[0];
1237 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1238 if ( strpos( $match[1], '%' ) !== false ) {
1239 $match[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $match[1] ) );
1242 # Handle link renaming [[foo|text]] will show link as "text"
1243 if ( $match[3] != "" ) {
1248 $submatch = array();
1250 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1251 # Media link; trail not supported.
1252 $linkRegexp = '/\[\[(.*?)\]\]/';
1253 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1255 $thelink = self
::makeMediaLinkObj( $title, $text );
1258 # Other kind of link
1259 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1260 $trail = $submatch[1];
1264 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1265 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1266 $match[1] = substr( $match[1], 1 );
1267 list( $inside, $trail ) = self
::splitTrail( $trail );
1270 $linkTarget = self
::normalizeSubpageLink( self
::$commentContextTitle,
1271 $match[1], $linkText );
1273 $target = Title
::newFromText( $linkTarget );
1275 if ( $target->getText() == '' && $target->getInterwiki() === ''
1276 && !self
::$commentLocal && self
::$commentContextTitle )
1278 $newTarget = clone ( self
::$commentContextTitle );
1279 $newTarget->setFragment( '#' . $target->getFragment() );
1280 $target = $newTarget;
1282 $thelink = self
::link(
1289 // If the link is still valid, go ahead and replace it in!
1290 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1297 * @param $contextTitle Title
1302 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1305 # :Foobar -- override special treatment of prefix (images, language links)
1306 # /Foobar -- convert to CurrentPage/Foobar
1307 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1308 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1309 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1311 wfProfileIn( __METHOD__
);
1312 $ret = $target; # default return value is no change
1314 # Some namespaces don't allow subpages,
1315 # so only perform processing if subpages are allowed
1316 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1317 $hash = strpos( $target, '#' );
1318 if ( $hash !== false ) {
1319 $suffix = substr( $target, $hash );
1320 $target = substr( $target, 0, $hash );
1325 $target = trim( $target );
1326 # Look at the first character
1327 if ( $target != '' && $target[0] === '/' ) {
1328 # / at end means we don't want the slash to be shown
1330 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1331 if ( $trailingSlashes ) {
1332 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1334 $noslash = substr( $target, 1 );
1337 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1338 if ( $text === '' ) {
1339 $text = $target . $suffix;
1340 } # this might be changed for ugliness reasons
1342 # check for .. subpage backlinks
1344 $nodotdot = $target;
1345 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1347 $nodotdot = substr( $nodotdot, 3 );
1349 if ( $dotdotcount > 0 ) {
1350 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1351 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1352 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1353 # / at the end means don't show full path
1354 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1355 $nodotdot = substr( $nodotdot, 0, -1 );
1356 if ( $text === '' ) {
1357 $text = $nodotdot . $suffix;
1360 $nodotdot = trim( $nodotdot );
1361 if ( $nodotdot != '' ) {
1362 $ret .= '/' . $nodotdot;
1370 wfProfileOut( __METHOD__
);
1375 * Wrap a comment in standard punctuation and formatting if
1376 * it's non-empty, otherwise return empty string.
1378 * @param $comment String
1379 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1380 * @param $local Boolean: whether section links should refer to local page
1384 public static function commentBlock( $comment, $title = null, $local = false ) {
1385 // '*' used to be the comment inserted by the software way back
1386 // in antiquity in case none was provided, here for backwards
1387 // compatability, acc. to brion -ævar
1388 if ( $comment == '' ||
$comment == '*' ) {
1391 $formatted = self
::formatComment( $comment, $title, $local );
1392 return " <span class=\"comment\" dir=\"auto\">($formatted)</span>";
1397 * Wrap and format the given revision's comment block, if the current
1398 * user is allowed to view it.
1400 * @param $rev Revision object
1401 * @param $local Boolean: whether section links should refer to local page
1402 * @param $isPublic Boolean: show only if all users can see it
1403 * @return String: HTML fragment
1405 public static function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1406 if ( $rev->getRawComment() == "" ) {
1409 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1410 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1411 } elseif ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1412 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1413 $rev->getTitle(), $local );
1415 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1417 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1418 return " <span class=\"history-deleted\">$block</span>";
1427 public static function formatRevisionSize( $size ) {
1429 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1432 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1435 $stxt = htmlspecialchars( $stxt );
1436 return "<span class=\"history-size\">$stxt</span>";
1440 * Add another level to the Table of Contents
1444 public static function tocIndent() {
1449 * Finish one or more sublevels on the Table of Contents
1453 public static function tocUnindent( $level ) {
1454 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1458 * parameter level defines if we are on an indentation level
1462 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1463 $classes = "toclevel-$level";
1464 if ( $sectionIndex !== false ) {
1465 $classes .= " tocsection-$sectionIndex";
1467 return "\n<li class=\"$classes\"><a href=\"#" .
1468 $anchor . '"><span class="tocnumber">' .
1469 $tocnumber . '</span> <span class="toctext">' .
1470 $tocline . '</span></a>';
1474 * End a Table Of Contents line.
1475 * tocUnindent() will be used instead if we're ending a line below
1478 public static function tocLineEnd() {
1483 * Wraps the TOC in a table and provides the hide/collapse javascript.
1485 * @param $toc String: html of the Table Of Contents
1486 * @param $lang mixed: Language code for the toc title
1487 * @return String: full html of the TOC
1489 public static function tocList( $toc, $lang = false ) {
1490 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1492 '<table id="toc" class="toc"><tr><td>'
1493 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1495 . "</ul>\n</td></tr></table>\n";
1499 * Generate a table of contents from a section tree
1502 * @param $tree array Return value of ParserOutput::getSections()
1503 * @return String: HTML fragment
1505 public static function generateTOC( $tree ) {
1508 foreach ( $tree as $section ) {
1509 if ( $section['toclevel'] > $lastLevel )
1510 $toc .= self
::tocIndent();
1511 elseif ( $section['toclevel'] < $lastLevel )
1512 $toc .= self
::tocUnindent(
1513 $lastLevel - $section['toclevel'] );
1515 $toc .= self
::tocLineEnd();
1517 $toc .= self
::tocLine( $section['anchor'],
1518 $section['line'], $section['number'],
1519 $section['toclevel'], $section['index'] );
1520 $lastLevel = $section['toclevel'];
1522 $toc .= self
::tocLineEnd();
1523 return self
::tocList( $toc );
1527 * Create a headline for content
1529 * @param $level Integer: the level of the headline (1-6)
1530 * @param $attribs String: any attributes for the headline, starting with
1531 * a space and ending with '>'
1532 * This *must* be at least '>' for no attribs
1533 * @param $anchor String: the anchor to give the headline (the bit after the #)
1534 * @param $html String: html for the text of the header
1535 * @param $link String: HTML to add for the section edit link
1536 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1537 * backward compatibility (false to omit)
1539 * @return String: HTML headline
1541 public static function makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor = false ) {
1542 $ret = "<h$level$attribs"
1544 . " <span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1546 if ( $legacyAnchor !== false ) {
1547 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1553 * Split a link trail, return the "inside" portion and the remainder of the trail
1554 * as a two-element array
1556 static function splitTrail( $trail ) {
1558 $regex = $wgContLang->linkTrail();
1560 if ( $trail !== '' ) {
1562 if ( preg_match( $regex, $trail, $m ) ) {
1567 return array( $inside, $trail );
1571 * Generate a rollback link for a given revision. Currently it's the
1572 * caller's responsibility to ensure that the revision is the top one. If
1573 * it's not, of course, the user will get an error message.
1575 * If the calling page is called with the parameter &bot=1, all rollback
1576 * links also get that parameter. It causes the edit itself and the rollback
1577 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1578 * changes, so this allows sysops to combat a busy vandal without bothering
1581 * @param $rev Revision object
1583 public static function generateRollback( $rev ) {
1584 return '<span class="mw-rollback-link">['
1585 . self
::buildRollbackLink( $rev )
1590 * Build a raw rollback link, useful for collections of "tool" links
1592 * @param $rev Revision object
1593 * @return String: HTML fragment
1595 public static function buildRollbackLink( $rev ) {
1596 global $wgRequest, $wgUser;
1597 $title = $rev->getTitle();
1599 'action' => 'rollback',
1600 'from' => $rev->getUserText(),
1601 'token' => $wgUser->getEditToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1603 if ( $wgRequest->getBool( 'bot' ) ) {
1604 $query['bot'] = '1';
1605 $query['hidediff'] = '1'; // bug 15999
1609 wfMsgHtml( 'rollbacklink' ),
1610 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1612 array( 'known', 'noclasses' )
1617 * Returns HTML for the "templates used on this page" list.
1619 * @param $templates Array of templates from Article::getUsedTemplate
1621 * @param $preview Boolean: whether this is for a preview
1622 * @param $section Boolean: whether this is for a section edit
1623 * @return String: HTML output
1625 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1626 wfProfileIn( __METHOD__
);
1629 if ( count( $templates ) > 0 ) {
1630 # Do a batch existence check
1631 $batch = new LinkBatch
;
1632 foreach ( $templates as $title ) {
1633 $batch->addObj( $title );
1637 # Construct the HTML
1638 $outText = '<div class="mw-templatesUsedExplanation">';
1640 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1641 } elseif ( $section ) {
1642 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1644 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1646 $outText .= "</div><ul>\n";
1648 usort( $templates, array( 'Title', 'compare' ) );
1649 foreach ( $templates as $titleObj ) {
1650 $r = $titleObj->getRestrictions( 'edit' );
1651 if ( in_array( 'sysop', $r ) ) {
1652 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1653 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1654 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1658 if ( $titleObj->quickUserCan( 'edit' ) ) {
1659 $editLink = self
::link(
1661 wfMsg( 'editlink' ),
1663 array( 'action' => 'edit' )
1666 $editLink = self
::link(
1668 wfMsg( 'viewsourcelink' ),
1670 array( 'action' => 'edit' )
1673 $outText .= '<li>' . self
::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1675 $outText .= '</ul>';
1677 wfProfileOut( __METHOD__
);
1682 * Returns HTML for the "hidden categories on this page" list.
1684 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1686 * @return String: HTML output
1688 public static function formatHiddenCategories( $hiddencats ) {
1690 wfProfileIn( __METHOD__
);
1693 if ( count( $hiddencats ) > 0 ) {
1694 # Construct the HTML
1695 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1696 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1697 $outText .= "</div><ul>\n";
1699 foreach ( $hiddencats as $titleObj ) {
1700 $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
1702 $outText .= '</ul>';
1704 wfProfileOut( __METHOD__
);
1709 * Format a size in bytes for output, using an appropriate
1710 * unit (B, KB, MB or GB) according to the magnitude in question
1712 * @param $size int Size to format
1715 public static function formatSize( $size ) {
1717 return htmlspecialchars( $wgLang->formatSize( $size ) );
1721 * Given the id of an interface element, constructs the appropriate title
1722 * attribute from the system messages. (Note, this is usually the id but
1723 * isn't always, because sometimes the accesskey needs to go on a different
1724 * element than the id, for reverse-compatibility, etc.)
1726 * @param $name String: id of the element, minus prefixes.
1727 * @param $options Mixed: null or the string 'withaccess' to add an access-
1729 * @return String: contents of the title attribute (which you must HTML-
1730 * escape), or false for no title attribute
1732 public static function titleAttrib( $name, $options = null ) {
1733 wfProfileIn( __METHOD__
);
1735 $message = wfMessage( "tooltip-$name" );
1737 if ( !$message->exists() ) {
1740 $tooltip = $message->text();
1741 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1742 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1743 # Message equal to '-' means suppress it.
1744 if ( $tooltip == '-' ) {
1749 if ( $options == 'withaccess' ) {
1750 $accesskey = self
::accesskey( $name );
1751 if ( $accesskey !== false ) {
1752 if ( $tooltip === false ||
$tooltip === '' ) {
1753 $tooltip = "[$accesskey]";
1755 $tooltip .= " [$accesskey]";
1760 wfProfileOut( __METHOD__
);
1764 static $accesskeycache;
1767 * Given the id of an interface element, constructs the appropriate
1768 * accesskey attribute from the system messages. (Note, this is usually
1769 * the id but isn't always, because sometimes the accesskey needs to go on
1770 * a different element than the id, for reverse-compatibility, etc.)
1772 * @param $name String: id of the element, minus prefixes.
1773 * @return String: contents of the accesskey attribute (which you must HTML-
1774 * escape), or false for no accesskey attribute
1776 public static function accesskey( $name ) {
1777 if ( isset( self
::$accesskeycache[$name] ) ) {
1778 return self
::$accesskeycache[$name];
1780 wfProfileIn( __METHOD__
);
1782 $message = wfMessage( "accesskey-$name" );
1784 if ( !$message->exists() ) {
1787 $accesskey = $message->plain();
1788 if ( $accesskey === '' ||
$accesskey === '-' ) {
1789 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
1790 # attribute, but this is broken for accesskey: that might be a useful
1796 wfProfileOut( __METHOD__
);
1797 return self
::$accesskeycache[$name] = $accesskey;
1801 * Get a revision-deletion link, or disabled link, or nothing, depending
1802 * on user permissions & the settings on the revision.
1804 * Will use forward-compatible revision ID in the Special:RevDelete link
1805 * if possible, otherwise the timestamp-based ID which may break after
1809 * @param Revision $rev
1810 * @param Revision $title
1811 * @return string HTML fragment
1813 public static function getRevDeleteLink( User
$user, Revision
$rev, Title
$title ) {
1814 $canHide = $user->isAllowed( 'deleterevision' );
1815 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
1819 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
1820 return Linker
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
1822 if ( $rev->getId() ) {
1823 // RevDelete links using revision ID are stable across
1824 // page deletion and undeletion; use when possible.
1826 'type' => 'revision',
1827 'target' => $title->getPrefixedDBkey(),
1828 'ids' => $rev->getId()
1831 // Older deleted entries didn't save a revision ID.
1832 // We have to refer to these by timestamp, ick!
1834 'type' => 'archive',
1835 'target' => $title->getPrefixedDBkey(),
1836 'ids' => $rev->getTimestamp()
1839 return Linker
::revDeleteLink( $query,
1840 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
1845 * Creates a (show/hide) link for deleting revisions/log entries
1847 * @param $query Array: query parameters to be passed to link()
1848 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1849 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1851 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1852 * span to allow for customization of appearance with CSS
1854 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1855 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1856 $html = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1857 $tag = $restricted ?
'strong' : 'span';
1858 $link = self
::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
1859 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1863 * Creates a dead (show/hide) link for deleting revisions/log entries
1865 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1867 * @return string HTML text wrapped in a span to allow for customization
1868 * of appearance with CSS
1870 public static function revDeleteLinkDisabled( $delete = true ) {
1871 $html = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1872 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($html)" );
1875 /* Deprecated methods */
1878 * @deprecated since 1.16 Use link()
1880 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1881 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1883 * @param $title String: The text of the title
1884 * @param $text String: Link text
1885 * @param $query String: Optional query part
1886 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1887 * be included in the link text. Other characters will be appended after
1888 * the end of the link.
1890 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1891 wfDeprecated( __METHOD__
, '1.16' );
1893 $nt = Title
::newFromText( $title );
1894 if ( $nt instanceof Title
) {
1895 return self
::makeBrokenLinkObj( $nt, $text, $query, $trail );
1897 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
1898 return $text == '' ?
$title : $text;
1903 * @deprecated since 1.16 Use link()
1905 * Make a link for a title which may or may not be in the database. If you need to
1906 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1907 * call to this will result in a DB query.
1909 * @param $nt Title: the title object to make the link from, e.g. from
1910 * Title::newFromText.
1911 * @param $text String: link text
1912 * @param $query String: optional query part
1913 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1914 * be included in the link text. Other characters will be appended after
1915 * the end of the link.
1916 * @param $prefix String: optional prefix. As trail, only before instead of after.
1918 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1919 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
1921 wfProfileIn( __METHOD__
);
1922 $query = wfCgiToArray( $query );
1923 list( $inside, $trail ) = self
::splitTrail( $trail );
1924 if ( $text === '' ) {
1925 $text = self
::linkText( $nt );
1928 $ret = self
::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1930 wfProfileOut( __METHOD__
);
1935 * @deprecated since 1.16 Use link()
1937 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1938 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1941 * @param $title Title object of target page
1942 * @param $text String: text to replace the title
1943 * @param $query String: link target
1944 * @param $trail String: text after link
1945 * @param $prefix String: text before link text
1946 * @param $aprops String: extra attributes to the a-element
1947 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1948 * @return string the a-element
1950 static function makeKnownLinkObj(
1951 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
1953 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
1955 wfProfileIn( __METHOD__
);
1957 if ( $text == '' ) {
1958 $text = self
::linkText( $title );
1960 $attribs = Sanitizer
::mergeAttributes(
1961 Sanitizer
::decodeTagAttributes( $aprops ),
1962 Sanitizer
::decodeTagAttributes( $style )
1964 $query = wfCgiToArray( $query );
1965 list( $inside, $trail ) = self
::splitTrail( $trail );
1967 $ret = self
::link( $title, "$prefix$text$inside", $attribs, $query,
1968 array( 'known', 'noclasses' ) ) . $trail;
1970 wfProfileOut( __METHOD__
);
1975 * @deprecated since 1.16 Use link()
1977 * Make a red link to the edit page of a given title.
1979 * @param $title Title object of the target page
1980 * @param $text String: Link text
1981 * @param $query String: Optional query part
1982 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1983 * be included in the link text. Other characters will be appended after
1984 * the end of the link.
1985 * @param $prefix String: Optional prefix
1987 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
1988 wfDeprecated( __METHOD__
, '1.16' );
1990 wfProfileIn( __METHOD__
);
1992 list( $inside, $trail ) = self
::splitTrail( $trail );
1993 if ( $text === '' ) {
1994 $text = self
::linkText( $title );
1997 $ret = self
::link( $title, "$prefix$text$inside", array(),
1998 wfCgiToArray( $query ), 'broken' ) . $trail;
2000 wfProfileOut( __METHOD__
);
2005 * @deprecated since 1.16 Use link()
2007 * Make a coloured link.
2009 * @param $nt Title object of the target page
2010 * @param $colour Integer: colour of the link
2011 * @param $text String: link text
2012 * @param $query String: optional query part
2013 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2014 * be included in the link text. Other characters will be appended after
2015 * the end of the link.
2016 * @param $prefix String: Optional prefix
2018 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2019 wfDeprecated( __METHOD__
, '1.16' );
2021 if ( $colour != '' ) {
2022 $style = self
::getInternalLinkAttributesObj( $nt, $text, $colour );
2026 return self
::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2030 * Returns the attributes for the tooltip and access key.
2032 public static function tooltipAndAccesskeyAttribs( $name ) {
2033 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2034 # no attribute" instead of "output '' as value for attribute", this
2035 # would be three lines.
2037 'title' => self
::titleAttrib( $name, 'withaccess' ),
2038 'accesskey' => self
::accesskey( $name )
2040 if ( $attribs['title'] === false ) {
2041 unset( $attribs['title'] );
2043 if ( $attribs['accesskey'] === false ) {
2044 unset( $attribs['accesskey'] );
2050 * Returns raw bits of HTML, use titleAttrib()
2052 public static function tooltip( $name, $options = null ) {
2053 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2054 # no attribute" instead of "output '' as value for attribute", this
2055 # would be two lines.
2056 $tooltip = self
::titleAttrib( $name, $options );
2057 if ( $tooltip === false ) {
2060 return Xml
::expandAttributes( array(
2072 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2073 * into static calls to the new Linker for backwards compatibility.
2075 * @param $fname String Name of called method
2076 * @param $args Array Arguments to the method
2078 public function __call( $fname, $args ) {
2079 return call_user_func_array( array( 'Linker', $fname ), $args );