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 # @todo 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 * @param $title string
87 * @param $class string
91 private static function getLinkAttributesInternal( $title, $class ) {
92 $title = htmlspecialchars( $title );
93 $class = htmlspecialchars( $class );
96 $r .= " class=\"$class\"";
99 $r .= " title=\"$title\"";
105 * Return the CSS colour of a known link
107 * @param $t Title object
108 * @param $threshold Integer: user defined threshold
109 * @return String: CSS class
111 static function getLinkColour( $t, $threshold ) {
113 if ( $t->isRedirect() ) {
115 $colour = 'mw-redirect';
116 } elseif ( $threshold > 0 &&
117 $t->exists() && $t->getLength() < $threshold &&
118 $t->isContentPage() ) {
126 * This function returns an HTML link to the given target. It serves a few
128 * 1) If $target is a Title, the correct URL to link to will be figured
130 * 2) It automatically adds the usual classes for various types of link
131 * targets: "new" for red links, "stub" for short articles, etc.
132 * 3) It escapes all attribute values safely so there's no risk of XSS.
133 * 4) It provides a default tooltip if the target is a Title (the page
134 * name of the target).
135 * link() replaces the old functions in the makeLink() family.
137 * @param $target Title Can currently only be a Title, but this may
138 * change to support Images, literal URLs, etc.
139 * @param $text string The HTML contents of the <a> element, i.e.,
140 * the link text. This is raw HTML and will not be escaped. If null,
141 * defaults to the prefixed text of the Title; or if the Title is just a
142 * fragment, the contents of the fragment.
143 * @param $customAttribs array A key => value array of extra HTML attri-
144 * butes, such as title and class. (href is ignored.) Classes will be
145 * merged with the default classes, while other attributes will replace
146 * default attributes. All passed attribute values will be HTML-escaped.
147 * A false attribute value means to suppress that attribute.
148 * @param $query array The query string to append to the URL
149 * you're linking to, in key => value array form. Query keys and values
150 * will be URL-encoded.
151 * @param $options string|array String or array of strings:
152 * 'known': Page is known to exist, so don't check if it does.
153 * 'broken': Page is known not to exist, so don't check if it does.
154 * 'noclasses': Don't add any classes automatically (includes "new",
155 * "stub", "mw-redirect", "extiw"). Only use the class attribute
156 * provided, if any, so you get a simple blue link with no funny i-
158 * 'forcearticlepath': Use the article path always, even with a querystring.
159 * Has compatibility issues on some setups, so avoid wherever possible.
160 * @return string HTML <a> attribute
162 public static function link(
163 $target, $html = null, $customAttribs = array(), $query = array(), $options = array()
165 wfProfileIn( __METHOD__
);
166 if ( !$target instanceof Title
) {
167 wfProfileOut( __METHOD__
);
168 return "<!-- ERROR -->$html";
170 $options = (array)$options;
172 $dummy = new DummyLinker
; // dummy linker instance for bc on the hooks
175 if ( !wfRunHooks( 'LinkBegin', array( $dummy, $target, &$html,
176 &$customAttribs, &$query, &$options, &$ret ) ) ) {
177 wfProfileOut( __METHOD__
);
181 # Normalize the Title if it's a special page
182 $target = self
::normaliseSpecialPage( $target );
184 # If we don't know whether the page exists, let's find out.
185 wfProfileIn( __METHOD__
. '-checkPageExistence' );
186 if ( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
187 if ( $target->isKnown() ) {
188 $options[] = 'known';
190 $options[] = 'broken';
193 wfProfileOut( __METHOD__
. '-checkPageExistence' );
196 if ( in_array( "forcearticlepath", $options ) && $query ) {
201 # Note: we want the href attribute first, for prettiness.
202 $attribs = array( 'href' => self
::linkUrl( $target, $query, $options ) );
203 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
204 $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
207 $attribs = array_merge(
209 self
::linkAttribs( $target, $customAttribs, $options )
211 if ( is_null( $html ) ) {
212 $html = self
::linkText( $target );
216 if ( wfRunHooks( 'LinkEnd', array( $dummy, $target, $options, &$html, &$attribs, &$ret ) ) ) {
217 $ret = Html
::rawElement( 'a', $attribs, $html );
220 wfProfileOut( __METHOD__
);
225 * Identical to link(), except $options defaults to 'known'.
227 public static function linkKnown(
228 $target, $text = null, $customAttribs = array(),
229 $query = array(), $options = array( 'known', 'noclasses' ) )
231 return self
::link( $target, $text, $customAttribs, $query, $options );
235 * Returns the Url used to link to a Title
237 * @param $target Title
239 private static function linkUrl( $target, $query, $options ) {
240 wfProfileIn( __METHOD__
);
241 # We don't want to include fragments for broken links, because they
242 # generally make no sense.
243 if ( in_array( 'broken', $options ) && $target->mFragment
!== '' ) {
244 $target = clone $target;
245 $target->mFragment
= '';
248 # If it's a broken link, add the appropriate query pieces, unless
249 # there's already an action specified, or unless 'edit' makes no sense
250 # (i.e., for a nonexistent special page).
251 if ( in_array( 'broken', $options ) && empty( $query['action'] )
252 && $target->getNamespace() != NS_SPECIAL
) {
253 $query['action'] = 'edit';
254 $query['redlink'] = '1';
256 $ret = $target->getLinkUrl( $query );
257 wfProfileOut( __METHOD__
);
262 * Returns the array of attributes used when linking to the Title $target
264 * @param $target Title
266 private static function linkAttribs( $target, $attribs, $options ) {
267 wfProfileIn( __METHOD__
);
271 if ( !in_array( 'noclasses', $options ) ) {
272 wfProfileIn( __METHOD__
. '-getClasses' );
273 # Now build the classes.
276 if ( in_array( 'broken', $options ) ) {
280 if ( $target->isExternal() ) {
281 $classes[] = 'extiw';
284 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
285 $colour = self
::getLinkColour( $target, $wgUser->getStubThreshold() );
286 if ( $colour !== '' ) {
287 $classes[] = $colour; # mw-redirect or stub
290 if ( $classes != array() ) {
291 $defaults['class'] = implode( ' ', $classes );
293 wfProfileOut( __METHOD__
. '-getClasses' );
296 # Get a default title attribute.
297 if ( $target->getPrefixedText() == '' ) {
298 # A link like [[#Foo]]. This used to mean an empty title
299 # attribute, but that's silly. Just don't output a title.
300 } elseif ( in_array( 'known', $options ) ) {
301 $defaults['title'] = $target->getPrefixedText();
303 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
306 # Finally, merge the custom attribs with the default ones, and iterate
307 # over that, deleting all "false" attributes.
309 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
310 foreach ( $merged as $key => $val ) {
311 # A false value suppresses the attribute, and we don't want the
312 # href attribute to be overridden.
313 if ( $key != 'href' and $val !== false ) {
317 wfProfileOut( __METHOD__
);
322 * Default text of the links to the Title $target
324 * @param $target Title
328 private static function linkText( $target ) {
329 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
330 if ( !$target instanceof Title
) {
334 # If the target is just a fragment, with no title, we return the frag-
335 # ment text. Otherwise, we return the title text itself.
336 if ( $target->getPrefixedText() === '' && $target->getFragment() !== '' ) {
337 return htmlspecialchars( $target->getFragment() );
339 return htmlspecialchars( $target->getPrefixedText() );
343 * Generate either a normal exists-style link or a stub link, depending
344 * on the given page size.
346 * @param $size Integer
347 * @param $nt Title object.
348 * @param $text String
349 * @param $query String
350 * @param $trail String
351 * @param $prefix String
352 * @return string HTML of link
353 * @deprecated since 1.17
355 static function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
357 wfDeprecated( __METHOD__
);
359 $threshold = $wgUser->getStubThreshold();
360 $colour = ( $size < $threshold ) ?
'stub' : '';
361 // @todo FIXME: Replace deprecated makeColouredLinkObj by link()
362 return self
::makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
366 * Make appropriate markup for a link to the current article. This is currently rendered
367 * as the bold link text. The calling sequence is the same as the other make*LinkObj static functions,
368 * despite $query not being used.
374 static function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
376 $text = htmlspecialchars( $nt->getPrefixedText() );
378 list( $inside, $trail ) = self
::splitTrail( $trail );
379 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
383 * @param $title Title
386 static function normaliseSpecialPage( Title
$title ) {
387 if ( $title->getNamespace() == NS_SPECIAL
) {
388 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
392 $ret = SpecialPage
::getTitleFor( $name, $subpage );
393 $ret->mFragment
= $title->getFragment();
401 * Returns the filename part of an url.
402 * Used as alternative text for external images.
408 static function fnamePart( $url ) {
409 $basename = strrchr( $url, '/' );
410 if ( false === $basename ) {
413 $basename = substr( $basename, 1 );
419 * Return the code for images which were added via external links,
420 * via Parser::maybeMakeExternalImage().
427 static function makeExternalImage( $url, $alt = '' ) {
429 $alt = self
::fnamePart( $url );
432 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
434 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
437 return Html
::element( 'img',
444 * Given parameters derived from [[Image:Foo|options...]], generate the
445 * HTML that that syntax inserts in the page.
447 * @param $title Title object
448 * @param $file File object, or false if it doesn't exist
449 * @param $frameParams Array: associative array of parameters external to the media handler.
450 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
451 * will often be false.
452 * thumbnail If present, downscale and frame
453 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
454 * framed Shows image in original size in a frame
455 * frameless Downscale but don't frame
456 * upright If present, tweak default sizes for portrait orientation
457 * upright_factor Fudge factor for "upright" tweak (default 0.75)
458 * border If present, show a border around the image
459 * align Horizontal alignment (left, right, center, none)
460 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
461 * bottom, text-bottom)
462 * alt Alternate text for image (i.e. alt attribute). Plain text.
463 * caption HTML for image caption.
464 * link-url URL to link to
465 * link-title Title object to link to
466 * link-target Value for the target attribue, only with link-url
467 * no-link Boolean, suppress description link
469 * @param $handlerParams Array: associative array of media handler parameters, to be passed
470 * to transform(). Typical keys are "width" and "page".
471 * @param $time String: timestamp of the file, set as false for current
472 * @param $query String: query params for desc url
473 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
474 * @return String: HTML for an image, with links, wrappers, etc.
476 static function makeImageLink2( Title
$title, $file, $frameParams = array(),
477 $handlerParams = array(), $time = false, $query = "", $widthOption = null )
480 $dummy = new DummyLinker
;
481 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
482 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
486 if ( $file && !$file->allowInlineDisplay() ) {
487 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
488 return self
::link( $title );
493 $hp =& $handlerParams;
495 // Clean up parameters
496 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
497 if ( !isset( $fp['align'] ) ) {
500 if ( !isset( $fp['alt'] ) ) {
503 if ( !isset( $fp['title'] ) ) {
507 $prefix = $postfix = '';
509 if ( 'center' == $fp['align'] ) {
510 $prefix = '<div class="center">';
512 $fp['align'] = 'none';
514 if ( $file && !isset( $hp['width'] ) ) {
515 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
516 // If its a vector image, and user only specifies height
517 // we don't want it to be limited by its "normal" width.
518 global $wgSVGMaxSize;
519 $hp['width'] = $wgSVGMaxSize;
521 $hp['width'] = $file->getWidth( $page );
524 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
525 global $wgThumbLimits, $wgThumbUpright;
526 if ( !isset( $widthOption ) ||
!isset( $wgThumbLimits[$widthOption] ) ) {
527 $widthOption = User
::getDefaultOption( 'thumbsize' );
530 // Reduce width for upright images when parameter 'upright' is used
531 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
532 $fp['upright'] = $wgThumbUpright;
534 // 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
535 $prefWidth = isset( $fp['upright'] ) ?
536 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
537 $wgThumbLimits[$widthOption];
539 // Use width which is smaller: real image width or user preference width
540 // Unless image is scalable vector.
541 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
542 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
543 $hp['width'] = $prefWidth;
548 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
550 # Create a thumbnail. Alignment depends on language
551 # writing direction, # right aligned for left-to-right-
552 # languages ("Western languages"), left-aligned
553 # for right-to-left-languages ("Semitic languages")
555 # If thumbnail width has not been provided, it is set
556 # to the default user option as specified in Language*.php
557 if ( $fp['align'] == '' ) {
558 $fp['align'] = $wgContLang->alignEnd();
560 return $prefix . self
::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
563 if ( $file && isset( $fp['frameless'] ) ) {
564 $srcWidth = $file->getWidth( $page );
565 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
566 # This is the same behaviour as the "thumb" option does it already.
567 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
568 $hp['width'] = $srcWidth;
572 if ( $file && isset( $hp['width'] ) ) {
573 # Create a resized image, without the additional thumbnail features
574 $thumb = $file->transform( $hp );
580 $s = self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
584 'title' => $fp['title'],
585 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
586 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
587 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
589 $s = $thumb->toHtml( $params );
591 if ( $fp['align'] != '' ) {
592 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
594 return str_replace( "\n", ' ', $prefix . $s . $postfix );
598 * Get the link parameters for MediaTransformOutput::toHtml() from given
599 * frame parameters supplied by the Parser.
600 * @param $frameParams The frame parameters
601 * @param $query An optional query string to add to description page links
603 static function getImageLinkMTOParams( $frameParams, $query = '' ) {
604 $mtoParams = array();
605 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
606 $mtoParams['custom-url-link'] = $frameParams['link-url'];
607 if ( isset( $frameParams['link-target'] ) ) {
608 $mtoParams['custom-target-link'] = $frameParams['link-target'];
610 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
611 $mtoParams['custom-title-link'] = self
::normaliseSpecialPage( $frameParams['link-title'] );
612 } elseif ( !empty( $frameParams['no-link'] ) ) {
615 $mtoParams['desc-link'] = true;
616 $mtoParams['desc-query'] = $query;
622 * Make HTML for a thumbnail including image, border and caption
623 * @param $title Title object
624 * @param $file File object or false if it doesn't exist
625 * @param $label String
627 * @param $align String
628 * @param $params Array
629 * @param $framed Boolean
630 * @param $manualthumb String
632 static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt,
633 $align = 'right', $params = array(), $framed = false , $manualthumb = "" )
635 $frameParams = array(
641 $frameParams['framed'] = true;
643 if ( $manualthumb ) {
644 $frameParams['manualthumb'] = $manualthumb;
646 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
650 * @param $title Title
652 * @param array $frameParams
653 * @param array $handlerParams
655 * @param string $query
658 static function makeThumbLink2( Title
$title, $file, $frameParams = array(),
659 $handlerParams = array(), $time = false, $query = "" )
661 global $wgStylePath, $wgContLang;
662 $exists = $file && $file->exists();
666 $hp =& $handlerParams;
668 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
669 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
670 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
671 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
672 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
674 if ( empty( $hp['width'] ) ) {
675 // Reduce width for upright images when parameter 'upright' is used
676 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
681 $outerWidth = $hp['width'] +
2;
683 if ( isset( $fp['manualthumb'] ) ) {
684 # Use manually specified thumbnail
685 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
686 if ( $manual_title ) {
687 $manual_img = wfFindFile( $manual_title );
689 $thumb = $manual_img->getUnscaledThumb( $hp );
694 } elseif ( isset( $fp['framed'] ) ) {
695 // Use image dimensions, don't scale
696 $thumb = $file->getUnscaledThumb( $hp );
698 # Do not present an image bigger than the source, for bitmap-style images
699 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
700 $srcWidth = $file->getWidth( $page );
701 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
702 $hp['width'] = $srcWidth;
704 $thumb = $file->transform( $hp );
708 $outerWidth = $thumb->getWidth() +
2;
710 $outerWidth = $hp['width'] +
2;
714 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
715 # So we don't need to pass it here in $query. However, the URL for the
716 # zoom icon still needs it, so we make a unique query for it. See bug 14771
717 $url = $title->getLocalURL( $query );
719 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
722 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
724 $s .= self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
726 } elseif ( !$thumb ) {
727 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
732 'title' => $fp['title'],
733 'img-class' => 'thumbimage' );
734 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
735 $s .= $thumb->toHtml( $params );
736 if ( isset( $fp['framed'] ) ) {
739 $zoomIcon = Html
::rawElement( 'div', array( 'class' => 'magnify' ),
740 Html
::rawElement( 'a', array(
742 'class' => 'internal',
743 'title' => wfMsg( 'thumbnail-more' ) ),
744 Html
::element( 'img', array(
745 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ?
'-rtl' : '' ) . '.png',
751 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
752 return str_replace( "\n", ' ', $s );
756 * Make a "broken" link to an image
758 * @param $title Title object
759 * @param $text String: link label in unescaped text form
760 * @param $query String: query string
761 * @param $trail String: link trail (HTML fragment)
762 * @param $prefix String: link prefix (HTML fragment)
763 * @param $time Boolean: a file of a certain timestamp was requested
766 public static function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
767 global $wgEnableUploads, $wgUploadMissingFileUrl;
768 if ( ! $title instanceof Title
) {
769 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
771 wfProfileIn( __METHOD__
);
772 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
774 list( $inside, $trail ) = self
::splitTrail( $trail );
776 $text = htmlspecialchars( $title->getPrefixedText() );
778 if ( ( $wgUploadMissingFileUrl ||
$wgEnableUploads ) && !$currentExists ) {
779 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
782 wfProfileOut( __METHOD__
);
783 return self
::linkKnown( $title, "$prefix$text$inside", array(), $query ) . $trail;
786 $href = self
::getUploadUrl( $title, $query );
788 wfProfileOut( __METHOD__
);
789 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
790 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
791 "$prefix$text$inside</a>$trail";
793 wfProfileOut( __METHOD__
);
794 return self
::linkKnown( $title, "$prefix$text$inside", array(), $query ) . $trail;
799 * Get the URL to upload a certain file
801 * @param $destFile Title object of the file to upload
802 * @param $query String: urlencoded query string to prepend
803 * @return String: urlencoded URL
805 protected static function getUploadUrl( $destFile, $query = '' ) {
806 global $wgUploadMissingFileUrl;
807 $q = 'wpDestFile=' . $destFile->getPartialUrl();
811 if ( $wgUploadMissingFileUrl ) {
812 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
814 $upload = SpecialPage
::getTitleFor( 'Upload' );
815 return $upload->getLocalUrl( $q );
820 * Create a direct link to a given uploaded file.
822 * @param $title Title object.
823 * @param $text String: pre-sanitized HTML
824 * @param $time string: MW timestamp of file creation time
825 * @return String: HTML
827 public static function makeMediaLinkObj( $title, $text = '', $time = false ) {
828 $img = wfFindFile( $title, array( 'time' => $time ) );
829 return self
::makeMediaLinkFile( $title, $img, $text );
833 * Create a direct link to a given uploaded file.
834 * This will make a broken link if $file is false.
836 * @param $title Title object.
837 * @param $file mixed File object or false
838 * @param $text String: pre-sanitized HTML
839 * @return String: HTML
841 * @todo Handle invalid or missing images better.
843 public static function makeMediaLinkFile( Title
$title, $file, $text = '' ) {
844 if ( $file && $file->exists() ) {
845 $url = $file->getURL();
848 $url = self
::getUploadUrl( $title );
851 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES
);
855 $u = htmlspecialchars( $url );
856 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
860 * Make a link to a special page given its name and, optionally,
861 * a message key from the link text.
862 * Usage example: $skin->specialLink( 'recentchanges' )
864 static function specialLink( $name, $key = '' ) {
865 if ( $key == '' ) { $key = strtolower( $name ); }
867 return self
::linkKnown( SpecialPage
::getTitleFor( $name ) , wfMsg( $key ) );
871 * Make an external link
872 * @param $url String: URL to link to
873 * @param $text String: text of link
874 * @param $escape Boolean: do we escape the link text?
875 * @param $linktype String: type of external link. Gets added to the classes
876 * @param $attribs Array of extra attributes to <a>
878 static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
880 if ( isset($linktype) && $linktype ) {
881 $class .= " $linktype";
883 if ( isset($attribs['class']) && $attribs['class'] ) {
884 $class .= " {$attribs['class']}";
886 $attribs['class'] = $class;
889 $text = htmlspecialchars( $text );
892 $success = wfRunHooks( 'LinkerMakeExternalLink',
893 array( &$url, &$text, &$link, &$attribs, $linktype ) );
895 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
898 $attribs['href'] = $url;
899 return Html
::rawElement( 'a', $attribs, $text );
903 * Make user link (or user contributions for unregistered users)
904 * @param $userId Integer: user id in database.
905 * @param $userText String: user name in database
906 * @return String: HTML fragment
909 static function userLink( $userId, $userText ) {
910 if ( $userId == 0 ) {
911 $page = SpecialPage
::getTitleFor( 'Contributions', $userText );
913 $page = Title
::makeTitle( NS_USER
, $userText );
915 return self
::link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
919 * Generate standard user tool links (talk, contributions, block link, etc.)
921 * @param $userId Integer: user identifier
922 * @param $userText String: user name or IP address
923 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
924 * red if the user has no edits?
925 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK)
926 * @param $edits Integer: user edit count (optional, for performance)
927 * @return String: HTML fragment
929 public static function userToolLinks(
930 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
932 global $wgUser, $wgDisableAnonTalk, $wgLang;
933 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
934 $blockable = !$flags & self
::TOOL_LINKS_NOBLOCK
;
938 $items[] = self
::userTalkLink( $userId, $userText );
941 // check if the user has an edit
943 if ( $redContribsWhenNoEdits ) {
944 $count = !is_null( $edits ) ?
$edits : User
::edits( $userId );
946 $attribs['class'] = 'new';
949 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
951 $items[] = self
::link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
953 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
954 $items[] = self
::blockLink( $userId, $userText );
958 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
965 * Alias for userToolLinks( $userId, $userText, true );
966 * @param $userId Integer: user identifier
967 * @param $userText String: user name or IP address
968 * @param $edits Integer: user edit count (optional, for performance)
970 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
971 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
976 * @param $userId Integer: user id in database.
977 * @param $userText String: user name in database.
978 * @return String: HTML fragment with user talk link
981 static function userTalkLink( $userId, $userText ) {
982 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
983 $userTalkLink = self
::link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
984 return $userTalkLink;
988 * @param $userId Integer: userid
989 * @param $userText String: user name in database.
990 * @return String: HTML fragment with block link
993 static function blockLink( $userId, $userText ) {
994 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
995 $blockLink = self
::link( $blockPage, wfMsgHtml( 'blocklink' ) );
1000 * Generate a user link if the current user is allowed to view it
1001 * @param $rev Revision object.
1002 * @param $isPublic Boolean: show only if all users can see it
1003 * @return String: HTML fragment
1005 static function revUserLink( $rev, $isPublic = false ) {
1006 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1007 $link = wfMsgHtml( 'rev-deleted-user' );
1008 } else if ( $rev->userCan( Revision
::DELETED_USER
) ) {
1009 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1010 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1012 $link = wfMsgHtml( 'rev-deleted-user' );
1014 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1015 return '<span class="history-deleted">' . $link . '</span>';
1021 * Generate a user tool link cluster if the current user is allowed to view it
1022 * @param $rev Revision object.
1023 * @param $isPublic Boolean: show only if all users can see it
1024 * @return string HTML
1026 static function revUserTools( $rev, $isPublic = false ) {
1027 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1028 $link = wfMsgHtml( 'rev-deleted-user' );
1029 } else if ( $rev->userCan( Revision
::DELETED_USER
) ) {
1030 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1031 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1032 $link = self
::userLink( $userId, $userText ) .
1033 ' ' . self
::userToolLinks( $userId, $userText );
1035 $link = wfMsgHtml( 'rev-deleted-user' );
1037 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1038 return ' <span class="history-deleted">' . $link . '</span>';
1044 * This function is called by all recent changes variants, by the page history,
1045 * and by the user contributions list. It is responsible for formatting edit
1046 * comments. It escapes any HTML in the comment, but adds some CSS to format
1047 * auto-generated comments (from section editing) and formats [[wikilinks]].
1049 * @author Erik Moeller <moeller@scireview.de>
1051 * Note: there's not always a title to pass to this function.
1052 * Since you can't set a default parameter for a reference, I've turned it
1053 * temporarily to a value pass. Should be adjusted further. --brion
1055 * @param $comment String
1056 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1057 * @param $local Boolean: whether section links should refer to local page
1059 static function formatComment( $comment, $title = null, $local = false ) {
1060 wfProfileIn( __METHOD__
);
1062 # Sanitize text a bit:
1063 $comment = str_replace( "\n", " ", $comment );
1064 # Allow HTML entities (for bug 13815)
1065 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1067 # Render autocomments and make links:
1068 $comment = self
::formatAutocomments( $comment, $title, $local );
1069 $comment = self
::formatLinksInComment( $comment, $title, $local );
1071 wfProfileOut( __METHOD__
);
1078 static $autocommentTitle;
1079 static $autocommentLocal;
1082 * The pattern for autogen comments is / * foo * /, which makes for
1084 * We look for all comments, match any text before and after the comment,
1085 * add a separator where needed and format the comment itself with CSS
1086 * Called by Linker::formatComment.
1088 * @param $comment String: comment text
1089 * @param $title An optional title object used to links to sections
1090 * @param $local Boolean: whether section links should refer to local page
1091 * @return String: formatted comment
1093 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1095 self
::$autocommentTitle = $title;
1096 self
::$autocommentLocal = $local;
1097 $comment = preg_replace_callback(
1098 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1099 array( 'Linker', 'formatAutocommentsCallback' ),
1101 self
::$autocommentTitle = null;
1102 self
::$autocommentLocal = null;
1106 private static function formatAutocommentsCallback( $match ) {
1107 $title = self
::$autocommentTitle;
1108 $local = self
::$autocommentLocal;
1117 # Remove links that a user may have manually put in the autosummary
1118 # This could be improved by copying as much of Parser::stripSectionName as desired.
1119 $section = str_replace( '[[:', '', $section );
1120 $section = str_replace( '[[', '', $section );
1121 $section = str_replace( ']]', '', $section );
1123 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1125 $sectionTitle = Title
::newFromText( '#' . $section );
1127 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1128 $title->getDBkey(), $section );
1130 if ( $sectionTitle ) {
1131 $link = self
::link( $sectionTitle,
1132 htmlspecialchars( wfMsgForContent( 'sectionlink' ) ), array(), array(),
1138 $auto = "$link$auto";
1140 # written summary $presep autocomment (summary /* section */)
1141 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1144 # autocomment $postsep written summary (/* section */ summary)
1145 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1147 $auto = '<span class="autocomment">' . $auto . '</span>';
1148 $comment = $pre . $auto . $post;
1152 static $commentContextTitle;
1153 static $commentLocal;
1156 * Formats wiki links and media links in text; all other wiki formatting
1159 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1160 * @param $comment String: text to format links in
1161 * @param $title An optional title object used to links to sections
1162 * @param $local Boolean: whether section links should refer to local page
1165 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1166 self
::$commentContextTitle = $title;
1167 self
::$commentLocal = $local;
1168 $html = preg_replace_callback(
1169 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1170 array( 'Linker', 'formatLinksInCommentCallback' ),
1172 self
::$commentContextTitle = null;
1173 self
::$commentLocal = null;
1177 protected static function formatLinksInCommentCallback( $match ) {
1180 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1181 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1183 $comment = $match[0];
1185 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1186 if ( strpos( $match[1], '%' ) !== false ) {
1187 $match[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $match[1] ) );
1190 # Handle link renaming [[foo|text]] will show link as "text"
1191 if ( $match[3] != "" ) {
1196 $submatch = array();
1198 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1199 # Media link; trail not supported.
1200 $linkRegexp = '/\[\[(.*?)\]\]/';
1201 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1202 $thelink = self
::makeMediaLinkObj( $title, $text );
1204 # Other kind of link
1205 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1206 $trail = $submatch[1];
1210 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1211 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1212 $match[1] = substr( $match[1], 1 );
1213 list( $inside, $trail ) = self
::splitTrail( $trail );
1216 $linkTarget = self
::normalizeSubpageLink( self
::$commentContextTitle,
1217 $match[1], $linkText );
1219 $target = Title
::newFromText( $linkTarget );
1221 if ( $target->getText() == '' && $target->getInterwiki() === ''
1222 && !self
::$commentLocal && self
::$commentContextTitle )
1224 $newTarget = clone ( self
::$commentContextTitle );
1225 $newTarget->setFragment( '#' . $target->getFragment() );
1226 $target = $newTarget;
1228 $thelink = self
::link(
1235 // If the link is still valid, go ahead and replace it in!
1236 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1243 * @param $contextTitle Title
1248 static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1251 # :Foobar -- override special treatment of prefix (images, language links)
1252 # /Foobar -- convert to CurrentPage/Foobar
1253 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1254 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1255 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1257 wfProfileIn( __METHOD__
);
1258 $ret = $target; # default return value is no change
1260 # Some namespaces don't allow subpages,
1261 # so only perform processing if subpages are allowed
1262 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1263 $hash = strpos( $target, '#' );
1264 if ( $hash !== false ) {
1265 $suffix = substr( $target, $hash );
1266 $target = substr( $target, 0, $hash );
1271 $target = trim( $target );
1272 # Look at the first character
1273 if ( $target != '' && $target { 0 } === '/' ) {
1274 # / at end means we don't want the slash to be shown
1276 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1277 if ( $trailingSlashes ) {
1278 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1280 $noslash = substr( $target, 1 );
1283 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1284 if ( $text === '' ) {
1285 $text = $target . $suffix;
1286 } # this might be changed for ugliness reasons
1288 # check for .. subpage backlinks
1290 $nodotdot = $target;
1291 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1293 $nodotdot = substr( $nodotdot, 3 );
1295 if ( $dotdotcount > 0 ) {
1296 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1297 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1298 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1299 # / at the end means don't show full path
1300 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1301 $nodotdot = substr( $nodotdot, 0, -1 );
1302 if ( $text === '' ) {
1303 $text = $nodotdot . $suffix;
1306 $nodotdot = trim( $nodotdot );
1307 if ( $nodotdot != '' ) {
1308 $ret .= '/' . $nodotdot;
1316 wfProfileOut( __METHOD__
);
1321 * Wrap a comment in standard punctuation and formatting if
1322 * it's non-empty, otherwise return empty string.
1324 * @param $comment String
1325 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1326 * @param $local Boolean: whether section links should refer to local page
1327 * @param $embraced Boolean: whether the formatted comment should be embraced with ()
1330 static function commentBlock( $comment, $title = null, $local = false, $embraced = true ) {
1331 // '*' used to be the comment inserted by the software way back
1332 // in antiquity in case none was provided, here for backwards
1333 // compatability, acc. to brion -ævar
1334 if ( $comment == '' ||
$comment == '*' ) {
1337 $formatted = self
::formatComment( $comment, $title, $local );
1339 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1341 return Html
::rawElement( 'span', array( 'class' => 'comment' ), $formatted );
1346 * Wrap and format the given revision's comment block, if the current
1347 * user is allowed to view it.
1349 * @param $rev Revision object
1350 * @param $local Boolean: whether section links should refer to local page
1351 * @param $isPublic Boolean: show only if all users can see it
1352 * @return String: HTML fragment
1354 static function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1355 if ( $rev->getRawComment() == "" ) {
1358 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1359 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1360 } else if ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1361 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1362 $rev->getTitle(), $local );
1364 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1366 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1367 return " <span class=\"history-deleted\">$block</span>";
1372 public static function formatRevisionSize( $size ) {
1374 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1377 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1380 $stxt = htmlspecialchars( $stxt );
1381 return "<span class=\"history-size\">$stxt</span>";
1385 * Add another level to the Table of Contents
1387 static function tocIndent() {
1392 * Finish one or more sublevels on the Table of Contents
1394 static function tocUnindent( $level ) {
1395 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1399 * parameter level defines if we are on an indentation level
1401 static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1402 $classes = "toclevel-$level";
1403 if ( $sectionIndex !== false )
1404 $classes .= " tocsection-$sectionIndex";
1405 return "\n<li class=\"$classes\"><a href=\"#" .
1406 $anchor . '"><span class="tocnumber">' .
1407 $tocnumber . '</span> <span class="toctext">' .
1408 $tocline . '</span></a>';
1412 * End a Table Of Contents line.
1413 * tocUnindent() will be used instead if we're ending a line below
1416 static function tocLineEnd() {
1421 * Wraps the TOC in a table and provides the hide/collapse javascript.
1423 * @param $toc String: html of the Table Of Contents
1424 * @param $lang mixed: Language code for the toc title
1425 * @return String: full html of the TOC
1427 static function tocList( $toc, $lang = false ) {
1428 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1430 '<table id="toc" class="toc"><tr><td>'
1431 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1433 . "</ul>\n</td></tr></table>\n";
1437 * Generate a table of contents from a section tree
1440 * @param $tree Return value of ParserOutput::getSections()
1441 * @return String: HTML fragment
1443 public static function generateTOC( $tree ) {
1446 foreach ( $tree as $section ) {
1447 if ( $section['toclevel'] > $lastLevel )
1448 $toc .= self
::tocIndent();
1449 else if ( $section['toclevel'] < $lastLevel )
1450 $toc .= self
::tocUnindent(
1451 $lastLevel - $section['toclevel'] );
1453 $toc .= self
::tocLineEnd();
1455 $toc .= self
::tocLine( $section['anchor'],
1456 $section['line'], $section['number'],
1457 $section['toclevel'], $section['index'] );
1458 $lastLevel = $section['toclevel'];
1460 $toc .= self
::tocLineEnd();
1461 return self
::tocList( $toc );
1465 * Create a headline for content
1467 * @param $level Integer: the level of the headline (1-6)
1468 * @param $attribs String: any attributes for the headline, starting with
1469 * a space and ending with '>'
1470 * This *must* be at least '>' for no attribs
1471 * @param $anchor String: the anchor to give the headline (the bit after the #)
1472 * @param $text String: the text of the header
1473 * @param $link String: HTML to add for the section edit link
1474 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1475 * backward compatibility (false to omit)
1477 * @return String: HTML headline
1479 public static function makeHeadline( $level, $attribs, $anchor, $text, $link, $legacyAnchor = false ) {
1480 $ret = "<h$level$attribs"
1482 . " <span class=\"mw-headline\" id=\"$anchor\">$text</span>"
1484 if ( $legacyAnchor !== false ) {
1485 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1491 * Split a link trail, return the "inside" portion and the remainder of the trail
1492 * as a two-element array
1494 static function splitTrail( $trail ) {
1496 $regex = $wgContLang->linkTrail();
1498 if ( $trail !== '' ) {
1500 if ( preg_match( $regex, $trail, $m ) ) {
1505 return array( $inside, $trail );
1509 * Generate a rollback link for a given revision. Currently it's the
1510 * caller's responsibility to ensure that the revision is the top one. If
1511 * it's not, of course, the user will get an error message.
1513 * If the calling page is called with the parameter &bot=1, all rollback
1514 * links also get that parameter. It causes the edit itself and the rollback
1515 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1516 * changes, so this allows sysops to combat a busy vandal without bothering
1519 * @param $rev Revision object
1521 static function generateRollback( $rev ) {
1522 return '<span class="mw-rollback-link">['
1523 . self
::buildRollbackLink( $rev )
1528 * Build a raw rollback link, useful for collections of "tool" links
1530 * @param $rev Revision object
1531 * @return String: HTML fragment
1533 public static function buildRollbackLink( $rev ) {
1534 global $wgRequest, $wgUser;
1535 $title = $rev->getTitle();
1537 'action' => 'rollback',
1538 'from' => $rev->getUserText(),
1539 'token' => $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1541 if ( $wgRequest->getBool( 'bot' ) ) {
1542 $query['bot'] = '1';
1543 $query['hidediff'] = '1'; // bug 15999
1547 wfMsgHtml( 'rollbacklink' ),
1548 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1550 array( 'known', 'noclasses' )
1555 * Returns HTML for the "templates used on this page" list.
1557 * @param $templates Array of templates from Article::getUsedTemplate
1559 * @param $preview Boolean: whether this is for a preview
1560 * @param $section Boolean: whether this is for a section edit
1561 * @return String: HTML output
1563 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1564 wfProfileIn( __METHOD__
);
1567 if ( count( $templates ) > 0 ) {
1568 # Do a batch existence check
1569 $batch = new LinkBatch
;
1570 foreach ( $templates as $title ) {
1571 $batch->addObj( $title );
1575 # Construct the HTML
1576 $outText = '<div class="mw-templatesUsedExplanation">';
1578 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1579 } elseif ( $section ) {
1580 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1582 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1584 $outText .= "</div><ul>\n";
1586 usort( $templates, array( 'Title', 'compare' ) );
1587 foreach ( $templates as $titleObj ) {
1588 $r = $titleObj->getRestrictions( 'edit' );
1589 if ( in_array( 'sysop', $r ) ) {
1590 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1591 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1592 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1596 if ( $titleObj->quickUserCan( 'edit' ) ) {
1597 $editLink = self
::link(
1599 wfMsg( 'editlink' ),
1601 array( 'action' => 'edit' )
1604 $editLink = self
::link(
1606 wfMsg( 'viewsourcelink' ),
1608 array( 'action' => 'edit' )
1611 $outText .= '<li>' . self
::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1613 $outText .= '</ul>';
1615 wfProfileOut( __METHOD__
);
1620 * Returns HTML for the "hidden categories on this page" list.
1622 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1624 * @return String: HTML output
1626 public static function formatHiddenCategories( $hiddencats ) {
1628 wfProfileIn( __METHOD__
);
1631 if ( count( $hiddencats ) > 0 ) {
1632 # Construct the HTML
1633 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1634 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1635 $outText .= "</div><ul>\n";
1637 foreach ( $hiddencats as $titleObj ) {
1638 $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
1640 $outText .= '</ul>';
1642 wfProfileOut( __METHOD__
);
1647 * Format a size in bytes for output, using an appropriate
1648 * unit (B, KB, MB or GB) according to the magnitude in question
1650 * @param $size Size to format
1653 public static function formatSize( $size ) {
1655 return htmlspecialchars( $wgLang->formatSize( $size ) );
1659 * Given the id of an interface element, constructs the appropriate title
1660 * attribute from the system messages. (Note, this is usually the id but
1661 * isn't always, because sometimes the accesskey needs to go on a different
1662 * element than the id, for reverse-compatibility, etc.)
1664 * @param $name String: id of the element, minus prefixes.
1665 * @param $options Mixed: null or the string 'withaccess' to add an access-
1667 * @return String: contents of the title attribute (which you must HTML-
1668 * escape), or false for no title attribute
1670 public static function titleAttrib( $name, $options = null ) {
1671 wfProfileIn( __METHOD__
);
1673 $message = wfMessage( "tooltip-$name" );
1675 if ( !$message->exists() ) {
1678 $tooltip = $message->text();
1679 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1680 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1681 # Message equal to '-' means suppress it.
1682 if ( $tooltip == '-' ) {
1687 if ( $options == 'withaccess' ) {
1688 $accesskey = self
::accesskey( $name );
1689 if ( $accesskey !== false ) {
1690 if ( $tooltip === false ||
$tooltip === '' ) {
1691 $tooltip = "[$accesskey]";
1693 $tooltip .= " [$accesskey]";
1698 wfProfileOut( __METHOD__
);
1702 static $accesskeycache;
1705 * Given the id of an interface element, constructs the appropriate
1706 * accesskey attribute from the system messages. (Note, this is usually
1707 * the id but isn't always, because sometimes the accesskey needs to go on
1708 * a different element than the id, for reverse-compatibility, etc.)
1710 * @param $name String: id of the element, minus prefixes.
1711 * @return String: contents of the accesskey attribute (which you must HTML-
1712 * escape), or false for no accesskey attribute
1714 public static function accesskey( $name ) {
1715 if ( isset( self
::$accesskeycache[$name] ) ) {
1716 return self
::$accesskeycache[$name];
1718 wfProfileIn( __METHOD__
);
1720 $message = wfMessage( "accesskey-$name" );
1722 if ( !$message->exists() ) {
1725 $accesskey = $message->plain();
1726 if ( $accesskey === '' ||
$accesskey === '-' ) {
1727 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
1728 # attribute, but this is broken for accesskey: that might be a useful
1734 wfProfileOut( __METHOD__
);
1735 return self
::$accesskeycache[$name] = $accesskey;
1739 * Creates a (show/hide) link for deleting revisions/log entries
1741 * @param $query Array: query parameters to be passed to link()
1742 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1743 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1745 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1746 * span to allow for customization of appearance with CSS
1748 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1749 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1750 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1751 $tag = $restricted ?
'strong' : 'span';
1752 $link = self
::link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1753 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1757 * Creates a dead (show/hide) link for deleting revisions/log entries
1759 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1761 * @return string HTML text wrapped in a span to allow for customization
1762 * of appearance with CSS
1764 public static function revDeleteLinkDisabled( $delete = true ) {
1765 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1766 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($text)" );
1769 /* Deprecated methods */
1772 * @deprecated since 1.16 Use link()
1774 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1775 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1777 * @param $title String: The text of the title
1778 * @param $text String: Link text
1779 * @param $query String: Optional query part
1780 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1781 * be included in the link text. Other characters will be appended after
1782 * the end of the link.
1784 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1785 $nt = Title
::newFromText( $title );
1786 if ( $nt instanceof Title
) {
1787 return self
::makeBrokenLinkObj( $nt, $text, $query, $trail );
1789 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
1790 return $text == '' ?
$title : $text;
1795 * @deprecated since 1.16 Use link()
1797 * Make a link for a title which may or may not be in the database. If you need to
1798 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1799 * call to this will result in a DB query.
1801 * @param $nt Title: the title object to make the link from, e.g. from
1802 * Title::newFromText.
1803 * @param $text String: link text
1804 * @param $query String: optional query part
1805 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1806 * be included in the link text. Other characters will be appended after
1807 * the end of the link.
1808 * @param $prefix String: optional prefix. As trail, only before instead of after.
1810 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1811 wfProfileIn( __METHOD__
);
1812 $query = wfCgiToArray( $query );
1813 list( $inside, $trail ) = self
::splitTrail( $trail );
1814 if ( $text === '' ) {
1815 $text = self
::linkText( $nt );
1818 $ret = self
::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1820 wfProfileOut( __METHOD__
);
1825 * @deprecated since 1.16 Use link()
1827 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1828 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1831 * @param $title Title object of target page
1832 * @param $text String: text to replace the title
1833 * @param $query String: link target
1834 * @param $trail String: text after link
1835 * @param $prefix String: text before link text
1836 * @param $aprops String: extra attributes to the a-element
1837 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1838 * @return the a-element
1840 static function makeKnownLinkObj(
1841 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
1843 wfProfileIn( __METHOD__
);
1845 if ( $text == '' ) {
1846 $text = self
::linkText( $title );
1848 $attribs = Sanitizer
::mergeAttributes(
1849 Sanitizer
::decodeTagAttributes( $aprops ),
1850 Sanitizer
::decodeTagAttributes( $style )
1852 $query = wfCgiToArray( $query );
1853 list( $inside, $trail ) = self
::splitTrail( $trail );
1855 $ret = self
::link( $title, "$prefix$text$inside", $attribs, $query,
1856 array( 'known', 'noclasses' ) ) . $trail;
1858 wfProfileOut( __METHOD__
);
1863 * @deprecated since 1.16 Use link()
1865 * Make a red link to the edit page of a given title.
1867 * @param $title Title object of the target page
1868 * @param $text String: Link text
1869 * @param $query String: Optional query part
1870 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1871 * be included in the link text. Other characters will be appended after
1872 * the end of the link.
1873 * @param $prefix String: Optional prefix
1875 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
1876 wfProfileIn( __METHOD__
);
1878 list( $inside, $trail ) = self
::splitTrail( $trail );
1879 if ( $text === '' ) {
1880 $text = self
::linkText( $title );
1883 $ret = self
::link( $title, "$prefix$text$inside", array(),
1884 wfCgiToArray( $query ), 'broken' ) . $trail;
1886 wfProfileOut( __METHOD__
);
1891 * @deprecated since 1.16 Use link()
1893 * Make a coloured link.
1895 * @param $nt Title object of the target page
1896 * @param $colour Integer: colour of the link
1897 * @param $text String: link text
1898 * @param $query String: optional query part
1899 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1900 * be included in the link text. Other characters will be appended after
1901 * the end of the link.
1902 * @param $prefix String: Optional prefix
1904 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
1905 if ( $colour != '' ) {
1906 $style = self
::getInternalLinkAttributesObj( $nt, $text, $colour );
1910 return self
::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
1914 * Returns the attributes for the tooltip and access key.
1916 public static function tooltipAndAccesskeyAttribs( $name ) {
1917 global $wgEnableTooltipsAndAccesskeys;
1918 if ( !$wgEnableTooltipsAndAccesskeys )
1920 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
1921 # no attribute" instead of "output '' as value for attribute", this
1922 # would be three lines.
1924 'title' => self
::titleAttrib( $name, 'withaccess' ),
1925 'accesskey' => self
::accesskey( $name )
1927 if ( $attribs['title'] === false ) {
1928 unset( $attribs['title'] );
1930 if ( $attribs['accesskey'] === false ) {
1931 unset( $attribs['accesskey'] );
1937 * @deprecated since 1.14
1938 * Returns raw bits of HTML, use titleAttrib()
1940 public static function tooltip( $name, $options = null ) {
1941 global $wgEnableTooltipsAndAccesskeys;
1942 if ( !$wgEnableTooltipsAndAccesskeys )
1944 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
1945 # no attribute" instead of "output '' as value for attribute", this
1946 # would be two lines.
1947 $tooltip = self
::titleAttrib( $name, $options );
1948 if ( $tooltip === false ) {
1951 return Xml
::expandAttributes( array(
1960 * Use PHP's magic __call handler to transform instance calls to a dummy instance
1961 * into static calls to the new Linker for backwards compatibility.
1963 * @param $fname String Name of called method
1964 * @param $args Array Arguments to the method
1966 function __call( $fname, $args ) {
1967 return call_user_func_array( array( 'Linker', $fname ), $args );