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;
17 * Get the appropriate HTML attributes to add to the "a" element of an ex-
18 * ternal link, as created by [wikisyntax].
20 * @param $class String: the contents of the class attribute; if an empty
21 * string is passed, which is the default value, defaults to 'external'.
22 * @deprecated since 1.18 Just pass the external class directly to something using Html::expandAttributes
24 static function getExternalLinkAttributes( $class = 'external' ) {
25 wfDeprecated( __METHOD__
);
26 return self
::getLinkAttributesInternal( '', $class );
30 * Get the appropriate HTML attributes to add to the "a" element of an in-
33 * @param $title String: the title text for the link, URL-encoded (???) but
35 * @param $unused String: unused
36 * @param $class String: the contents of the class attribute; if an empty
37 * string is passed, which is the default value, defaults to 'external'.
39 static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
42 # FIXME: We have a whole bunch of handling here that doesn't happen in
43 # getExternalLinkAttributes, why?
44 $title = urldecode( $title );
45 $title = $wgContLang->checkTitleEncoding( $title );
46 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
48 return self
::getLinkAttributesInternal( $title, $class );
52 * Get the appropriate HTML attributes to add to the "a" element of an in-
55 * @param $title String: the title text for the link, URL-encoded (???) but
57 * @param $unused String: unused
58 * @param $class String: the contents of the class attribute, default none
60 static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
61 $title = urldecode( $title );
62 $title = str_replace( '_', ' ', $title );
63 return self
::getLinkAttributesInternal( $title, $class );
67 * Get the appropriate HTML attributes to add to the "a" element of an in-
68 * ternal link, given the Title object for the page we want to link to.
71 * @param $unused String: unused
72 * @param $class String: the contents of the class attribute, default none
73 * @param $title Mixed: optional (unescaped) string to use in the title
74 * attribute; if false, default to the name of the page we're linking to
76 static function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
77 if ( $title === false ) {
78 $title = $nt->getPrefixedText();
80 return self
::getLinkAttributesInternal( $title, $class );
84 * Common code for getLinkAttributesX functions
86 private static function getLinkAttributesInternal( $title, $class ) {
87 $title = htmlspecialchars( $title );
88 $class = htmlspecialchars( $class );
91 $r .= " class=\"$class\"";
94 $r .= " title=\"$title\"";
100 * Return the CSS colour of a known link
102 * @param $t Title object
103 * @param $threshold Integer: user defined threshold
104 * @return String: CSS class
106 static function getLinkColour( $t, $threshold ) {
108 if ( $t->isRedirect() ) {
110 $colour = 'mw-redirect';
111 } elseif ( $threshold > 0 &&
112 $t->exists() && $t->getLength() < $threshold &&
113 $t->isContentPage() ) {
121 * This function returns an HTML link to the given target. It serves a few
123 * 1) If $target is a Title, the correct URL to link to will be figured
125 * 2) It automatically adds the usual classes for various types of link
126 * targets: "new" for red links, "stub" for short articles, etc.
127 * 3) It escapes all attribute values safely so there's no risk of XSS.
128 * 4) It provides a default tooltip if the target is a Title (the page
129 * name of the target).
130 * link() replaces the old functions in the makeLink() family.
132 * @param $target Title Can currently only be a Title, but this may
133 * change to support Images, literal URLs, etc.
134 * @param $text string The HTML contents of the <a> element, i.e.,
135 * the link text. This is raw HTML and will not be escaped. If null,
136 * defaults to the prefixed text of the Title; or if the Title is just a
137 * fragment, the contents of the fragment.
138 * @param $customAttribs array A key => value array of extra HTML attri-
139 * butes, such as title and class. (href is ignored.) Classes will be
140 * merged with the default classes, while other attributes will replace
141 * default attributes. All passed attribute values will be HTML-escaped.
142 * A false attribute value means to suppress that attribute.
143 * @param $query array The query string to append to the URL
144 * you're linking to, in key => value array form. Query keys and values
145 * will be URL-encoded.
146 * @param $options mixed String or array of strings:
147 * 'known': Page is known to exist, so don't check if it does.
148 * 'broken': Page is known not to exist, so don't check if it does.
149 * 'noclasses': Don't add any classes automatically (includes "new",
150 * "stub", "mw-redirect", "extiw"). Only use the class attribute
151 * provided, if any, so you get a simple blue link with no funny i-
153 * 'forcearticlepath': Use the article path always, even with a querystring.
154 * Has compatibility issues on some setups, so avoid wherever possible.
155 * @return string HTML <a> attribute
157 public static function link(
158 $target, $html = null, $customAttribs = array(), $query = array(), $options = array()
160 wfProfileIn( __METHOD__
);
161 if ( !$target instanceof Title
) {
162 wfProfileOut( __METHOD__
);
163 return "<!-- ERROR -->$html";
165 $options = (array)$options;
167 $dummy = new DummyLinker
; // dummy linker instance for bc on the hooks
170 if ( !wfRunHooks( 'LinkBegin', array( $dummy, $target, &$html,
171 &$customAttribs, &$query, &$options, &$ret ) ) ) {
172 wfProfileOut( __METHOD__
);
176 # Normalize the Title if it's a special page
177 $target = self
::normaliseSpecialPage( $target );
179 # If we don't know whether the page exists, let's find out.
180 wfProfileIn( __METHOD__
. '-checkPageExistence' );
181 if ( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
182 if ( $target->isKnown() ) {
183 $options[] = 'known';
185 $options[] = 'broken';
188 wfProfileOut( __METHOD__
. '-checkPageExistence' );
191 if ( in_array( "forcearticlepath", $options ) && $query ) {
196 # Note: we want the href attribute first, for prettiness.
197 $attribs = array( 'href' => self
::linkUrl( $target, $query, $options ) );
198 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
199 $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
202 $attribs = array_merge(
204 self
::linkAttribs( $target, $customAttribs, $options )
206 if ( is_null( $html ) ) {
207 $html = self
::linkText( $target );
211 if ( wfRunHooks( 'LinkEnd', array( $dummy, $target, $options, &$html, &$attribs, &$ret ) ) ) {
212 $ret = Html
::rawElement( 'a', $attribs, $html );
215 wfProfileOut( __METHOD__
);
220 * Identical to link(), except $options defaults to 'known'.
222 public static function linkKnown(
223 $target, $text = null, $customAttribs = array(),
224 $query = array(), $options = array( 'known', 'noclasses' ) )
226 return self
::link( $target, $text, $customAttribs, $query, $options );
230 * Returns the Url used to link to a Title
232 * @param $target Title
234 private static function linkUrl( $target, $query, $options ) {
235 wfProfileIn( __METHOD__
);
236 # We don't want to include fragments for broken links, because they
237 # generally make no sense.
238 if ( in_array( 'broken', $options ) && $target->mFragment
!== '' ) {
239 $target = clone $target;
240 $target->mFragment
= '';
243 # If it's a broken link, add the appropriate query pieces, unless
244 # there's already an action specified, or unless 'edit' makes no sense
245 # (i.e., for a nonexistent special page).
246 if ( in_array( 'broken', $options ) && empty( $query['action'] )
247 && $target->getNamespace() != NS_SPECIAL
) {
248 $query['action'] = 'edit';
249 $query['redlink'] = '1';
251 $ret = $target->getLinkUrl( $query );
252 wfProfileOut( __METHOD__
);
257 * Returns the array of attributes used when linking to the Title $target
259 * @param $target Title
261 private static function linkAttribs( $target, $attribs, $options ) {
262 wfProfileIn( __METHOD__
);
266 if ( !in_array( 'noclasses', $options ) ) {
267 wfProfileIn( __METHOD__
. '-getClasses' );
268 # Now build the classes.
271 if ( in_array( 'broken', $options ) ) {
275 if ( $target->isExternal() ) {
276 $classes[] = 'extiw';
279 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
280 $colour = self
::getLinkColour( $target, $wgUser->getStubThreshold() );
281 if ( $colour !== '' ) {
282 $classes[] = $colour; # mw-redirect or stub
285 if ( $classes != array() ) {
286 $defaults['class'] = implode( ' ', $classes );
288 wfProfileOut( __METHOD__
. '-getClasses' );
291 # Get a default title attribute.
292 if ( $target->getPrefixedText() == '' ) {
293 # A link like [[#Foo]]. This used to mean an empty title
294 # attribute, but that's silly. Just don't output a title.
295 } elseif ( in_array( 'known', $options ) ) {
296 $defaults['title'] = $target->getPrefixedText();
298 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
301 # Finally, merge the custom attribs with the default ones, and iterate
302 # over that, deleting all "false" attributes.
304 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
305 foreach ( $merged as $key => $val ) {
306 # A false value suppresses the attribute, and we don't want the
307 # href attribute to be overridden.
308 if ( $key != 'href' and $val !== false ) {
312 wfProfileOut( __METHOD__
);
317 * Default text of the links to the Title $target
319 * @param $target Title
323 private static function linkText( $target ) {
324 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
325 if ( !$target instanceof Title
) {
329 # If the target is just a fragment, with no title, we return the frag-
330 # ment text. Otherwise, we return the title text itself.
331 if ( $target->getPrefixedText() === '' && $target->getFragment() !== '' ) {
332 return htmlspecialchars( $target->getFragment() );
334 return htmlspecialchars( $target->getPrefixedText() );
338 * Generate either a normal exists-style link or a stub link, depending
339 * on the given page size.
341 * @param $size Integer
342 * @param $nt Title object.
343 * @param $text String
344 * @param $query String
345 * @param $trail String
346 * @param $prefix String
347 * @return string HTML of link
348 * @deprecated since 1.17
350 static function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
352 wfDeprecated( __METHOD__
);
354 $threshold = $wgUser->getStubThreshold();
355 $colour = ( $size < $threshold ) ?
'stub' : '';
356 // FIXME: replace deprecated makeColouredLinkObj by link()
357 return self
::makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
361 * Make appropriate markup for a link to the current article. This is currently rendered
362 * as the bold link text. The calling sequence is the same as the other make*LinkObj static functions,
363 * despite $query not being used.
369 static function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
371 $text = htmlspecialchars( $nt->getPrefixedText() );
373 list( $inside, $trail ) = self
::splitTrail( $trail );
374 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
378 * @param $title Title
381 static function normaliseSpecialPage( Title
$title ) {
382 if ( $title->getNamespace() == NS_SPECIAL
) {
383 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
387 $ret = SpecialPage
::getTitleFor( $name, $subpage );
388 $ret->mFragment
= $title->getFragment();
396 * Returns the filename part of an url.
397 * Used as alternative text for external images.
403 static function fnamePart( $url ) {
404 $basename = strrchr( $url, '/' );
405 if ( false === $basename ) {
408 $basename = substr( $basename, 1 );
414 * Return the code for images which were added via external links,
415 * via Parser::maybeMakeExternalImage().
422 static function makeExternalImage( $url, $alt = '' ) {
424 $alt = self
::fnamePart( $url );
427 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
429 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
432 return Html
::element( 'img',
439 * Given parameters derived from [[Image:Foo|options...]], generate the
440 * HTML that that syntax inserts in the page.
442 * @param $title Title object
443 * @param $file File object, or false if it doesn't exist
444 * @param $frameParams Array: associative array of parameters external to the media handler.
445 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
446 * will often be false.
447 * thumbnail If present, downscale and frame
448 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
449 * framed Shows image in original size in a frame
450 * frameless Downscale but don't frame
451 * upright If present, tweak default sizes for portrait orientation
452 * upright_factor Fudge factor for "upright" tweak (default 0.75)
453 * border If present, show a border around the image
454 * align Horizontal alignment (left, right, center, none)
455 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
456 * bottom, text-bottom)
457 * alt Alternate text for image (i.e. alt attribute). Plain text.
458 * caption HTML for image caption.
459 * link-url URL to link to
460 * link-title Title object to link to
461 * link-target Value for the target attribue, only with link-url
462 * no-link Boolean, suppress description link
464 * @param $handlerParams Array: associative array of media handler parameters, to be passed
465 * to transform(). Typical keys are "width" and "page".
466 * @param $time String: timestamp of the file, set as false for current
467 * @param $query String: query params for desc url
468 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
469 * @return String: HTML for an image, with links, wrappers, etc.
471 static function makeImageLink2( Title
$title, $file, $frameParams = array(),
472 $handlerParams = array(), $time = false, $query = "", $widthOption = null )
475 $dummy = new DummyLinker
;
476 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
477 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
481 if ( $file && !$file->allowInlineDisplay() ) {
482 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
483 return self
::link( $title );
488 $hp =& $handlerParams;
490 // Clean up parameters
491 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
492 if ( !isset( $fp['align'] ) ) {
495 if ( !isset( $fp['alt'] ) ) {
498 if ( !isset( $fp['title'] ) ) {
502 $prefix = $postfix = '';
504 if ( 'center' == $fp['align'] ) {
505 $prefix = '<div class="center">';
507 $fp['align'] = 'none';
509 if ( $file && !isset( $hp['width'] ) ) {
510 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
511 // If its a vector image, and user only specifies height
512 // we don't want it to be limited by its "normal" width.
513 global $wgSVGMaxSize;
514 $hp['width'] = $wgSVGMaxSize;
516 $hp['width'] = $file->getWidth( $page );
519 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
520 global $wgThumbLimits, $wgThumbUpright;
521 if ( !isset( $widthOption ) ||
!isset( $wgThumbLimits[$widthOption] ) ) {
522 $widthOption = User
::getDefaultOption( 'thumbsize' );
525 // Reduce width for upright images when parameter 'upright' is used
526 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
527 $fp['upright'] = $wgThumbUpright;
529 // 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
530 $prefWidth = isset( $fp['upright'] ) ?
531 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
532 $wgThumbLimits[$widthOption];
534 // Use width which is smaller: real image width or user preference width
535 // Unless image is scalable vector.
536 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
537 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
538 $hp['width'] = $prefWidth;
543 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
545 # Create a thumbnail. Alignment depends on language
546 # writing direction, # right aligned for left-to-right-
547 # languages ("Western languages"), left-aligned
548 # for right-to-left-languages ("Semitic languages")
550 # If thumbnail width has not been provided, it is set
551 # to the default user option as specified in Language*.php
552 if ( $fp['align'] == '' ) {
553 $fp['align'] = $wgContLang->alignEnd();
555 return $prefix . self
::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
558 if ( $file && isset( $fp['frameless'] ) ) {
559 $srcWidth = $file->getWidth( $page );
560 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
561 # This is the same behaviour as the "thumb" option does it already.
562 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
563 $hp['width'] = $srcWidth;
567 if ( $file && isset( $hp['width'] ) ) {
568 # Create a resized image, without the additional thumbnail features
569 $thumb = $file->transform( $hp );
575 $s = self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
579 'title' => $fp['title'],
580 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
581 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
582 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
584 $s = $thumb->toHtml( $params );
586 if ( $fp['align'] != '' ) {
587 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
589 return str_replace( "\n", ' ', $prefix . $s . $postfix );
593 * Get the link parameters for MediaTransformOutput::toHtml() from given
594 * frame parameters supplied by the Parser.
595 * @param $frameParams The frame parameters
596 * @param $query An optional query string to add to description page links
598 static function getImageLinkMTOParams( $frameParams, $query = '' ) {
599 $mtoParams = array();
600 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
601 $mtoParams['custom-url-link'] = $frameParams['link-url'];
602 if ( isset( $frameParams['link-target'] ) ) {
603 $mtoParams['custom-target-link'] = $frameParams['link-target'];
605 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
606 $mtoParams['custom-title-link'] = self
::normaliseSpecialPage( $frameParams['link-title'] );
607 } elseif ( !empty( $frameParams['no-link'] ) ) {
610 $mtoParams['desc-link'] = true;
611 $mtoParams['desc-query'] = $query;
617 * Make HTML for a thumbnail including image, border and caption
618 * @param $title Title object
619 * @param $file File object or false if it doesn't exist
620 * @param $label String
622 * @param $align String
623 * @param $params Array
624 * @param $framed Boolean
625 * @param $manualthumb String
627 static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt,
628 $align = 'right', $params = array(), $framed = false , $manualthumb = "" )
630 $frameParams = array(
636 $frameParams['framed'] = true;
638 if ( $manualthumb ) {
639 $frameParams['manualthumb'] = $manualthumb;
641 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
645 * @param $title Title
647 * @param array $frameParams
648 * @param array $handlerParams
650 * @param string $query
653 static function makeThumbLink2( Title
$title, $file, $frameParams = array(),
654 $handlerParams = array(), $time = false, $query = "" )
656 global $wgStylePath, $wgContLang;
657 $exists = $file && $file->exists();
661 $hp =& $handlerParams;
663 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
664 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
665 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
666 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
667 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
669 if ( empty( $hp['width'] ) ) {
670 // Reduce width for upright images when parameter 'upright' is used
671 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
676 $outerWidth = $hp['width'] +
2;
678 if ( isset( $fp['manualthumb'] ) ) {
679 # Use manually specified thumbnail
680 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
681 if ( $manual_title ) {
682 $manual_img = wfFindFile( $manual_title );
684 $thumb = $manual_img->getUnscaledThumb( $hp );
689 } elseif ( isset( $fp['framed'] ) ) {
690 // Use image dimensions, don't scale
691 $thumb = $file->getUnscaledThumb( $hp );
693 # Do not present an image bigger than the source, for bitmap-style images
694 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
695 $srcWidth = $file->getWidth( $page );
696 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
697 $hp['width'] = $srcWidth;
699 $thumb = $file->transform( $hp );
703 $outerWidth = $thumb->getWidth() +
2;
705 $outerWidth = $hp['width'] +
2;
709 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
710 # So we don't need to pass it here in $query. However, the URL for the
711 # zoom icon still needs it, so we make a unique query for it. See bug 14771
712 $url = $title->getLocalURL( $query );
714 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
717 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
719 $s .= self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
721 } elseif ( !$thumb ) {
722 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
727 'title' => $fp['title'],
728 'img-class' => 'thumbimage' );
729 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
730 $s .= $thumb->toHtml( $params );
731 if ( isset( $fp['framed'] ) ) {
734 $zoomIcon = Html
::rawElement( 'div', array( 'class' => 'magnify' ),
735 Html
::rawElement( 'a', array(
737 'class' => 'internal',
738 'title' => wfMsg( 'thumbnail-more' ) ),
739 Html
::element( 'img', array(
740 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ?
'-rtl' : '' ) . '.png',
746 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
747 return str_replace( "\n", ' ', $s );
751 * Make a "broken" link to an image
753 * @param $title Title object
754 * @param $text String: link label in unescaped text form
755 * @param $query String: query string
756 * @param $trail String: link trail (HTML fragment)
757 * @param $prefix String: link prefix (HTML fragment)
758 * @param $time Boolean: a file of a certain timestamp was requested
761 public static function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
762 global $wgEnableUploads, $wgUploadMissingFileUrl;
763 if ( $title instanceof Title
) {
764 wfProfileIn( __METHOD__
);
765 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
767 list( $inside, $trail ) = self
::splitTrail( $trail );
769 $text = htmlspecialchars( $title->getPrefixedText() );
771 if ( ( $wgUploadMissingFileUrl ||
$wgEnableUploads ) && !$currentExists ) {
772 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
775 wfProfileOut( __METHOD__
);
776 return self
::linkKnown( $title, "$prefix$text$inside", array(), $query ) . $trail;
779 $href = self
::getUploadUrl( $title, $query );
781 wfProfileOut( __METHOD__
);
782 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
783 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
784 "$prefix$text$inside</a>$trail";
786 wfProfileOut( __METHOD__
);
787 return self
::linkKnown( $title, "$prefix$text$inside", array(), $query ) . $trail;
790 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
795 * Get the URL to upload a certain file
797 * @param $destFile Title object of the file to upload
798 * @param $query String: urlencoded query string to prepend
799 * @return String: urlencoded URL
801 protected static function getUploadUrl( $destFile, $query = '' ) {
802 global $wgUploadMissingFileUrl;
803 $q = 'wpDestFile=' . $destFile->getPartialUrl();
807 if ( $wgUploadMissingFileUrl ) {
808 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
810 $upload = SpecialPage
::getTitleFor( 'Upload' );
811 return $upload->getLocalUrl( $q );
816 * Create a direct link to a given uploaded file.
818 * @param $title Title object.
819 * @param $text String: pre-sanitized HTML
820 * @param $time string: MW timestamp of file creation time
821 * @return String: HTML
823 public static function makeMediaLinkObj( $title, $text = '', $time = false ) {
824 $img = wfFindFile( $title, array( 'time' => $time ) );
825 return self
::makeMediaLinkFile( $title, $img, $text );
829 * Create a direct link to a given uploaded file.
830 * This will make a broken link if $file is false.
832 * @param $title Title object.
833 * @param $file mixed File object or false
834 * @param $text String: pre-sanitized HTML
835 * @return String: HTML
837 * @todo Handle invalid or missing images better.
839 public static function makeMediaLinkFile( Title
$title, $file, $text = '' ) {
840 if ( $file && $file->exists() ) {
841 $url = $file->getURL();
844 $url = self
::getUploadUrl( $title );
847 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES
);
851 $u = htmlspecialchars( $url );
852 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
856 * Make a link to a special page given its name and, optionally,
857 * a message key from the link text.
858 * Usage example: $skin->specialLink( 'recentchanges' )
860 static function specialLink( $name, $key = '' ) {
861 if ( $key == '' ) { $key = strtolower( $name ); }
863 return self
::linkKnown( SpecialPage
::getTitleFor( $name ) , wfMsg( $key ) );
867 * Make an external link
868 * @param $url String: URL to link to
869 * @param $text String: text of link
870 * @param $escape Boolean: do we escape the link text?
871 * @param $linktype String: type of external link. Gets added to the classes
872 * @param $attribs Array of extra attributes to <a>
874 static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
876 if ( isset($linktype) && $linktype ) {
877 $class .= " $linktype";
879 if ( isset($attribs['class']) && $attribs['class'] ) {
880 $class .= " {$attribs['class']}";
882 $attribs['class'] = $class;
885 $text = htmlspecialchars( $text );
888 $success = wfRunHooks( 'LinkerMakeExternalLink',
889 array( &$url, &$text, &$link, &$attribs, $linktype ) );
891 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
894 $attribs['href'] = $url;
895 return Html
::rawElement( 'a', $attribs, $text );
899 * Make user link (or user contributions for unregistered users)
900 * @param $userId Integer: user id in database.
901 * @param $userText String: user name in database
902 * @return String: HTML fragment
905 static function userLink( $userId, $userText ) {
906 if ( $userId == 0 ) {
907 $page = SpecialPage
::getTitleFor( 'Contributions', $userText );
909 $page = Title
::makeTitle( NS_USER
, $userText );
911 return self
::link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
915 * Generate standard user tool links (talk, contributions, block link, etc.)
917 * @param $userId Integer: user identifier
918 * @param $userText String: user name or IP address
919 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
920 * red if the user has no edits?
921 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK)
922 * @param $edits Integer: user edit count (optional, for performance)
923 * @return String: HTML fragment
925 public static function userToolLinks(
926 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
928 global $wgUser, $wgDisableAnonTalk, $wgLang;
929 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
930 $blockable = !$flags & self
::TOOL_LINKS_NOBLOCK
;
934 $items[] = self
::userTalkLink( $userId, $userText );
937 // check if the user has an edit
939 if ( $redContribsWhenNoEdits ) {
940 $count = !is_null( $edits ) ?
$edits : User
::edits( $userId );
942 $attribs['class'] = 'new';
945 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
947 $items[] = self
::link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
949 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
950 $items[] = self
::blockLink( $userId, $userText );
954 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
961 * Alias for userToolLinks( $userId, $userText, true );
962 * @param $userId Integer: user identifier
963 * @param $userText String: user name or IP address
964 * @param $edits Integer: user edit count (optional, for performance)
966 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
967 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
972 * @param $userId Integer: user id in database.
973 * @param $userText String: user name in database.
974 * @return String: HTML fragment with user talk link
977 static function userTalkLink( $userId, $userText ) {
978 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
979 $userTalkLink = self
::link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
980 return $userTalkLink;
984 * @param $userId Integer: userid
985 * @param $userText String: user name in database.
986 * @return String: HTML fragment with block link
989 static function blockLink( $userId, $userText ) {
990 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
991 $blockLink = self
::link( $blockPage, wfMsgHtml( 'blocklink' ) );
996 * Generate a user link if the current user is allowed to view it
997 * @param $rev Revision object.
998 * @param $isPublic Boolean: show only if all users can see it
999 * @return String: HTML fragment
1001 static function revUserLink( $rev, $isPublic = false ) {
1002 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1003 $link = wfMsgHtml( 'rev-deleted-user' );
1004 } else if ( $rev->userCan( Revision
::DELETED_USER
) ) {
1005 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1006 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1008 $link = wfMsgHtml( 'rev-deleted-user' );
1010 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1011 return '<span class="history-deleted">' . $link . '</span>';
1017 * Generate a user tool link cluster if the current user is allowed to view it
1018 * @param $rev Revision object.
1019 * @param $isPublic Boolean: show only if all users can see it
1020 * @return string HTML
1022 static function revUserTools( $rev, $isPublic = false ) {
1023 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1024 $link = wfMsgHtml( 'rev-deleted-user' );
1025 } else if ( $rev->userCan( Revision
::DELETED_USER
) ) {
1026 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1027 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1028 $link = self
::userLink( $userId, $userText ) .
1029 ' ' . self
::userToolLinks( $userId, $userText );
1031 $link = wfMsgHtml( 'rev-deleted-user' );
1033 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1034 return ' <span class="history-deleted">' . $link . '</span>';
1040 * This function is called by all recent changes variants, by the page history,
1041 * and by the user contributions list. It is responsible for formatting edit
1042 * comments. It escapes any HTML in the comment, but adds some CSS to format
1043 * auto-generated comments (from section editing) and formats [[wikilinks]].
1045 * @author Erik Moeller <moeller@scireview.de>
1047 * Note: there's not always a title to pass to this function.
1048 * Since you can't set a default parameter for a reference, I've turned it
1049 * temporarily to a value pass. Should be adjusted further. --brion
1051 * @param $comment String
1052 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1053 * @param $local Boolean: whether section links should refer to local page
1055 static function formatComment( $comment, $title = null, $local = false ) {
1056 wfProfileIn( __METHOD__
);
1058 # Sanitize text a bit:
1059 $comment = str_replace( "\n", " ", $comment );
1060 # Allow HTML entities (for bug 13815)
1061 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1063 # Render autocomments and make links:
1064 $comment = self
::formatAutocomments( $comment, $title, $local );
1065 $comment = self
::formatLinksInComment( $comment, $title, $local );
1067 wfProfileOut( __METHOD__
);
1071 static $autocommentTitle;
1072 static $autocommentLocal;
1075 * The pattern for autogen comments is / * foo * /, which makes for
1077 * We look for all comments, match any text before and after the comment,
1078 * add a separator where needed and format the comment itself with CSS
1079 * Called by Linker::formatComment.
1081 * @param $comment String: comment text
1082 * @param $title An optional title object used to links to sections
1083 * @param $local Boolean: whether section links should refer to local page
1084 * @return String: formatted comment
1086 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1088 self
::$autocommentTitle = $title;
1089 self
::$autocommentLocal = $local;
1090 $comment = preg_replace_callback(
1091 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1092 array( 'Linker', 'formatAutocommentsCallback' ),
1094 self
::$autocommentTitle = null;
1095 self
::$autocommentLocal = null;
1099 private static function formatAutocommentsCallback( $match ) {
1100 $title = self
::$autocommentTitle;
1101 $local = self
::$autocommentLocal;
1110 # Remove links that a user may have manually put in the autosummary
1111 # This could be improved by copying as much of Parser::stripSectionName as desired.
1112 $section = str_replace( '[[:', '', $section );
1113 $section = str_replace( '[[', '', $section );
1114 $section = str_replace( ']]', '', $section );
1116 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1118 $sectionTitle = Title
::newFromText( '#' . $section );
1120 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1121 $title->getDBkey(), $section );
1123 if ( $sectionTitle ) {
1124 $link = self
::link( $sectionTitle,
1125 htmlspecialchars( wfMsgForContent( 'sectionlink' ) ), array(), array(),
1131 $auto = "$link$auto";
1133 # written summary $presep autocomment (summary /* section */)
1134 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1137 # autocomment $postsep written summary (/* section */ summary)
1138 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1140 $auto = '<span class="autocomment">' . $auto . '</span>';
1141 $comment = $pre . $auto . $post;
1145 static $commentContextTitle;
1146 static $commentLocal;
1149 * Formats wiki links and media links in text; all other wiki formatting
1152 * @todo Fixme: doesn't handle sub-links as in image thumb texts like the main parser
1153 * @param $comment String: text to format links in
1154 * @param $title An optional title object used to links to sections
1155 * @param $local Boolean: whether section links should refer to local page
1158 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1159 self
::$commentContextTitle = $title;
1160 self
::$commentLocal = $local;
1161 $html = preg_replace_callback(
1162 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1163 array( 'Linker', 'formatLinksInCommentCallback' ),
1165 self
::$commentContextTitle = null;
1166 self
::$commentLocal = null;
1170 protected static function formatLinksInCommentCallback( $match ) {
1173 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1174 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1176 $comment = $match[0];
1178 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1179 if ( strpos( $match[1], '%' ) !== false ) {
1180 $match[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $match[1] ) );
1183 # Handle link renaming [[foo|text]] will show link as "text"
1184 if ( $match[3] != "" ) {
1189 $submatch = array();
1191 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1192 # Media link; trail not supported.
1193 $linkRegexp = '/\[\[(.*?)\]\]/';
1194 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1195 $thelink = self
::makeMediaLinkObj( $title, $text );
1197 # Other kind of link
1198 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1199 $trail = $submatch[1];
1203 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1204 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1205 $match[1] = substr( $match[1], 1 );
1206 list( $inside, $trail ) = self
::splitTrail( $trail );
1209 $linkTarget = self
::normalizeSubpageLink( self
::$commentContextTitle,
1210 $match[1], $linkText );
1212 $target = Title
::newFromText( $linkTarget );
1214 if ( $target->getText() == '' && $target->getInterwiki() === ''
1215 && !self
::$commentLocal && self
::$commentContextTitle )
1217 $newTarget = clone ( self
::$commentContextTitle );
1218 $newTarget->setFragment( '#' . $target->getFragment() );
1219 $target = $newTarget;
1221 $thelink = self
::link(
1228 // If the link is still valid, go ahead and replace it in!
1229 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1236 * @param $contextTitle Title
1241 static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1244 # :Foobar -- override special treatment of prefix (images, language links)
1245 # /Foobar -- convert to CurrentPage/Foobar
1246 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1247 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1248 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1250 wfProfileIn( __METHOD__
);
1251 $ret = $target; # default return value is no change
1253 # Some namespaces don't allow subpages,
1254 # so only perform processing if subpages are allowed
1255 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1256 $hash = strpos( $target, '#' );
1257 if ( $hash !== false ) {
1258 $suffix = substr( $target, $hash );
1259 $target = substr( $target, 0, $hash );
1264 $target = trim( $target );
1265 # Look at the first character
1266 if ( $target != '' && $target { 0 } === '/' ) {
1267 # / at end means we don't want the slash to be shown
1269 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1270 if ( $trailingSlashes ) {
1271 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1273 $noslash = substr( $target, 1 );
1276 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1277 if ( $text === '' ) {
1278 $text = $target . $suffix;
1279 } # this might be changed for ugliness reasons
1281 # check for .. subpage backlinks
1283 $nodotdot = $target;
1284 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1286 $nodotdot = substr( $nodotdot, 3 );
1288 if ( $dotdotcount > 0 ) {
1289 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1290 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1291 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1292 # / at the end means don't show full path
1293 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1294 $nodotdot = substr( $nodotdot, 0, -1 );
1295 if ( $text === '' ) {
1296 $text = $nodotdot . $suffix;
1299 $nodotdot = trim( $nodotdot );
1300 if ( $nodotdot != '' ) {
1301 $ret .= '/' . $nodotdot;
1309 wfProfileOut( __METHOD__
);
1314 * Wrap a comment in standard punctuation and formatting if
1315 * it's non-empty, otherwise return empty string.
1317 * @param $comment String
1318 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1319 * @param $local Boolean: whether section links should refer to local page
1320 * @param $embraced Boolean: whether the formatted comment should be embraced with ()
1323 static function commentBlock( $comment, $title = null, $local = false, $embraced = true ) {
1324 // '*' used to be the comment inserted by the software way back
1325 // in antiquity in case none was provided, here for backwards
1326 // compatability, acc. to brion -ævar
1327 if ( $comment == '' ||
$comment == '*' ) {
1330 $formatted = self
::formatComment( $comment, $title, $local );
1332 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1334 return Html
::rawElement( 'span', array( 'class' => 'comment' ), $formatted );
1339 * Wrap and format the given revision's comment block, if the current
1340 * user is allowed to view it.
1342 * @param $rev Revision object
1343 * @param $local Boolean: whether section links should refer to local page
1344 * @param $isPublic Boolean: show only if all users can see it
1345 * @return String: HTML fragment
1347 static function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1348 if ( $rev->getRawComment() == "" ) {
1351 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1352 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1353 } else if ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1354 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1355 $rev->getTitle(), $local );
1357 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1359 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1360 return " <span class=\"history-deleted\">$block</span>";
1365 public static function formatRevisionSize( $size ) {
1367 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1370 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1373 $stxt = htmlspecialchars( $stxt );
1374 return "<span class=\"history-size\">$stxt</span>";
1378 * Add another level to the Table of Contents
1380 static function tocIndent() {
1385 * Finish one or more sublevels on the Table of Contents
1387 static function tocUnindent( $level ) {
1388 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1392 * parameter level defines if we are on an indentation level
1394 static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1395 $classes = "toclevel-$level";
1396 if ( $sectionIndex !== false )
1397 $classes .= " tocsection-$sectionIndex";
1398 return "\n<li class=\"$classes\"><a href=\"#" .
1399 $anchor . '"><span class="tocnumber">' .
1400 $tocnumber . '</span> <span class="toctext">' .
1401 $tocline . '</span></a>';
1405 * End a Table Of Contents line.
1406 * tocUnindent() will be used instead if we're ending a line below
1409 static function tocLineEnd() {
1414 * Wraps the TOC in a table and provides the hide/collapse javascript.
1416 * @param $toc String: html of the Table Of Contents
1417 * @param $lang mixed: Language code for the toc title
1418 * @return String: full html of the TOC
1420 static function tocList( $toc, $lang = false ) {
1421 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1423 '<table id="toc" class="toc"><tr><td>'
1424 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1426 . "</ul>\n</td></tr></table>\n";
1430 * Generate a table of contents from a section tree
1433 * @param $tree Return value of ParserOutput::getSections()
1434 * @return String: HTML fragment
1436 public static function generateTOC( $tree ) {
1439 foreach ( $tree as $section ) {
1440 if ( $section['toclevel'] > $lastLevel )
1441 $toc .= self
::tocIndent();
1442 else if ( $section['toclevel'] < $lastLevel )
1443 $toc .= self
::tocUnindent(
1444 $lastLevel - $section['toclevel'] );
1446 $toc .= self
::tocLineEnd();
1448 $toc .= self
::tocLine( $section['anchor'],
1449 $section['line'], $section['number'],
1450 $section['toclevel'], $section['index'] );
1451 $lastLevel = $section['toclevel'];
1453 $toc .= self
::tocLineEnd();
1454 return self
::tocList( $toc );
1458 * Create a headline for content
1460 * @param $level Integer: the level of the headline (1-6)
1461 * @param $attribs String: any attributes for the headline, starting with
1462 * a space and ending with '>'
1463 * This *must* be at least '>' for no attribs
1464 * @param $anchor String: the anchor to give the headline (the bit after the #)
1465 * @param $text String: the text of the header
1466 * @param $link String: HTML to add for the section edit link
1467 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1468 * backward compatibility (false to omit)
1470 * @return String: HTML headline
1472 public static function makeHeadline( $level, $attribs, $anchor, $text, $link, $legacyAnchor = false ) {
1473 $ret = "<h$level$attribs"
1475 . " <span class=\"mw-headline\" id=\"$anchor\">$text</span>"
1477 if ( $legacyAnchor !== false ) {
1478 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1484 * Split a link trail, return the "inside" portion and the remainder of the trail
1485 * as a two-element array
1487 static function splitTrail( $trail ) {
1489 $regex = $wgContLang->linkTrail();
1491 if ( $trail !== '' ) {
1493 if ( preg_match( $regex, $trail, $m ) ) {
1498 return array( $inside, $trail );
1502 * Generate a rollback link for a given revision. Currently it's the
1503 * caller's responsibility to ensure that the revision is the top one. If
1504 * it's not, of course, the user will get an error message.
1506 * If the calling page is called with the parameter &bot=1, all rollback
1507 * links also get that parameter. It causes the edit itself and the rollback
1508 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1509 * changes, so this allows sysops to combat a busy vandal without bothering
1512 * @param $rev Revision object
1514 static function generateRollback( $rev ) {
1515 return '<span class="mw-rollback-link">['
1516 . self
::buildRollbackLink( $rev )
1521 * Build a raw rollback link, useful for collections of "tool" links
1523 * @param $rev Revision object
1524 * @return String: HTML fragment
1526 public static function buildRollbackLink( $rev ) {
1527 global $wgRequest, $wgUser;
1528 $title = $rev->getTitle();
1530 'action' => 'rollback',
1531 'from' => $rev->getUserText(),
1532 'token' => $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1534 if ( $wgRequest->getBool( 'bot' ) ) {
1535 $query['bot'] = '1';
1536 $query['hidediff'] = '1'; // bug 15999
1540 wfMsgHtml( 'rollbacklink' ),
1541 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1543 array( 'known', 'noclasses' )
1548 * Returns HTML for the "templates used on this page" list.
1550 * @param $templates Array of templates from Article::getUsedTemplate
1552 * @param $preview Boolean: whether this is for a preview
1553 * @param $section Boolean: whether this is for a section edit
1554 * @return String: HTML output
1556 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1557 wfProfileIn( __METHOD__
);
1560 if ( count( $templates ) > 0 ) {
1561 # Do a batch existence check
1562 $batch = new LinkBatch
;
1563 foreach ( $templates as $title ) {
1564 $batch->addObj( $title );
1568 # Construct the HTML
1569 $outText = '<div class="mw-templatesUsedExplanation">';
1571 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1572 } elseif ( $section ) {
1573 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1575 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1577 $outText .= "</div><ul>\n";
1579 usort( $templates, array( 'Title', 'compare' ) );
1580 foreach ( $templates as $titleObj ) {
1581 $r = $titleObj->getRestrictions( 'edit' );
1582 if ( in_array( 'sysop', $r ) ) {
1583 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1584 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1585 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1589 if ( $titleObj->quickUserCan( 'edit' ) ) {
1590 $editLink = self
::link(
1592 wfMsg( 'editlink' ),
1594 array( 'action' => 'edit' )
1597 $editLink = self
::link(
1599 wfMsg( 'viewsourcelink' ),
1601 array( 'action' => 'edit' )
1604 $outText .= '<li>' . self
::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1606 $outText .= '</ul>';
1608 wfProfileOut( __METHOD__
);
1613 * Returns HTML for the "hidden categories on this page" list.
1615 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1617 * @return String: HTML output
1619 public static function formatHiddenCategories( $hiddencats ) {
1621 wfProfileIn( __METHOD__
);
1624 if ( count( $hiddencats ) > 0 ) {
1625 # Construct the HTML
1626 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1627 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1628 $outText .= "</div><ul>\n";
1630 foreach ( $hiddencats as $titleObj ) {
1631 $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
1633 $outText .= '</ul>';
1635 wfProfileOut( __METHOD__
);
1640 * Format a size in bytes for output, using an appropriate
1641 * unit (B, KB, MB or GB) according to the magnitude in question
1643 * @param $size Size to format
1646 public static function formatSize( $size ) {
1648 return htmlspecialchars( $wgLang->formatSize( $size ) );
1652 * Given the id of an interface element, constructs the appropriate title
1653 * attribute from the system messages. (Note, this is usually the id but
1654 * isn't always, because sometimes the accesskey needs to go on a different
1655 * element than the id, for reverse-compatibility, etc.)
1657 * @param $name String: id of the element, minus prefixes.
1658 * @param $options Mixed: null or the string 'withaccess' to add an access-
1660 * @return String: contents of the title attribute (which you must HTML-
1661 * escape), or false for no title attribute
1663 public static function titleAttrib( $name, $options = null ) {
1664 wfProfileIn( __METHOD__
);
1666 $message = wfMessage( "tooltip-$name" );
1668 if ( !$message->exists() ) {
1671 $tooltip = $message->text();
1672 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1673 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1674 # Message equal to '-' means suppress it.
1675 if ( $tooltip == '-' ) {
1680 if ( $options == 'withaccess' ) {
1681 $accesskey = self
::accesskey( $name );
1682 if ( $accesskey !== false ) {
1683 if ( $tooltip === false ||
$tooltip === '' ) {
1684 $tooltip = "[$accesskey]";
1686 $tooltip .= " [$accesskey]";
1691 wfProfileOut( __METHOD__
);
1695 static $accesskeycache;
1698 * Given the id of an interface element, constructs the appropriate
1699 * accesskey attribute from the system messages. (Note, this is usually
1700 * the id but isn't always, because sometimes the accesskey needs to go on
1701 * a different element than the id, for reverse-compatibility, etc.)
1703 * @param $name String: id of the element, minus prefixes.
1704 * @return String: contents of the accesskey attribute (which you must HTML-
1705 * escape), or false for no accesskey attribute
1707 public static function accesskey( $name ) {
1708 if ( isset( self
::$accesskeycache[$name] ) ) {
1709 return self
::$accesskeycache[$name];
1711 wfProfileIn( __METHOD__
);
1713 $message = wfMessage( "accesskey-$name" );
1715 if ( !$message->exists() ) {
1718 $accesskey = $message->plain();
1719 if ( $accesskey === '' ||
$accesskey === '-' ) {
1720 # FIXME: Per standard MW behavior, a value of '-' means to suppress the
1721 # attribute, but this is broken for accesskey: that might be a useful
1727 wfProfileOut( __METHOD__
);
1728 return self
::$accesskeycache[$name] = $accesskey;
1732 * Creates a (show/hide) link for deleting revisions/log entries
1734 * @param $query Array: query parameters to be passed to link()
1735 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1736 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1738 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1739 * span to allow for customization of appearance with CSS
1741 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1742 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1743 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1744 $tag = $restricted ?
'strong' : 'span';
1745 $link = self
::link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1746 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1750 * Creates a dead (show/hide) link for deleting revisions/log entries
1752 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1754 * @return string HTML text wrapped in a span to allow for customization
1755 * of appearance with CSS
1757 public static function revDeleteLinkDisabled( $delete = true ) {
1758 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1759 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($text)" );
1762 /* Deprecated methods */
1765 * @deprecated since 1.16 Use link()
1767 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1768 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1770 * @param $title String: The text of the title
1771 * @param $text String: Link text
1772 * @param $query String: Optional query part
1773 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1774 * be included in the link text. Other characters will be appended after
1775 * the end of the link.
1777 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1778 $nt = Title
::newFromText( $title );
1779 if ( $nt instanceof Title
) {
1780 return self
::makeBrokenLinkObj( $nt, $text, $query, $trail );
1782 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
1783 return $text == '' ?
$title : $text;
1788 * @deprecated since 1.16 Use link()
1790 * Make a link for a title which may or may not be in the database. If you need to
1791 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1792 * call to this will result in a DB query.
1794 * @param $nt Title: the title object to make the link from, e.g. from
1795 * Title::newFromText.
1796 * @param $text String: link text
1797 * @param $query String: optional query part
1798 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1799 * be included in the link text. Other characters will be appended after
1800 * the end of the link.
1801 * @param $prefix String: optional prefix. As trail, only before instead of after.
1803 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1804 wfProfileIn( __METHOD__
);
1805 $query = wfCgiToArray( $query );
1806 list( $inside, $trail ) = self
::splitTrail( $trail );
1807 if ( $text === '' ) {
1808 $text = self
::linkText( $nt );
1811 $ret = self
::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1813 wfProfileOut( __METHOD__
);
1818 * @deprecated since 1.16 Use link()
1820 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1821 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1824 * @param $title Title object of target page
1825 * @param $text String: text to replace the title
1826 * @param $query String: link target
1827 * @param $trail String: text after link
1828 * @param $prefix String: text before link text
1829 * @param $aprops String: extra attributes to the a-element
1830 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1831 * @return the a-element
1833 static function makeKnownLinkObj(
1834 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
1836 wfProfileIn( __METHOD__
);
1838 if ( $text == '' ) {
1839 $text = self
::linkText( $title );
1841 $attribs = Sanitizer
::mergeAttributes(
1842 Sanitizer
::decodeTagAttributes( $aprops ),
1843 Sanitizer
::decodeTagAttributes( $style )
1845 $query = wfCgiToArray( $query );
1846 list( $inside, $trail ) = self
::splitTrail( $trail );
1848 $ret = self
::link( $title, "$prefix$text$inside", $attribs, $query,
1849 array( 'known', 'noclasses' ) ) . $trail;
1851 wfProfileOut( __METHOD__
);
1856 * @deprecated since 1.16 Use link()
1858 * Make a red link to the edit page of a given title.
1860 * @param $title Title object of the target page
1861 * @param $text String: Link text
1862 * @param $query String: Optional query part
1863 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1864 * be included in the link text. Other characters will be appended after
1865 * the end of the link.
1866 * @param $prefix String: Optional prefix
1868 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
1869 wfProfileIn( __METHOD__
);
1871 list( $inside, $trail ) = self
::splitTrail( $trail );
1872 if ( $text === '' ) {
1873 $text = self
::linkText( $title );
1876 $ret = self
::link( $title, "$prefix$text$inside", array(),
1877 wfCgiToArray( $query ), 'broken' ) . $trail;
1879 wfProfileOut( __METHOD__
);
1884 * @deprecated since 1.16 Use link()
1886 * Make a coloured link.
1888 * @param $nt Title object of the target page
1889 * @param $colour Integer: colour of the link
1890 * @param $text String: link text
1891 * @param $query String: optional query part
1892 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1893 * be included in the link text. Other characters will be appended after
1894 * the end of the link.
1895 * @param $prefix String: Optional prefix
1897 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
1898 if ( $colour != '' ) {
1899 $style = self
::getInternalLinkAttributesObj( $nt, $text, $colour );
1903 return self
::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
1907 * Returns the attributes for the tooltip and access key.
1909 public static function tooltipAndAccesskeyAttribs( $name ) {
1910 global $wgEnableTooltipsAndAccesskeys;
1911 if ( !$wgEnableTooltipsAndAccesskeys )
1913 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
1914 # no attribute" instead of "output '' as value for attribute", this
1915 # would be three lines.
1917 'title' => self
::titleAttrib( $name, 'withaccess' ),
1918 'accesskey' => self
::accesskey( $name )
1920 if ( $attribs['title'] === false ) {
1921 unset( $attribs['title'] );
1923 if ( $attribs['accesskey'] === false ) {
1924 unset( $attribs['accesskey'] );
1930 * @deprecated since 1.14
1931 * Returns raw bits of HTML, use titleAttrib()
1933 public static function tooltip( $name, $options = null ) {
1934 global $wgEnableTooltipsAndAccesskeys;
1935 if ( !$wgEnableTooltipsAndAccesskeys )
1937 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
1938 # no attribute" instead of "output '' as value for attribute", this
1939 # would be two lines.
1940 $tooltip = self
::titleAttrib( $name, $options );
1941 if ( $tooltip === false ) {
1944 return Xml
::expandAttributes( array(
1953 * Use PHP's magic __call handler to transform instance calls to a dummy instance
1954 * into static calls to the new Linker for backwards compatibility.
1956 * @param $fname String Name of called method
1957 * @param $args Array Arguments to the method
1959 function __call( $fname, $args ) {
1960 return call_user_func_array( array( 'Linker', $fname ), $args );