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 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, $text = null, $customAttribs = array(), $query = array(), $options = array()
160 wfProfileIn( __METHOD__
);
161 if ( !$target instanceof Title
) {
162 wfProfileOut( __METHOD__
);
163 return "<!-- ERROR -->$text";
165 $options = (array)$options;
167 $dummy = new DummyLinker
; // dummy linker instance for bc on the hooks
170 if ( !wfRunHooks( 'LinkBegin', array( $dummy, $target, &$text,
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( $text ) ) {
207 $text = self
::linkText( $target );
211 if ( wfRunHooks( 'LinkEnd', array( $dummy, $target, $options, &$text, &$attribs, &$ret ) ) ) {
212 $ret = Html
::rawElement( 'a', $attribs, $text );
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
321 private static function linkText( $target ) {
322 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
323 if ( !$target instanceof Title
) {
327 # If the target is just a fragment, with no title, we return the frag-
328 # ment text. Otherwise, we return the title text itself.
329 if ( $target->getPrefixedText() === '' && $target->getFragment() !== '' ) {
330 return htmlspecialchars( $target->getFragment() );
332 return htmlspecialchars( $target->getPrefixedText() );
336 * Generate either a normal exists-style link or a stub link, depending
337 * on the given page size.
339 * @param $size Integer
340 * @param $nt Title object.
341 * @param $text String
342 * @param $query String
343 * @param $trail String
344 * @param $prefix String
345 * @return string HTML of link
346 * @deprecated since 1.17
348 static function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
350 wfDeprecated( __METHOD__
);
352 $threshold = $wgUser->getStubThreshold();
353 $colour = ( $size < $threshold ) ?
'stub' : '';
354 // FIXME: replace deprecated makeColouredLinkObj by link()
355 return self
::makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
359 * Make appropriate markup for a link to the current article. This is currently rendered
360 * as the bold link text. The calling sequence is the same as the other make*LinkObj static functions,
361 * despite $query not being used.
365 static function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
367 $text = htmlspecialchars( $nt->getPrefixedText() );
369 list( $inside, $trail ) = self
::splitTrail( $trail );
370 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
373 static function normaliseSpecialPage( Title
$title ) {
374 if ( $title->getNamespace() == NS_SPECIAL
) {
375 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
379 $ret = SpecialPage
::getTitleFor( $name, $subpage );
380 $ret->mFragment
= $title->getFragment();
388 * Returns the filename part of an url.
389 * Used as alternative text for external images.
391 static function fnamePart( $url ) {
392 $basename = strrchr( $url, '/' );
393 if ( false === $basename ) {
396 $basename = substr( $basename, 1 );
402 * Return the code for images which were added via external links,
403 * via Parser::maybeMakeExternalImage().
405 static function makeExternalImage( $url, $alt = '' ) {
407 $alt = self
::fnamePart( $url );
410 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
412 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
415 return Html
::element( 'img',
422 * Given parameters derived from [[Image:Foo|options...]], generate the
423 * HTML that that syntax inserts in the page.
425 * @param $title Title object
426 * @param $file File object, or false if it doesn't exist
427 * @param $frameParams Array: associative array of parameters external to the media handler.
428 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
429 * will often be false.
430 * thumbnail If present, downscale and frame
431 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
432 * framed Shows image in original size in a frame
433 * frameless Downscale but don't frame
434 * upright If present, tweak default sizes for portrait orientation
435 * upright_factor Fudge factor for "upright" tweak (default 0.75)
436 * border If present, show a border around the image
437 * align Horizontal alignment (left, right, center, none)
438 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
439 * bottom, text-bottom)
440 * alt Alternate text for image (i.e. alt attribute). Plain text.
441 * caption HTML for image caption.
442 * link-url URL to link to
443 * link-title Title object to link to
444 * link-target Value for the target attribue, only with link-url
445 * no-link Boolean, suppress description link
447 * @param $handlerParams Array: associative array of media handler parameters, to be passed
448 * to transform(). Typical keys are "width" and "page".
449 * @param $time String: timestamp of the file, set as false for current
450 * @param $query String: query params for desc url
451 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
452 * @return String: HTML for an image, with links, wrappers, etc.
454 static function makeImageLink2( Title
$title, $file, $frameParams = array(),
455 $handlerParams = array(), $time = false, $query = "", $widthOption = null )
458 $dummy = new DummyLinker
;
459 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
460 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
464 if ( $file && !$file->allowInlineDisplay() ) {
465 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
466 return self
::link( $title );
471 $hp =& $handlerParams;
473 // Clean up parameters
474 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
475 if ( !isset( $fp['align'] ) ) {
478 if ( !isset( $fp['alt'] ) ) {
481 if ( !isset( $fp['title'] ) ) {
485 $prefix = $postfix = '';
487 if ( 'center' == $fp['align'] ) {
488 $prefix = '<div class="center">';
490 $fp['align'] = 'none';
492 if ( $file && !isset( $hp['width'] ) ) {
493 $hp['width'] = $file->getWidth( $page );
495 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
496 global $wgThumbLimits, $wgThumbUpright;
497 if ( !isset( $widthOption ) ||
!isset( $wgThumbLimits[$widthOption] ) ) {
498 $widthOption = User
::getDefaultOption( 'thumbsize' );
501 // Reduce width for upright images when parameter 'upright' is used
502 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
503 $fp['upright'] = $wgThumbUpright;
505 // 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
506 $prefWidth = isset( $fp['upright'] ) ?
507 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
508 $wgThumbLimits[$widthOption];
510 // Use width which is smaller: real image width or user preference width
511 // Unless image is scalable vector.
512 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
513 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
514 $hp['width'] = $prefWidth;
519 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
521 # Create a thumbnail. Alignment depends on language
522 # writing direction, # right aligned for left-to-right-
523 # languages ("Western languages"), left-aligned
524 # for right-to-left-languages ("Semitic languages")
526 # If thumbnail width has not been provided, it is set
527 # to the default user option as specified in Language*.php
528 if ( $fp['align'] == '' ) {
529 $fp['align'] = $wgContLang->alignEnd();
531 return $prefix . self
::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
534 if ( $file && isset( $fp['frameless'] ) ) {
535 $srcWidth = $file->getWidth( $page );
536 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
537 # This is the same behaviour as the "thumb" option does it already.
538 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
539 $hp['width'] = $srcWidth;
543 if ( $file && isset( $hp['width'] ) ) {
544 # Create a resized image, without the additional thumbnail features
545 $thumb = $file->transform( $hp );
551 $s = self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
555 'title' => $fp['title'],
556 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
557 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
558 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
560 $s = $thumb->toHtml( $params );
562 if ( $fp['align'] != '' ) {
563 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
565 return str_replace( "\n", ' ', $prefix . $s . $postfix );
569 * Get the link parameters for MediaTransformOutput::toHtml() from given
570 * frame parameters supplied by the Parser.
571 * @param $frameParams The frame parameters
572 * @param $query An optional query string to add to description page links
574 static function getImageLinkMTOParams( $frameParams, $query = '' ) {
575 $mtoParams = array();
576 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
577 $mtoParams['custom-url-link'] = $frameParams['link-url'];
578 if ( isset( $frameParams['link-target'] ) ) {
579 $mtoParams['custom-target-link'] = $frameParams['link-target'];
581 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
582 $mtoParams['custom-title-link'] = self
::normaliseSpecialPage( $frameParams['link-title'] );
583 } elseif ( !empty( $frameParams['no-link'] ) ) {
586 $mtoParams['desc-link'] = true;
587 $mtoParams['desc-query'] = $query;
593 * Make HTML for a thumbnail including image, border and caption
594 * @param $title Title object
595 * @param $file File object or false if it doesn't exist
596 * @param $label String
598 * @param $align String
599 * @param $params Array
600 * @param $framed Boolean
601 * @param $manualthumb String
603 static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt,
604 $align = 'right', $params = array(), $framed = false , $manualthumb = "" )
606 $frameParams = array(
612 $frameParams['framed'] = true;
614 if ( $manualthumb ) {
615 $frameParams['manualthumb'] = $manualthumb;
617 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
621 * @param $title Title
623 * @param array $frameParams
624 * @param array $handlerParams
626 * @param string $query
629 static function makeThumbLink2( Title
$title, $file, $frameParams = array(),
630 $handlerParams = array(), $time = false, $query = "" )
632 global $wgStylePath, $wgContLang;
633 $exists = $file && $file->exists();
637 $hp =& $handlerParams;
639 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
640 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
641 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
642 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
643 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
645 if ( empty( $hp['width'] ) ) {
646 // Reduce width for upright images when parameter 'upright' is used
647 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
652 $outerWidth = $hp['width'] +
2;
654 if ( isset( $fp['manualthumb'] ) ) {
655 # Use manually specified thumbnail
656 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
657 if ( $manual_title ) {
658 $manual_img = wfFindFile( $manual_title );
660 $thumb = $manual_img->getUnscaledThumb( $hp );
665 } elseif ( isset( $fp['framed'] ) ) {
666 // Use image dimensions, don't scale
667 $thumb = $file->getUnscaledThumb( $hp );
669 # Do not present an image bigger than the source, for bitmap-style images
670 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
671 $srcWidth = $file->getWidth( $page );
672 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
673 $hp['width'] = $srcWidth;
675 $thumb = $file->transform( $hp );
679 $outerWidth = $thumb->getWidth() +
2;
681 $outerWidth = $hp['width'] +
2;
685 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
686 # So we don't need to pass it here in $query. However, the URL for the
687 # zoom icon still needs it, so we make a unique query for it. See bug 14771
688 $url = $title->getLocalURL( $query );
690 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
693 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
695 $s .= self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
697 } elseif ( !$thumb ) {
698 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
703 'title' => $fp['title'],
704 'img-class' => 'thumbimage' );
705 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
706 $s .= $thumb->toHtml( $params );
707 if ( isset( $fp['framed'] ) ) {
710 $zoomIcon = Html
::rawElement( 'div', array( 'class' => 'magnify' ),
711 Html
::rawElement( 'a', array(
713 'class' => 'internal',
714 'title' => wfMsg( 'thumbnail-more' ) ),
715 Html
::element( 'img', array(
716 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ?
'-rtl' : '' ) . '.png',
722 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
723 return str_replace( "\n", ' ', $s );
727 * Make a "broken" link to an image
729 * @param $title Title object
730 * @param $text String: link label in unescaped text form
731 * @param $query String: query string
732 * @param $trail String: link trail (HTML fragment)
733 * @param $prefix String: link prefix (HTML fragment)
734 * @param $time Boolean: a file of a certain timestamp was requested
737 public static function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
738 global $wgEnableUploads, $wgUploadMissingFileUrl;
739 if ( $title instanceof Title
) {
740 wfProfileIn( __METHOD__
);
741 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
743 list( $inside, $trail ) = self
::splitTrail( $trail );
745 $text = htmlspecialchars( $title->getPrefixedText() );
747 if ( ( $wgUploadMissingFileUrl ||
$wgEnableUploads ) && !$currentExists ) {
748 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
751 wfProfileOut( __METHOD__
);
752 return self
::linkKnown( $title, "$prefix$text$inside", array(), $query ) . $trail;
755 $href = self
::getUploadUrl( $title, $query );
757 wfProfileOut( __METHOD__
);
758 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
759 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
760 "$prefix$text$inside</a>$trail";
762 wfProfileOut( __METHOD__
);
763 return self
::linkKnown( $title, "$prefix$text$inside", array(), $query ) . $trail;
766 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
771 * Get the URL to upload a certain file
773 * @param $destFile Title object of the file to upload
774 * @param $query String: urlencoded query string to prepend
775 * @return String: urlencoded URL
777 protected static function getUploadUrl( $destFile, $query = '' ) {
778 global $wgUploadMissingFileUrl;
779 $q = 'wpDestFile=' . $destFile->getPartialUrl();
783 if ( $wgUploadMissingFileUrl ) {
784 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
786 $upload = SpecialPage
::getTitleFor( 'Upload' );
787 return $upload->getLocalUrl( $q );
792 * Create a direct link to a given uploaded file.
794 * @param $title Title object.
795 * @param $text String: pre-sanitized HTML
796 * @param $time string: MW timestamp of file creation time
797 * @return String: HTML
799 public static function makeMediaLinkObj( $title, $text = '', $time = false ) {
800 $img = wfFindFile( $title, array( 'time' => $time ) );
801 return self
::makeMediaLinkFile( $title, $img, $text );
805 * Create a direct link to a given uploaded file.
806 * This will make a broken link if $file is false.
808 * @param $title Title object.
809 * @param $file mixed File object or false
810 * @param $text String: pre-sanitized HTML
811 * @return String: HTML
813 * @todo Handle invalid or missing images better.
815 public static function makeMediaLinkFile( Title
$title, $file, $text = '' ) {
816 if ( $file && $file->exists() ) {
817 $url = $file->getURL();
820 $url = self
::getUploadUrl( $title );
823 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES
);
827 $u = htmlspecialchars( $url );
828 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
832 * Make a link to a special page given its name and, optionally,
833 * a message key from the link text.
834 * Usage example: $skin->specialLink( 'recentchanges' )
836 static function specialLink( $name, $key = '' ) {
837 if ( $key == '' ) { $key = strtolower( $name ); }
839 return self
::linkKnown( SpecialPage
::getTitleFor( $name ) , wfMsg( $key ) );
843 * Make an external link
844 * @param $url String: URL to link to
845 * @param $text String: text of link
846 * @param $escape Boolean: do we escape the link text?
847 * @param $linktype String: type of external link. Gets added to the classes
848 * @param $attribs Array of extra attributes to <a>
850 static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
852 if ( isset($linktype) && $linktype ) {
853 $class .= " $linktype";
855 if ( isset($attribs['class']) && $attribs['class'] ) {
856 $class .= " {$attribs['class']}";
858 $attribs['class'] = $class;
861 $text = htmlspecialchars( $text );
864 $success = wfRunHooks( 'LinkerMakeExternalLink',
865 array( &$url, &$text, &$link, &$attribs, $linktype ) );
867 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
870 $attribs['href'] = $url;
871 return Html
::rawElement( 'a', $attribs, $text );
875 * Make user link (or user contributions for unregistered users)
876 * @param $userId Integer: user id in database.
877 * @param $userText String: user name in database
878 * @return String: HTML fragment
881 static function userLink( $userId, $userText ) {
882 if ( $userId == 0 ) {
883 $page = SpecialPage
::getTitleFor( 'Contributions', $userText );
885 $page = Title
::makeTitle( NS_USER
, $userText );
887 return self
::link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
891 * Generate standard user tool links (talk, contributions, block link, etc.)
893 * @param $userId Integer: user identifier
894 * @param $userText String: user name or IP address
895 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
896 * red if the user has no edits?
897 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK)
898 * @param $edits Integer: user edit count (optional, for performance)
899 * @return String: HTML fragment
901 public static function userToolLinks(
902 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
904 global $wgUser, $wgDisableAnonTalk, $wgLang;
905 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
906 $blockable = !$flags & self
::TOOL_LINKS_NOBLOCK
;
910 $items[] = self
::userTalkLink( $userId, $userText );
913 // check if the user has an edit
915 if ( $redContribsWhenNoEdits ) {
916 $count = !is_null( $edits ) ?
$edits : User
::edits( $userId );
918 $attribs['class'] = 'new';
921 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
923 $items[] = self
::link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
925 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
926 $items[] = self
::blockLink( $userId, $userText );
930 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
937 * Alias for userToolLinks( $userId, $userText, true );
938 * @param $userId Integer: user identifier
939 * @param $userText String: user name or IP address
940 * @param $edits Integer: user edit count (optional, for performance)
942 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
943 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
948 * @param $userId Integer: user id in database.
949 * @param $userText String: user name in database.
950 * @return String: HTML fragment with user talk link
953 static function userTalkLink( $userId, $userText ) {
954 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
955 $userTalkLink = self
::link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
956 return $userTalkLink;
960 * @param $userId Integer: userid
961 * @param $userText String: user name in database.
962 * @return String: HTML fragment with block link
965 static function blockLink( $userId, $userText ) {
966 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
967 $blockLink = self
::link( $blockPage, wfMsgHtml( 'blocklink' ) );
972 * Generate a user link if the current user is allowed to view it
973 * @param $rev Revision object.
974 * @param $isPublic Boolean: show only if all users can see it
975 * @return String: HTML fragment
977 static function revUserLink( $rev, $isPublic = false ) {
978 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
979 $link = wfMsgHtml( 'rev-deleted-user' );
980 } else if ( $rev->userCan( Revision
::DELETED_USER
) ) {
981 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
982 $rev->getUserText( Revision
::FOR_THIS_USER
) );
984 $link = wfMsgHtml( 'rev-deleted-user' );
986 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
987 return '<span class="history-deleted">' . $link . '</span>';
993 * Generate a user tool link cluster if the current user is allowed to view it
994 * @param $rev Revision object.
995 * @param $isPublic Boolean: show only if all users can see it
996 * @return string HTML
998 static function revUserTools( $rev, $isPublic = false ) {
999 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1000 $link = wfMsgHtml( 'rev-deleted-user' );
1001 } else if ( $rev->userCan( Revision
::DELETED_USER
) ) {
1002 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1003 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1004 $link = self
::userLink( $userId, $userText ) .
1005 ' ' . self
::userToolLinks( $userId, $userText );
1007 $link = wfMsgHtml( 'rev-deleted-user' );
1009 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1010 return ' <span class="history-deleted">' . $link . '</span>';
1016 * This function is called by all recent changes variants, by the page history,
1017 * and by the user contributions list. It is responsible for formatting edit
1018 * comments. It escapes any HTML in the comment, but adds some CSS to format
1019 * auto-generated comments (from section editing) and formats [[wikilinks]].
1021 * @author Erik Moeller <moeller@scireview.de>
1023 * Note: there's not always a title to pass to this function.
1024 * Since you can't set a default parameter for a reference, I've turned it
1025 * temporarily to a value pass. Should be adjusted further. --brion
1027 * @param $comment String
1028 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1029 * @param $local Boolean: whether section links should refer to local page
1031 static function formatComment( $comment, $title = null, $local = false ) {
1032 wfProfileIn( __METHOD__
);
1034 # Sanitize text a bit:
1035 $comment = str_replace( "\n", " ", $comment );
1036 # Allow HTML entities (for bug 13815)
1037 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1039 # Render autocomments and make links:
1040 $comment = self
::formatAutocomments( $comment, $title, $local );
1041 $comment = self
::formatLinksInComment( $comment, $title, $local );
1043 wfProfileOut( __METHOD__
);
1047 static $autocommentTitle;
1048 static $autocommentLocal;
1051 * The pattern for autogen comments is / * foo * /, which makes for
1053 * We look for all comments, match any text before and after the comment,
1054 * add a separator where needed and format the comment itself with CSS
1055 * Called by Linker::formatComment.
1057 * @param $comment String: comment text
1058 * @param $title An optional title object used to links to sections
1059 * @param $local Boolean: whether section links should refer to local page
1060 * @return String: formatted comment
1062 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1064 self
::$autocommentTitle = $title;
1065 self
::$autocommentLocal = $local;
1066 $comment = preg_replace_callback(
1067 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1068 array( 'Linker', 'formatAutocommentsCallback' ),
1070 self
::$autocommentTitle = null;
1071 self
::$autocommentLocal = null;
1075 private static function formatAutocommentsCallback( $match ) {
1076 $title = self
::$autocommentTitle;
1077 $local = self
::$autocommentLocal;
1086 # Remove links that a user may have manually put in the autosummary
1087 # This could be improved by copying as much of Parser::stripSectionName as desired.
1088 $section = str_replace( '[[:', '', $section );
1089 $section = str_replace( '[[', '', $section );
1090 $section = str_replace( ']]', '', $section );
1092 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1094 $sectionTitle = Title
::newFromText( '#' . $section );
1096 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1097 $title->getDBkey(), $section );
1099 if ( $sectionTitle ) {
1100 $link = self
::link( $sectionTitle,
1101 htmlspecialchars( wfMsgForContent( 'sectionlink' ) ), array(), array(),
1107 $auto = "$link$auto";
1109 # written summary $presep autocomment (summary /* section */)
1110 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1113 # autocomment $postsep written summary (/* section */ summary)
1114 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1116 $auto = '<span class="autocomment">' . $auto . '</span>';
1117 $comment = $pre . $auto . $post;
1121 static $commentContextTitle;
1122 static $commentLocal;
1125 * Formats wiki links and media links in text; all other wiki formatting
1128 * @todo Fixme: doesn't handle sub-links as in image thumb texts like the main parser
1129 * @param $comment String: text to format links in
1130 * @param $title An optional title object used to links to sections
1131 * @param $local Boolean: whether section links should refer to local page
1134 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1135 self
::$commentContextTitle = $title;
1136 self
::$commentLocal = $local;
1137 $html = preg_replace_callback(
1138 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1139 array( 'Linker', 'formatLinksInCommentCallback' ),
1141 self
::$commentContextTitle = null;
1142 self
::$commentLocal = null;
1146 protected static function formatLinksInCommentCallback( $match ) {
1149 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1150 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1152 $comment = $match[0];
1154 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1155 if ( strpos( $match[1], '%' ) !== false ) {
1156 $match[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $match[1] ) );
1159 # Handle link renaming [[foo|text]] will show link as "text"
1160 if ( $match[3] != "" ) {
1165 $submatch = array();
1167 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1168 # Media link; trail not supported.
1169 $linkRegexp = '/\[\[(.*?)\]\]/';
1170 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1171 $thelink = self
::makeMediaLinkObj( $title, $text );
1173 # Other kind of link
1174 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1175 $trail = $submatch[1];
1179 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1180 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1181 $match[1] = substr( $match[1], 1 );
1182 list( $inside, $trail ) = self
::splitTrail( $trail );
1185 $linkTarget = self
::normalizeSubpageLink( self
::$commentContextTitle,
1186 $match[1], $linkText );
1188 $target = Title
::newFromText( $linkTarget );
1190 if ( $target->getText() == '' && $target->getInterwiki() === ''
1191 && !self
::$commentLocal && self
::$commentContextTitle )
1193 $newTarget = clone ( self
::$commentContextTitle );
1194 $newTarget->setFragment( '#' . $target->getFragment() );
1195 $target = $newTarget;
1197 $thelink = self
::link(
1204 // If the link is still valid, go ahead and replace it in!
1205 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1212 * @param $contextTitle Title
1217 static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1220 # :Foobar -- override special treatment of prefix (images, language links)
1221 # /Foobar -- convert to CurrentPage/Foobar
1222 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1223 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1224 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1226 wfProfileIn( __METHOD__
);
1227 $ret = $target; # default return value is no change
1229 # Some namespaces don't allow subpages,
1230 # so only perform processing if subpages are allowed
1231 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1232 $hash = strpos( $target, '#' );
1233 if ( $hash !== false ) {
1234 $suffix = substr( $target, $hash );
1235 $target = substr( $target, 0, $hash );
1240 $target = trim( $target );
1241 # Look at the first character
1242 if ( $target != '' && $target { 0 } === '/' ) {
1243 # / at end means we don't want the slash to be shown
1245 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1246 if ( $trailingSlashes ) {
1247 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1249 $noslash = substr( $target, 1 );
1252 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1253 if ( $text === '' ) {
1254 $text = $target . $suffix;
1255 } # this might be changed for ugliness reasons
1257 # check for .. subpage backlinks
1259 $nodotdot = $target;
1260 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1262 $nodotdot = substr( $nodotdot, 3 );
1264 if ( $dotdotcount > 0 ) {
1265 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1266 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1267 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1268 # / at the end means don't show full path
1269 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1270 $nodotdot = substr( $nodotdot, 0, -1 );
1271 if ( $text === '' ) {
1272 $text = $nodotdot . $suffix;
1275 $nodotdot = trim( $nodotdot );
1276 if ( $nodotdot != '' ) {
1277 $ret .= '/' . $nodotdot;
1285 wfProfileOut( __METHOD__
);
1290 * Wrap a comment in standard punctuation and formatting if
1291 * it's non-empty, otherwise return empty string.
1293 * @param $comment String
1294 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1295 * @param $local Boolean: whether section links should refer to local page
1296 * @param $embraced Boolean: whether the formatted comment should be embraced with ()
1299 static function commentBlock( $comment, $title = null, $local = false, $embraced = true ) {
1300 // '*' used to be the comment inserted by the software way back
1301 // in antiquity in case none was provided, here for backwards
1302 // compatability, acc. to brion -ævar
1303 if ( $comment == '' ||
$comment == '*' ) {
1306 $formatted = self
::formatComment( $comment, $title, $local );
1308 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1310 return Html
::rawElement( 'span', array( 'class' => 'comment' ), $formatted );
1315 * Wrap and format the given revision's comment block, if the current
1316 * user is allowed to view it.
1318 * @param $rev Revision object
1319 * @param $local Boolean: whether section links should refer to local page
1320 * @param $isPublic Boolean: show only if all users can see it
1321 * @return String: HTML fragment
1323 static function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1324 if ( $rev->getRawComment() == "" ) {
1327 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1328 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1329 } else if ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1330 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1331 $rev->getTitle(), $local );
1333 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1335 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1336 return " <span class=\"history-deleted\">$block</span>";
1341 public static function formatRevisionSize( $size ) {
1343 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1346 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1349 $stxt = htmlspecialchars( $stxt );
1350 return "<span class=\"history-size\">$stxt</span>";
1354 * Add another level to the Table of Contents
1356 static function tocIndent() {
1361 * Finish one or more sublevels on the Table of Contents
1363 static function tocUnindent( $level ) {
1364 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1368 * parameter level defines if we are on an indentation level
1370 static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1371 $classes = "toclevel-$level";
1372 if ( $sectionIndex !== false )
1373 $classes .= " tocsection-$sectionIndex";
1374 return "\n<li class=\"$classes\"><a href=\"#" .
1375 $anchor . '"><span class="tocnumber">' .
1376 $tocnumber . '</span> <span class="toctext">' .
1377 $tocline . '</span></a>';
1381 * End a Table Of Contents line.
1382 * tocUnindent() will be used instead if we're ending a line below
1385 static function tocLineEnd() {
1390 * Wraps the TOC in a table and provides the hide/collapse javascript.
1392 * @param $toc String: html of the Table Of Contents
1393 * @param $lang mixed: Language code for the toc title
1394 * @return String: full html of the TOC
1396 static function tocList( $toc, $lang = false ) {
1397 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1399 '<table id="toc" class="toc"><tr><td>'
1400 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1402 . "</ul>\n</td></tr></table>\n";
1406 * Generate a table of contents from a section tree
1409 * @param $tree Return value of ParserOutput::getSections()
1410 * @return String: HTML fragment
1412 public static function generateTOC( $tree ) {
1415 foreach ( $tree as $section ) {
1416 if ( $section['toclevel'] > $lastLevel )
1417 $toc .= self
::tocIndent();
1418 else if ( $section['toclevel'] < $lastLevel )
1419 $toc .= self
::tocUnindent(
1420 $lastLevel - $section['toclevel'] );
1422 $toc .= self
::tocLineEnd();
1424 $toc .= self
::tocLine( $section['anchor'],
1425 $section['line'], $section['number'],
1426 $section['toclevel'], $section['index'] );
1427 $lastLevel = $section['toclevel'];
1429 $toc .= self
::tocLineEnd();
1430 return self
::tocList( $toc );
1434 * Create a headline for content
1436 * @param $level Integer: the level of the headline (1-6)
1437 * @param $attribs String: any attributes for the headline, starting with
1438 * a space and ending with '>'
1439 * This *must* be at least '>' for no attribs
1440 * @param $anchor String: the anchor to give the headline (the bit after the #)
1441 * @param $text String: the text of the header
1442 * @param $link String: HTML to add for the section edit link
1443 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1444 * backward compatibility (false to omit)
1446 * @return String: HTML headline
1448 public static function makeHeadline( $level, $attribs, $anchor, $text, $link, $legacyAnchor = false ) {
1449 $ret = "<h$level$attribs"
1451 . " <span class=\"mw-headline\" id=\"$anchor\">$text</span>"
1453 if ( $legacyAnchor !== false ) {
1454 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1460 * Split a link trail, return the "inside" portion and the remainder of the trail
1461 * as a two-element array
1463 static function splitTrail( $trail ) {
1465 $regex = $wgContLang->linkTrail();
1467 if ( $trail !== '' ) {
1469 if ( preg_match( $regex, $trail, $m ) ) {
1474 return array( $inside, $trail );
1478 * Generate a rollback link for a given revision. Currently it's the
1479 * caller's responsibility to ensure that the revision is the top one. If
1480 * it's not, of course, the user will get an error message.
1482 * If the calling page is called with the parameter &bot=1, all rollback
1483 * links also get that parameter. It causes the edit itself and the rollback
1484 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1485 * changes, so this allows sysops to combat a busy vandal without bothering
1488 * @param $rev Revision object
1490 static function generateRollback( $rev ) {
1491 return '<span class="mw-rollback-link">['
1492 . self
::buildRollbackLink( $rev )
1497 * Build a raw rollback link, useful for collections of "tool" links
1499 * @param $rev Revision object
1500 * @return String: HTML fragment
1502 public static function buildRollbackLink( $rev ) {
1503 global $wgRequest, $wgUser;
1504 $title = $rev->getTitle();
1506 'action' => 'rollback',
1507 'from' => $rev->getUserText(),
1508 'token' => $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1510 if ( $wgRequest->getBool( 'bot' ) ) {
1511 $query['bot'] = '1';
1512 $query['hidediff'] = '1'; // bug 15999
1516 wfMsgHtml( 'rollbacklink' ),
1517 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1519 array( 'known', 'noclasses' )
1524 * Returns HTML for the "templates used on this page" list.
1526 * @param $templates Array of templates from Article::getUsedTemplate
1528 * @param $preview Boolean: whether this is for a preview
1529 * @param $section Boolean: whether this is for a section edit
1530 * @return String: HTML output
1532 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1533 wfProfileIn( __METHOD__
);
1536 if ( count( $templates ) > 0 ) {
1537 # Do a batch existence check
1538 $batch = new LinkBatch
;
1539 foreach ( $templates as $title ) {
1540 $batch->addObj( $title );
1544 # Construct the HTML
1545 $outText = '<div class="mw-templatesUsedExplanation">';
1547 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1548 } elseif ( $section ) {
1549 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1551 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1553 $outText .= "</div><ul>\n";
1555 usort( $templates, array( 'Title', 'compare' ) );
1556 foreach ( $templates as $titleObj ) {
1557 $r = $titleObj->getRestrictions( 'edit' );
1558 if ( in_array( 'sysop', $r ) ) {
1559 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1560 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1561 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1565 if ( $titleObj->quickUserCan( 'edit' ) ) {
1566 $editLink = self
::link(
1568 wfMsg( 'editlink' ),
1570 array( 'action' => 'edit' )
1573 $editLink = self
::link(
1575 wfMsg( 'viewsourcelink' ),
1577 array( 'action' => 'edit' )
1580 $outText .= '<li>' . self
::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1582 $outText .= '</ul>';
1584 wfProfileOut( __METHOD__
);
1589 * Returns HTML for the "hidden categories on this page" list.
1591 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1593 * @return String: HTML output
1595 public static function formatHiddenCategories( $hiddencats ) {
1597 wfProfileIn( __METHOD__
);
1600 if ( count( $hiddencats ) > 0 ) {
1601 # Construct the HTML
1602 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1603 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1604 $outText .= "</div><ul>\n";
1606 foreach ( $hiddencats as $titleObj ) {
1607 $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
1609 $outText .= '</ul>';
1611 wfProfileOut( __METHOD__
);
1616 * Format a size in bytes for output, using an appropriate
1617 * unit (B, KB, MB or GB) according to the magnitude in question
1619 * @param $size Size to format
1622 public static function formatSize( $size ) {
1624 return htmlspecialchars( $wgLang->formatSize( $size ) );
1628 * Given the id of an interface element, constructs the appropriate title
1629 * attribute from the system messages. (Note, this is usually the id but
1630 * isn't always, because sometimes the accesskey needs to go on a different
1631 * element than the id, for reverse-compatibility, etc.)
1633 * @param $name String: id of the element, minus prefixes.
1634 * @param $options Mixed: null or the string 'withaccess' to add an access-
1636 * @return String: contents of the title attribute (which you must HTML-
1637 * escape), or false for no title attribute
1639 public static function titleAttrib( $name, $options = null ) {
1640 wfProfileIn( __METHOD__
);
1642 $message = wfMessage( "tooltip-$name" );
1644 if ( !$message->exists() ) {
1647 $tooltip = $message->text();
1648 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1649 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1650 # Message equal to '-' means suppress it.
1651 if ( $tooltip == '-' ) {
1656 if ( $options == 'withaccess' ) {
1657 $accesskey = self
::accesskey( $name );
1658 if ( $accesskey !== false ) {
1659 if ( $tooltip === false ||
$tooltip === '' ) {
1660 $tooltip = "[$accesskey]";
1662 $tooltip .= " [$accesskey]";
1667 wfProfileOut( __METHOD__
);
1671 static $accesskeycache;
1674 * Given the id of an interface element, constructs the appropriate
1675 * accesskey attribute from the system messages. (Note, this is usually
1676 * the id but isn't always, because sometimes the accesskey needs to go on
1677 * a different element than the id, for reverse-compatibility, etc.)
1679 * @param $name String: id of the element, minus prefixes.
1680 * @return String: contents of the accesskey attribute (which you must HTML-
1681 * escape), or false for no accesskey attribute
1683 public static function accesskey( $name ) {
1684 if ( isset( self
::$accesskeycache[$name] ) ) {
1685 return self
::$accesskeycache[$name];
1687 wfProfileIn( __METHOD__
);
1689 $message = wfMessage( "accesskey-$name" );
1691 if ( !$message->exists() ) {
1694 $accesskey = $message->plain();
1695 if ( $accesskey === '' ||
$accesskey === '-' ) {
1696 # FIXME: Per standard MW behavior, a value of '-' means to suppress the
1697 # attribute, but this is broken for accesskey: that might be a useful
1703 wfProfileOut( __METHOD__
);
1704 return self
::$accesskeycache[$name] = $accesskey;
1708 * Creates a (show/hide) link for deleting revisions/log entries
1710 * @param $query Array: query parameters to be passed to link()
1711 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1712 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1714 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1715 * span to allow for customization of appearance with CSS
1717 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1718 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1719 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1720 $tag = $restricted ?
'strong' : 'span';
1721 $link = self
::link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1722 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1726 * Creates a dead (show/hide) link for deleting revisions/log entries
1728 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1730 * @return string HTML text wrapped in a span to allow for customization
1731 * of appearance with CSS
1733 public static function revDeleteLinkDisabled( $delete = true ) {
1734 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1735 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($text)" );
1738 /* Deprecated methods */
1741 * @deprecated since 1.16 Use link()
1743 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
1744 * it if you already have a title object handy. See makeLinkObj for further documentation.
1746 * @param $title String: the text of the title
1747 * @param $text String: link text
1748 * @param $query String: optional query part
1749 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1750 * be included in the link text. Other characters will be appended after
1751 * the end of the link.
1753 static function makeLink( $title, $text = '', $query = '', $trail = '' ) {
1754 wfProfileIn( __METHOD__
);
1755 $nt = Title
::newFromText( $title );
1756 if ( $nt instanceof Title
) {
1757 $result = self
::makeLinkObj( $nt, $text, $query, $trail );
1759 wfDebug( 'Invalid title passed to self::makeLink(): "' . $title . "\"\n" );
1760 $result = $text == "" ?
$title : $text;
1763 wfProfileOut( __METHOD__
);
1768 * @deprecated since 1.16 Use link()
1770 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
1771 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
1773 * @param $title String: the text of the title
1774 * @param $text String: link text
1775 * @param $query String: optional query part
1776 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1777 * be included in the link text. Other characters will be appended after
1778 * the end of the link.
1779 * @param $prefix String: Optional prefix
1780 * @param $aprops String: extra attributes to the a-element
1782 static function makeKnownLink(
1783 $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = ''
1785 $nt = Title
::newFromText( $title );
1786 if ( $nt instanceof Title
) {
1787 return self
::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
1789 wfDebug( 'Invalid title passed to self::makeKnownLink(): "' . $title . "\"\n" );
1790 return $text == '' ?
$title : $text;
1795 * @deprecated since 1.16 Use link()
1797 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1798 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1800 * @param $title String: The text of the title
1801 * @param $text String: Link text
1802 * @param $query String: Optional query part
1803 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1804 * be included in the link text. Other characters will be appended after
1805 * the end of the link.
1807 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1808 $nt = Title
::newFromText( $title );
1809 if ( $nt instanceof Title
) {
1810 return self
::makeBrokenLinkObj( $nt, $text, $query, $trail );
1812 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
1813 return $text == '' ?
$title : $text;
1818 * @deprecated since 1.16 Use link()
1820 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
1821 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
1823 * @param $title String: the text of the title
1824 * @param $text String: link text
1825 * @param $query String: optional query part
1826 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1827 * be included in the link text. Other characters will be appended after
1828 * the end of the link.
1830 static function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
1831 wfDeprecated( __METHOD__
);
1832 $nt = Title
::newFromText( $title );
1833 if ( $nt instanceof Title
) {
1834 return self
::makeStubLinkObj( $nt, $text, $query, $trail );
1836 wfDebug( 'Invalid title passed to self::makeStubLink(): "' . $title . "\"\n" );
1837 return $text == '' ?
$title : $text;
1842 * @deprecated since 1.16 Use link()
1844 * Make a link for a title which may or may not be in the database. If you need to
1845 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1846 * call to this will result in a DB query.
1848 * @param $nt Title: the title object to make the link from, e.g. from
1849 * Title::newFromText.
1850 * @param $text String: link text
1851 * @param $query String: optional query part
1852 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1853 * be included in the link text. Other characters will be appended after
1854 * the end of the link.
1855 * @param $prefix String: optional prefix. As trail, only before instead of after.
1857 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1858 wfProfileIn( __METHOD__
);
1859 $query = wfCgiToArray( $query );
1860 list( $inside, $trail ) = self
::splitTrail( $trail );
1861 if ( $text === '' ) {
1862 $text = self
::linkText( $nt );
1865 $ret = self
::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1867 wfProfileOut( __METHOD__
);
1872 * @deprecated since 1.16 Use link()
1874 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1875 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1878 * @param $title Title object of target page
1879 * @param $text String: text to replace the title
1880 * @param $query String: link target
1881 * @param $trail String: text after link
1882 * @param $prefix String: text before link text
1883 * @param $aprops String: extra attributes to the a-element
1884 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1885 * @return the a-element
1887 static function makeKnownLinkObj(
1888 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
1890 wfProfileIn( __METHOD__
);
1892 if ( $text == '' ) {
1893 $text = self
::linkText( $title );
1895 $attribs = Sanitizer
::mergeAttributes(
1896 Sanitizer
::decodeTagAttributes( $aprops ),
1897 Sanitizer
::decodeTagAttributes( $style )
1899 $query = wfCgiToArray( $query );
1900 list( $inside, $trail ) = self
::splitTrail( $trail );
1902 $ret = self
::link( $title, "$prefix$text$inside", $attribs, $query,
1903 array( 'known', 'noclasses' ) ) . $trail;
1905 wfProfileOut( __METHOD__
);
1910 * @deprecated since 1.16 Use link()
1912 * Make a red link to the edit page of a given title.
1914 * @param $title Title object of the target page
1915 * @param $text String: Link text
1916 * @param $query String: Optional query part
1917 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1918 * be included in the link text. Other characters will be appended after
1919 * the end of the link.
1920 * @param $prefix String: Optional prefix
1922 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
1923 wfProfileIn( __METHOD__
);
1925 list( $inside, $trail ) = self
::splitTrail( $trail );
1926 if ( $text === '' ) {
1927 $text = self
::linkText( $title );
1930 $ret = self
::link( $title, "$prefix$text$inside", array(),
1931 wfCgiToArray( $query ), 'broken' ) . $trail;
1933 wfProfileOut( __METHOD__
);
1938 * @deprecated since 1.16 Use link()
1940 * Make a brown link to a short article.
1942 * @param $nt Title object of the target page
1943 * @param $text String: link text
1944 * @param $query String: optional query part
1945 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1946 * be included in the link text. Other characters will be appended after
1947 * the end of the link.
1948 * @param $prefix String: Optional prefix
1950 static function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1951 return self
::makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
1955 * @deprecated since 1.16 Use link()
1957 * Make a coloured link.
1959 * @param $nt Title object of the target page
1960 * @param $colour Integer: colour of the link
1961 * @param $text String: link text
1962 * @param $query String: optional query part
1963 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1964 * be included in the link text. Other characters will be appended after
1965 * the end of the link.
1966 * @param $prefix String: Optional prefix
1968 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
1969 if ( $colour != '' ) {
1970 $style = self
::getInternalLinkAttributesObj( $nt, $text, $colour );
1974 return self
::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
1977 /** Obsolete alias */
1978 static function makeImage( $url, $alt = '' ) {
1979 wfDeprecated( __METHOD__
);
1980 return self
::makeExternalImage( $url, $alt );
1984 * Creates the HTML source for images
1985 * @deprecated since 1.16 use makeImageLink2
1987 * @param $title Title object
1988 * @param $label String: label text
1989 * @param $alt String: alt text
1990 * @param $align String: horizontal alignment: none, left, center, right)
1991 * @param $handlerParams Array: parameters to be passed to the media handler
1992 * @param $framed Boolean: shows image in original size in a frame
1993 * @param $thumb Boolean: shows image as thumbnail in a frame
1994 * @param $manualthumb String: image name for the manual thumbnail
1995 * @param $valign String: vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
1996 * @param $time String: timestamp of the file, set as false for current
1999 static function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(),
2000 $framed = false, $thumb = false, $manualthumb = '', $valign = '', $time = false )
2002 $frameParams = array( 'alt' => $alt, 'caption' => $label );
2004 $frameParams['align'] = $align;
2007 $frameParams['framed'] = true;
2010 $frameParams['thumbnail'] = true;
2012 if ( $manualthumb ) {
2013 $frameParams['manualthumb'] = $manualthumb;
2016 $frameParams['valign'] = $valign;
2018 $file = wfFindFile( $title, array( 'time' => $time ) );
2019 return self
::makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
2022 /** @deprecated use Linker::makeMediaLinkObj() */
2023 static function makeMediaLink( $name, $unused = '', $text = '', $time = false ) {
2024 $nt = Title
::makeTitleSafe( NS_FILE
, $name );
2025 return self
::makeMediaLinkObj( $nt, $text, $time );
2029 * Returns the attributes for the tooltip and access key.
2031 public static function tooltipAndAccesskeyAttribs( $name ) {
2032 global $wgEnableTooltipsAndAccesskeys;
2033 if ( !$wgEnableTooltipsAndAccesskeys )
2035 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2036 # no attribute" instead of "output '' as value for attribute", this
2037 # would be three lines.
2039 'title' => self
::titleAttrib( $name, 'withaccess' ),
2040 'accesskey' => self
::accesskey( $name )
2042 if ( $attribs['title'] === false ) {
2043 unset( $attribs['title'] );
2045 if ( $attribs['accesskey'] === false ) {
2046 unset( $attribs['accesskey'] );
2052 * @deprecated since 1.14
2053 * Returns raw bits of HTML, use titleAttrib() and accesskey()
2055 public static function tooltipAndAccesskey( $name ) {
2056 return Xml
::expandAttributes( self
::tooltipAndAccesskeyAttribs( $name ) );
2060 * @deprecated since 1.14
2061 * Returns raw bits of HTML, use titleAttrib()
2063 public static function tooltip( $name, $options = null ) {
2064 global $wgEnableTooltipsAndAccesskeys;
2065 if ( !$wgEnableTooltipsAndAccesskeys )
2067 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2068 # no attribute" instead of "output '' as value for attribute", this
2069 # would be two lines.
2070 $tooltip = self
::titleAttrib( $name, $options );
2071 if ( $tooltip === false ) {
2074 return Xml
::expandAttributes( array(
2075 'title' => self
::titleAttrib( $name, $options )
2083 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2084 * into static calls to the new Linker for backwards compatibility.
2086 * @param $fname String Name of called method
2087 * @param $args Array Arguments to the method
2089 function __call( $fname, $args ) {
2090 return call_user_func_array( array( 'Linker', $fname ), $args );