3 * Split off some of the internal bits 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. For the moment, Skin is a descendent class of
6 * Linker. In the future, it should probably be further split so that every
7 * other bit of the wiki doesn't have to go loading up Skin to get at it.
14 * Flags for userToolLinks()
16 const TOOL_LINKS_NOBLOCK
= 1;
18 function __construct() {}
21 * Get the appropriate HTML attributes to add to the "a" element of an ex-
22 * ternal link, as created by [wikisyntax].
24 * @param $class String: the contents of the class attribute; if an empty
25 * string is passed, which is the default value, defaults to 'external'.
26 * @deprecated Just pass the external class directly to something using Html::expandAttributes
28 function getExternalLinkAttributes( $class = 'external' ) {
29 wfDeprecated( __METHOD__
);
30 return $this->getLinkAttributesInternal( '', $class );
34 * Get the appropriate HTML attributes to add to the "a" element of an in-
37 * @param $title String: the title text for the link, URL-encoded (???) but
39 * @param $unused String: unused
40 * @param $class String: the contents of the class attribute; if an empty
41 * string is passed, which is the default value, defaults to 'external'.
43 function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
46 # FIXME: We have a whole bunch of handling here that doesn't happen in
47 # getExternalLinkAttributes, why?
48 $title = urldecode( $title );
49 $title = $wgContLang->checkTitleEncoding( $title );
50 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
52 return $this->getLinkAttributesInternal( $title, $class );
56 * Get the appropriate HTML attributes to add to the "a" element of an in-
59 * @param $title String: the title text for the link, URL-encoded (???) but
61 * @param $unused String: unused
62 * @param $class String: the contents of the class attribute, default none
64 function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
65 $title = urldecode( $title );
66 $title = str_replace( '_', ' ', $title );
67 return $this->getLinkAttributesInternal( $title, $class );
71 * Get the appropriate HTML attributes to add to the "a" element of an in-
72 * ternal link, given the Title object for the page we want to link to.
75 * @param $unused String: unused
76 * @param $class String: the contents of the class attribute, default none
77 * @param $title Mixed: optional (unescaped) string to use in the title
78 * attribute; if false, default to the name of the page we're linking to
80 function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
81 if ( $title === false ) {
82 $title = $nt->getPrefixedText();
84 return $this->getLinkAttributesInternal( $title, $class );
88 * Common code for getLinkAttributesX functions
90 private function getLinkAttributesInternal( $title, $class ) {
91 $title = htmlspecialchars( $title );
92 $class = htmlspecialchars( $class );
95 $r .= " class=\"$class\"";
98 $r .= " title=\"$title\"";
104 * Return the CSS colour of a known link
106 * @param $t Title object
107 * @param $threshold Integer: user defined threshold
108 * @return String: CSS class
110 function getLinkColour( $t, $threshold ) {
112 if ( $t->isRedirect() ) {
114 $colour = 'mw-redirect';
115 } elseif ( $threshold > 0 &&
116 $t->exists() && $t->getLength() < $threshold &&
117 $t->isContentPage() ) {
125 * This function returns an HTML link to the given target. It serves a few
127 * 1) If $target is a Title, the correct URL to link to will be figured
129 * 2) It automatically adds the usual classes for various types of link
130 * targets: "new" for red links, "stub" for short articles, etc.
131 * 3) It escapes all attribute values safely so there's no risk of XSS.
132 * 4) It provides a default tooltip if the target is a Title (the page
133 * name of the target).
134 * link() replaces the old functions in the makeLink() family.
136 * @param $target Title Can currently only be a Title, but this may
137 * change to support Images, literal URLs, etc.
138 * @param $text string The HTML contents of the <a> element, i.e.,
139 * the link text. This is raw HTML and will not be escaped. If null,
140 * defaults to the prefixed text of the Title; or if the Title is just a
141 * fragment, the contents of the fragment.
142 * @param $customAttribs array A key => value array of extra HTML attri-
143 * butes, such as title and class. (href is ignored.) Classes will be
144 * merged with the default classes, while other attributes will replace
145 * default attributes. All passed attribute values will be HTML-escaped.
146 * A false attribute value means to suppress that attribute.
147 * @param $query array The query string to append to the URL
148 * you're linking to, in key => value array form. Query keys and values
149 * will be URL-encoded.
150 * @param $options mixed String or array of strings:
151 * 'known': Page is known to exist, so don't check if it does.
152 * 'broken': Page is known not to exist, so don't check if it does.
153 * 'noclasses': Don't add any classes automatically (includes "new",
154 * "stub", "mw-redirect", "extiw"). Only use the class attribute
155 * provided, if any, so you get a simple blue link with no funny i-
157 * 'forcearticlepath': Use the article path always, even with a querystring.
158 * Has compatibility issues on some setups, so avoid wherever possible.
159 * @return string HTML <a> attribute
161 public function link(
162 $target, $text = null, $customAttribs = array(), $query = array(), $options = array()
164 wfProfileIn( __METHOD__
);
165 if ( !$target instanceof Title
) {
166 wfProfileOut( __METHOD__
);
167 return "<!-- ERROR -->$text";
169 $options = (array)$options;
172 if ( !wfRunHooks( 'LinkBegin', array( $this, $target, &$text,
173 &$customAttribs, &$query, &$options, &$ret ) ) ) {
174 wfProfileOut( __METHOD__
);
178 # Normalize the Title if it's a special page
179 $target = $this->normaliseSpecialPage( $target );
181 # If we don't know whether the page exists, let's find out.
182 wfProfileIn( __METHOD__
. '-checkPageExistence' );
183 if ( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
184 if ( $target->isKnown() ) {
185 $options[] = 'known';
187 $options[] = 'broken';
190 wfProfileOut( __METHOD__
. '-checkPageExistence' );
193 if ( in_array( "forcearticlepath", $options ) && $query ) {
198 # Note: we want the href attribute first, for prettiness.
199 $attribs = array( 'href' => $this->linkUrl( $target, $query, $options ) );
200 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
201 $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
204 $attribs = array_merge(
206 $this->linkAttribs( $target, $customAttribs, $options, $text )
208 if ( is_null( $text ) ) {
209 $text = $this->linkText( $target );
213 if ( wfRunHooks( 'LinkEnd', array( $this, $target, $options, &$text, &$attribs, &$ret ) ) ) {
214 $ret = Html
::rawElement( 'a', $attribs, $text );
217 wfProfileOut( __METHOD__
);
222 * Identical to link(), except $options defaults to 'known'.
224 public function linkKnown(
225 $target, $text = null, $customAttribs = array(),
226 $query = array(), $options = array( 'known', 'noclasses' ) )
228 return $this->link( $target, $text, $customAttribs, $query, $options );
232 * Returns the Url used to link to a Title
234 * @param $target Title
236 private function linkUrl( $target, $query, $options ) {
237 wfProfileIn( __METHOD__
);
238 # We don't want to include fragments for broken links, because they
239 # generally make no sense.
240 if ( in_array( 'broken', $options ) && $target->mFragment
!== '' ) {
241 $target = clone $target;
242 $target->mFragment
= '';
245 # If it's a broken link, add the appropriate query pieces, unless
246 # there's already an action specified, or unless 'edit' makes no sense
247 # (i.e., for a nonexistent special page).
248 if ( in_array( 'broken', $options ) && empty( $query['action'] )
249 && $target->getNamespace() != NS_SPECIAL
) {
250 $query['action'] = 'edit';
251 $query['redlink'] = '1';
253 $ret = $target->getLinkUrl( $query );
254 wfProfileOut( __METHOD__
);
259 * Returns the array of attributes used when linking to the Title $target
261 * @param $target Title
263 private function linkAttribs( $target, $attribs, $options, $linkText ) {
264 wfProfileIn( __METHOD__
);
268 if ( !in_array( 'noclasses', $options ) ) {
269 wfProfileIn( __METHOD__
. '-getClasses' );
270 # Now build the classes.
273 if ( in_array( 'broken', $options ) ) {
277 if ( $target->isExternal() ) {
278 $classes[] = 'extiw';
281 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
282 $colour = $this->getLinkColour( $target, $wgUser->getStubThreshold() );
283 if ( $colour !== '' ) {
284 $classes[] = $colour; # mw-redirect or stub
287 if ( $classes != array() ) {
288 $defaults['class'] = implode( ' ', $classes );
290 wfProfileOut( __METHOD__
. '-getClasses' );
293 # Get a default title attribute.
295 $known = in_array( 'known', $options );
296 if ( $target->getPrefixedText() == '' ) {
297 # A link like [[#Foo]]. This used to mean an empty title
298 # attribute, but that's silly. Just don't output a title.
300 $wgLang->caseFold($linkText) !== $wgLang->caseFold($target->getPrefixedText() ) )
302 $defaults['title'] = $target->getPrefixedText();
303 } elseif ( !$known ) {
304 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
307 # Finally, merge the custom attribs with the default ones, and iterate
308 # over that, deleting all "false" attributes.
310 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
311 foreach ( $merged as $key => $val ) {
312 # A false value suppresses the attribute, and we don't want the
313 # href attribute to be overridden.
314 if ( $key != 'href' and $val !== false ) {
318 wfProfileOut( __METHOD__
);
323 * Default text of the links to the Title $target
325 * @param $target Title
327 private function linkText( $target ) {
328 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
329 if ( !$target instanceof Title
) {
333 # If the target is just a fragment, with no title, we return the frag-
334 # ment text. Otherwise, we return the title text itself.
335 if ( $target->getPrefixedText() === '' && $target->getFragment() !== '' ) {
336 return htmlspecialchars( $target->getFragment() );
338 return htmlspecialchars( $target->getPrefixedText() );
342 * Generate either a normal exists-style link or a stub link, depending
343 * on the given page size.
345 * @param $size Integer
346 * @param $nt Title object.
347 * @param $text String
348 * @param $query String
349 * @param $trail String
350 * @param $prefix String
351 * @return string HTML of link
352 * @deprecated since 1.17
354 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
356 wfDeprecated( __METHOD__
);
358 $threshold = $wgUser->getStubThreshold();
359 $colour = ( $size < $threshold ) ?
'stub' : '';
360 // FIXME: replace deprecated makeColouredLinkObj by link()
361 return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
365 * Make appropriate markup for a link to the current article. This is currently rendered
366 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
367 * despite $query not being used.
371 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
373 $text = htmlspecialchars( $nt->getPrefixedText() );
375 list( $inside, $trail ) = Linker
::splitTrail( $trail );
376 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
379 function normaliseSpecialPage( Title
$title ) {
380 if ( $title->getNamespace() == NS_SPECIAL
) {
381 list( $name, $subpage ) = SpecialPage
::resolveAliasWithSubpage( $title->getDBkey() );
385 $ret = SpecialPage
::getTitleFor( $name, $subpage );
386 $ret->mFragment
= $title->getFragment();
394 * Returns the filename part of an url.
395 * Used as alternative text for external images.
397 function fnamePart( $url ) {
398 $basename = strrchr( $url, '/' );
399 if ( false === $basename ) {
402 $basename = substr( $basename, 1 );
408 * Return the code for images which were added via external links,
409 * via Parser::maybeMakeExternalImage().
411 function makeExternalImage( $url, $alt = '' ) {
413 $alt = $this->fnamePart( $url );
416 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
418 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
421 return Html
::element( 'img',
428 * Given parameters derived from [[Image:Foo|options...]], generate the
429 * HTML that that syntax inserts in the page.
431 * @param $title Title object
432 * @param $file File object, or false if it doesn't exist
433 * @param $frameParams Array: associative array of parameters external to the media handler.
434 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
435 * will often be false.
436 * thumbnail If present, downscale and frame
437 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
438 * framed Shows image in original size in a frame
439 * frameless Downscale but don't frame
440 * upright If present, tweak default sizes for portrait orientation
441 * upright_factor Fudge factor for "upright" tweak (default 0.75)
442 * border If present, show a border around the image
443 * align Horizontal alignment (left, right, center, none)
444 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
445 * bottom, text-bottom)
446 * alt Alternate text for image (i.e. alt attribute). Plain text.
447 * caption HTML for image caption.
448 * link-url URL to link to
449 * link-title Title object to link to
450 * link-target Value for the target attribue, only with link-url
451 * no-link Boolean, suppress description link
453 * @param $handlerParams Array: associative array of media handler parameters, to be passed
454 * to transform(). Typical keys are "width" and "page".
455 * @param $time String: timestamp of the file, set as false for current
456 * @param $query String: query params for desc url
457 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
458 * @return String: HTML for an image, with links, wrappers, etc.
460 function makeImageLink2( Title
$title, $file, $frameParams = array(),
461 $handlerParams = array(), $time = false, $query = "", $widthOption = null )
464 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$this, &$title,
465 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
469 if ( $file && !$file->allowInlineDisplay() ) {
470 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
471 return $this->link( $title );
476 $hp =& $handlerParams;
478 // Clean up parameters
479 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
480 if ( !isset( $fp['align'] ) ) {
483 if ( !isset( $fp['alt'] ) ) {
486 if ( !isset( $fp['title'] ) ) {
490 $prefix = $postfix = '';
492 if ( 'center' == $fp['align'] ) {
493 $prefix = '<div class="center">';
495 $fp['align'] = 'none';
497 if ( $file && !isset( $hp['width'] ) ) {
498 $hp['width'] = $file->getWidth( $page );
500 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
501 global $wgThumbLimits, $wgThumbUpright;
502 if ( !isset( $widthOption ) ||
!isset( $wgThumbLimits[$widthOption] ) ) {
503 $widthOption = User
::getDefaultOption( 'thumbsize' );
506 // Reduce width for upright images when parameter 'upright' is used
507 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
508 $fp['upright'] = $wgThumbUpright;
510 // 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
511 $prefWidth = isset( $fp['upright'] ) ?
512 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
513 $wgThumbLimits[$widthOption];
515 // Use width which is smaller: real image width or user preference width
516 // Unless image is scalable vector.
517 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
518 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
519 $hp['width'] = $prefWidth;
524 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
526 # Create a thumbnail. Alignment depends on language
527 # writing direction, # right aligned for left-to-right-
528 # languages ("Western languages"), left-aligned
529 # for right-to-left-languages ("Semitic languages")
531 # If thumbnail width has not been provided, it is set
532 # to the default user option as specified in Language*.php
533 if ( $fp['align'] == '' ) {
534 $fp['align'] = $wgContLang->alignEnd();
536 return $prefix . $this->makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
539 if ( $file && isset( $fp['frameless'] ) ) {
540 $srcWidth = $file->getWidth( $page );
541 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
542 # This is the same behaviour as the "thumb" option does it already.
543 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
544 $hp['width'] = $srcWidth;
548 if ( $file && isset( $hp['width'] ) ) {
549 # Create a resized image, without the additional thumbnail features
550 $thumb = $file->transform( $hp );
556 $s = $this->makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
560 'title' => $fp['title'],
561 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
562 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
563 $params = $this->getImageLinkMTOParams( $fp, $query ) +
$params;
565 $s = $thumb->toHtml( $params );
567 if ( $fp['align'] != '' ) {
568 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
570 return str_replace( "\n", ' ', $prefix . $s . $postfix );
574 * Get the link parameters for MediaTransformOutput::toHtml() from given
575 * frame parameters supplied by the Parser.
576 * @param $frameParams The frame parameters
577 * @param $query An optional query string to add to description page links
579 function getImageLinkMTOParams( $frameParams, $query = '' ) {
580 $mtoParams = array();
581 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
582 $mtoParams['custom-url-link'] = $frameParams['link-url'];
583 if ( isset( $frameParams['link-target'] ) ) {
584 $mtoParams['custom-target-link'] = $frameParams['link-target'];
586 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
587 $mtoParams['custom-title-link'] = $this->normaliseSpecialPage( $frameParams['link-title'] );
588 } elseif ( !empty( $frameParams['no-link'] ) ) {
591 $mtoParams['desc-link'] = true;
592 $mtoParams['desc-query'] = $query;
598 * Make HTML for a thumbnail including image, border and caption
599 * @param $title Title object
600 * @param $file File object or false if it doesn't exist
601 * @param $label String
603 * @param $align String
604 * @param $params Array
605 * @param $framed Boolean
606 * @param $manualthumb String
608 function makeThumbLinkObj( Title
$title, $file, $label = '', $alt,
609 $align = 'right', $params = array(), $framed = false , $manualthumb = "" )
611 $frameParams = array(
617 $frameParams['framed'] = true;
619 if ( $manualthumb ) {
620 $frameParams['manualthumb'] = $manualthumb;
622 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
626 * @param $title Title
628 * @param array $frameParams
629 * @param array $handlerParams
631 * @param string $query
634 function makeThumbLink2( Title
$title, $file, $frameParams = array(),
635 $handlerParams = array(), $time = false, $query = "" )
638 $exists = $file && $file->exists();
642 $hp =& $handlerParams;
644 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
645 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
646 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
647 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
648 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
650 if ( empty( $hp['width'] ) ) {
651 // Reduce width for upright images when parameter 'upright' is used
652 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
657 $outerWidth = $hp['width'] +
2;
659 if ( isset( $fp['manualthumb'] ) ) {
660 # Use manually specified thumbnail
661 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
662 if ( $manual_title ) {
663 $manual_img = wfFindFile( $manual_title );
665 $thumb = $manual_img->getUnscaledThumb( $hp );
670 } elseif ( isset( $fp['framed'] ) ) {
671 // Use image dimensions, don't scale
672 $thumb = $file->getUnscaledThumb( $hp );
674 # Do not present an image bigger than the source, for bitmap-style images
675 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
676 $srcWidth = $file->getWidth( $page );
677 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
678 $hp['width'] = $srcWidth;
680 $thumb = $file->transform( $hp );
684 $outerWidth = $thumb->getWidth() +
2;
686 $outerWidth = $hp['width'] +
2;
690 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
691 # So we don't need to pass it here in $query. However, the URL for the
692 # zoom icon still needs it, so we make a unique query for it. See bug 14771
693 $url = $title->getLocalURL( $query );
695 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
698 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
700 $s .= $this->makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
702 } elseif ( !$thumb ) {
703 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
708 'title' => $fp['title'],
709 'img-class' => 'thumbimage' );
710 $params = $this->getImageLinkMTOParams( $fp, $query ) +
$params;
711 $s .= $thumb->toHtml( $params );
712 if ( isset( $fp['framed'] ) ) {
715 $zoomIcon = '<div class="magnify">' .
716 '<a href="' . htmlspecialchars( $url ) . '" class="internal" ' .
717 'title="' . htmlspecialchars( wfMsg( 'thumbnail-more' ) ) . '">' .
718 '<img src="' . htmlspecialchars( $wgStylePath ) . '/common/images/magnify-clip.png" ' .
719 'width="15" height="11" alt="" /></a></div>';
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 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 $this->linkKnown( $title, "$prefix$text$inside", array(), $query ) . $trail;
755 $href = $this->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 $this->linkKnown( $title, "$prefix$text$inside", array(), $query ) . $trail;
766 wfProfileOut( __METHOD__
);
767 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
772 * Get the URL to upload a certain file
774 * @param $destFile Title object of the file to upload
775 * @param $query String: urlencoded query string to prepend
776 * @return String: urlencoded URL
778 protected function getUploadUrl( $destFile, $query = '' ) {
779 global $wgUploadMissingFileUrl;
780 $q = 'wpDestFile=' . $destFile->getPartialUrl();
784 if ( $wgUploadMissingFileUrl ) {
785 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
787 $upload = SpecialPage
::getTitleFor( 'Upload' );
788 return $upload->getLocalUrl( $q );
793 * Create a direct link to a given uploaded file.
795 * @param $title Title object.
796 * @param $text String: pre-sanitized HTML
797 * @param $time string: MW timestamp of file creation time
798 * @return String: HTML
800 public function makeMediaLinkObj( $title, $text = '', $time = false ) {
801 $img = wfFindFile( $title, array( 'time' => $time ) );
802 return $this->makeMediaLinkFile( $title, $img, $text );
806 * Create a direct link to a given uploaded file.
807 * This will make a broken link if $file is false.
809 * @param $title Title object.
810 * @param $file mixed File object or false
811 * @param $text String: pre-sanitized HTML
812 * @return String: HTML
814 * @todo Handle invalid or missing images better.
816 public function makeMediaLinkFile( Title
$title, $file, $text = '' ) {
817 if ( $file && $file->exists() ) {
818 $url = $file->getURL();
821 $url = $this->getUploadUrl( $title );
824 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES
);
828 $u = htmlspecialchars( $url );
829 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
833 * Make a link to a special page given its name and, optionally,
834 * a message key from the link text.
835 * Usage example: $skin->specialLink( 'recentchanges' )
837 function specialLink( $name, $key = '' ) {
838 if ( $key == '' ) { $key = strtolower( $name ); }
840 return $this->linkKnown( SpecialPage
::getTitleFor( $name ) , wfMsg( $key ) );
844 * Make an external link
845 * @param $url String: URL to link to
846 * @param $text String: text of link
847 * @param $escape Boolean: do we escape the link text?
848 * @param $linktype String: type of external link. Gets added to the classes
849 * @param $attribs Array of extra attributes to <a>
851 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
853 if ( isset($linktype) && $linktype ) {
854 $class .= " $linktype";
856 if ( isset($attribs['class']) && $attribs['class'] ) {
857 $class .= " {$attribs['class']}";
859 $attribs['class'] = $class;
862 $text = htmlspecialchars( $text );
865 $success = wfRunHooks( 'LinkerMakeExternalLink',
866 array( &$url, &$text, &$link, &$attribs, $linktype ) );
868 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
871 $attribs['href'] = $url;
872 return Html
::rawElement( 'a', $attribs, $text );
876 * Make user link (or user contributions for unregistered users)
877 * @param $userId Integer: user id in database.
878 * @param $userText String: user name in database
879 * @return String: HTML fragment
882 function userLink( $userId, $userText ) {
883 if ( $userId == 0 ) {
884 $page = SpecialPage
::getTitleFor( 'Contributions', $userText );
886 $page = Title
::makeTitle( NS_USER
, $userText );
888 return $this->link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
892 * Generate standard user tool links (talk, contributions, block link, etc.)
894 * @param $userId Integer: user identifier
895 * @param $userText String: user name or IP address
896 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
897 * red if the user has no edits?
898 * @param $flags Integer: customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
899 * @param $edits Integer: user edit count (optional, for performance)
900 * @return String: HTML fragment
902 public function userToolLinks(
903 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
905 global $wgUser, $wgDisableAnonTalk, $wgLang;
906 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
907 $blockable = !$flags & self
::TOOL_LINKS_NOBLOCK
;
911 $items[] = $this->userTalkLink( $userId, $userText );
914 // check if the user has an edit
916 if ( $redContribsWhenNoEdits ) {
917 $count = !is_null( $edits ) ?
$edits : User
::edits( $userId );
919 $attribs['class'] = 'new';
922 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
924 $items[] = $this->link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
926 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
927 $items[] = $this->blockLink( $userId, $userText );
931 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
938 * Alias for userToolLinks( $userId, $userText, true );
939 * @param $userId Integer: user identifier
940 * @param $userText String: user name or IP address
941 * @param $edits Integer: user edit count (optional, for performance)
943 public function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
944 return $this->userToolLinks( $userId, $userText, true, 0, $edits );
949 * @param $userId Integer: user id in database.
950 * @param $userText String: user name in database.
951 * @return String: HTML fragment with user talk link
954 function userTalkLink( $userId, $userText ) {
955 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
956 $userTalkLink = $this->link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
957 return $userTalkLink;
961 * @param $userId Integer: userid
962 * @param $userText String: user name in database.
963 * @return String: HTML fragment with block link
966 function blockLink( $userId, $userText ) {
967 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
968 $blockLink = $this->link( $blockPage, wfMsgHtml( 'blocklink' ) );
973 * Generate a user link if the current user is allowed to view it
974 * @param $rev Revision object.
975 * @param $isPublic Boolean: show only if all users can see it
976 * @return String: HTML fragment
978 function revUserLink( $rev, $isPublic = false ) {
979 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
980 $link = wfMsgHtml( 'rev-deleted-user' );
981 } else if ( $rev->userCan( Revision
::DELETED_USER
) ) {
982 $link = $this->userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
983 $rev->getUserText( Revision
::FOR_THIS_USER
) );
985 $link = wfMsgHtml( 'rev-deleted-user' );
987 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
988 return '<span class="history-deleted">' . $link . '</span>';
994 * Generate a user tool link cluster if the current user is allowed to view it
995 * @param $rev Revision object.
996 * @param $isPublic Boolean: show only if all users can see it
997 * @return string HTML
999 function revUserTools( $rev, $isPublic = false ) {
1000 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1001 $link = wfMsgHtml( 'rev-deleted-user' );
1002 } else if ( $rev->userCan( Revision
::DELETED_USER
) ) {
1003 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1004 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1005 $link = $this->userLink( $userId, $userText ) .
1006 ' ' . $this->userToolLinks( $userId, $userText );
1008 $link = wfMsgHtml( 'rev-deleted-user' );
1010 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1011 return ' <span class="history-deleted">' . $link . '</span>';
1017 * This function is called by all recent changes variants, by the page history,
1018 * and by the user contributions list. It is responsible for formatting edit
1019 * comments. It escapes any HTML in the comment, but adds some CSS to format
1020 * auto-generated comments (from section editing) and formats [[wikilinks]].
1022 * @author Erik Moeller <moeller@scireview.de>
1024 * Note: there's not always a title to pass to this function.
1025 * Since you can't set a default parameter for a reference, I've turned it
1026 * temporarily to a value pass. Should be adjusted further. --brion
1028 * @param $comment String
1029 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1030 * @param $local Boolean: whether section links should refer to local page
1032 function formatComment( $comment, $title = null, $local = false ) {
1033 wfProfileIn( __METHOD__
);
1035 # Sanitize text a bit:
1036 $comment = str_replace( "\n", " ", $comment );
1037 # Allow HTML entities (for bug 13815)
1038 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1040 # Render autocomments and make links:
1041 $comment = $this->formatAutocomments( $comment, $title, $local );
1042 $comment = $this->formatLinksInComment( $comment, $title, $local );
1044 wfProfileOut( __METHOD__
);
1049 * The pattern for autogen comments is / * foo * /, which makes for
1051 * We look for all comments, match any text before and after the comment,
1052 * add a separator where needed and format the comment itself with CSS
1053 * Called by Linker::formatComment.
1055 * @param $comment String: comment text
1056 * @param $title An optional title object used to links to sections
1057 * @param $local Boolean: whether section links should refer to local page
1058 * @return String: formatted comment
1060 private function formatAutocomments( $comment, $title = null, $local = false ) {
1062 $this->autocommentTitle
= $title;
1063 $this->autocommentLocal
= $local;
1064 $comment = preg_replace_callback(
1065 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1066 array( $this, 'formatAutocommentsCallback' ),
1068 unset( $this->autocommentTitle
);
1069 unset( $this->autocommentLocal
);
1073 private function formatAutocommentsCallback( $match ) {
1074 $title = $this->autocommentTitle
;
1075 $local = $this->autocommentLocal
;
1084 # Remove links that a user may have manually put in the autosummary
1085 # This could be improved by copying as much of Parser::stripSectionName as desired.
1086 $section = str_replace( '[[:', '', $section );
1087 $section = str_replace( '[[', '', $section );
1088 $section = str_replace( ']]', '', $section );
1090 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1092 $sectionTitle = Title
::newFromText( '#' . $section );
1094 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1095 $title->getDBkey(), $section );
1097 if ( $sectionTitle ) {
1098 $link = $this->link( $sectionTitle,
1099 htmlspecialchars( wfMsgForContent( 'sectionlink' ) ), array(), array(),
1105 $auto = "$link$auto";
1107 # written summary $presep autocomment (summary /* section */)
1108 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1111 # autocomment $postsep written summary (/* section */ summary)
1112 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1114 $auto = '<span class="autocomment">' . $auto . '</span>';
1115 $comment = $pre . $auto . $post;
1120 * Formats wiki links and media links in text; all other wiki formatting
1123 * @todo Fixme: doesn't handle sub-links as in image thumb texts like the main parser
1124 * @param $comment String: text to format links in
1125 * @param $title An optional title object used to links to sections
1126 * @param $local Boolean: whether section links should refer to local page
1129 public function formatLinksInComment( $comment, $title = null, $local = false ) {
1130 $this->commentContextTitle
= $title;
1131 $this->commentLocal
= $local;
1132 $html = preg_replace_callback(
1133 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1134 array( $this, 'formatLinksInCommentCallback' ),
1136 unset( $this->commentContextTitle
);
1137 unset( $this->commentLocal
);
1141 protected function formatLinksInCommentCallback( $match ) {
1144 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1145 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1147 $comment = $match[0];
1149 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1150 if ( strpos( $match[1], '%' ) !== false ) {
1151 $match[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $match[1] ) );
1154 # Handle link renaming [[foo|text]] will show link as "text"
1155 if ( $match[3] != "" ) {
1160 $submatch = array();
1162 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1163 # Media link; trail not supported.
1164 $linkRegexp = '/\[\[(.*?)\]\]/';
1165 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1166 $thelink = $this->makeMediaLinkObj( $title, $text );
1168 # Other kind of link
1169 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1170 $trail = $submatch[1];
1174 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1175 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1176 $match[1] = substr( $match[1], 1 );
1177 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1180 $linkTarget = Linker
::normalizeSubpageLink( $this->commentContextTitle
,
1181 $match[1], $linkText );
1183 $target = Title
::newFromText( $linkTarget );
1185 if ( $target->getText() == '' && $target->getInterwiki() === ''
1186 && !$this->commentLocal
&& $this->commentContextTitle
)
1188 $newTarget = clone ( $this->commentContextTitle
);
1189 $newTarget->setFragment( '#' . $target->getFragment() );
1190 $target = $newTarget;
1192 $thelink = $this->link(
1199 // If the link is still valid, go ahead and replace it in!
1200 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1208 * @param $contextTitle Title
1213 static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1216 # :Foobar -- override special treatment of prefix (images, language links)
1217 # /Foobar -- convert to CurrentPage/Foobar
1218 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1219 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1220 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1222 wfProfileIn( __METHOD__
);
1223 $ret = $target; # default return value is no change
1225 # Some namespaces don't allow subpages,
1226 # so only perform processing if subpages are allowed
1227 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1228 $hash = strpos( $target, '#' );
1229 if ( $hash !== false ) {
1230 $suffix = substr( $target, $hash );
1231 $target = substr( $target, 0, $hash );
1236 $target = trim( $target );
1237 # Look at the first character
1238 if ( $target != '' && $target { 0 } === '/' ) {
1239 # / at end means we don't want the slash to be shown
1241 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1242 if ( $trailingSlashes ) {
1243 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1245 $noslash = substr( $target, 1 );
1248 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1249 if ( $text === '' ) {
1250 $text = $target . $suffix;
1251 } # this might be changed for ugliness reasons
1253 # check for .. subpage backlinks
1255 $nodotdot = $target;
1256 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1258 $nodotdot = substr( $nodotdot, 3 );
1260 if ( $dotdotcount > 0 ) {
1261 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1262 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1263 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1264 # / at the end means don't show full path
1265 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1266 $nodotdot = substr( $nodotdot, 0, -1 );
1267 if ( $text === '' ) {
1268 $text = $nodotdot . $suffix;
1271 $nodotdot = trim( $nodotdot );
1272 if ( $nodotdot != '' ) {
1273 $ret .= '/' . $nodotdot;
1281 wfProfileOut( __METHOD__
);
1286 * Wrap a comment in standard punctuation and formatting if
1287 * it's non-empty, otherwise return empty string.
1289 * @param $comment String
1290 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1291 * @param $local Boolean: whether section links should refer to local page
1295 function commentBlock( $comment, $title = null, $local = false ) {
1296 // '*' used to be the comment inserted by the software way back
1297 // in antiquity in case none was provided, here for backwards
1298 // compatability, acc. to brion -ævar
1299 if ( $comment == '' ||
$comment == '*' ) {
1302 $formatted = $this->formatComment( $comment, $title, $local );
1303 return " <span class=\"comment\">($formatted)</span>";
1308 * Wrap and format the given revision's comment block, if the current
1309 * user is allowed to view it.
1311 * @param $rev Revision object
1312 * @param $local Boolean: whether section links should refer to local page
1313 * @param $isPublic Boolean: show only if all users can see it
1314 * @return String: HTML fragment
1316 function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1317 if ( $rev->getRawComment() == "" ) {
1320 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1321 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1322 } else if ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1323 $block = $this->commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1324 $rev->getTitle(), $local );
1326 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1328 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1329 return " <span class=\"history-deleted\">$block</span>";
1334 public function formatRevisionSize( $size ) {
1336 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1339 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1342 $stxt = htmlspecialchars( $stxt );
1343 return "<span class=\"history-size\">$stxt</span>";
1347 * Add another level to the Table of Contents
1349 function tocIndent() {
1354 * Finish one or more sublevels on the Table of Contents
1356 function tocUnindent( $level ) {
1357 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1361 * parameter level defines if we are on an indentation level
1363 function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1364 $classes = "toclevel-$level";
1365 if ( $sectionIndex !== false )
1366 $classes .= " tocsection-$sectionIndex";
1367 return "\n<li class=\"$classes\"><a href=\"#" .
1368 $anchor . '"><span class="tocnumber">' .
1369 $tocnumber . '</span> <span class="toctext">' .
1370 $tocline . '</span></a>';
1374 * End a Table Of Contents line.
1375 * tocUnindent() will be used instead if we're ending a line below
1378 function tocLineEnd() {
1383 * Wraps the TOC in a table and provides the hide/collapse javascript.
1385 * @param $toc String: html of the Table Of Contents
1386 * @param $lang mixed: Language code for the toc title
1387 * @return String: full html of the TOC
1389 function tocList( $toc, $lang = false ) {
1390 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1392 '<table id="toc" class="toc"><tr><td>'
1393 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1395 . "</ul>\n</td></tr></table>\n";
1399 * Generate a table of contents from a section tree
1402 * @param $tree Return value of ParserOutput::getSections()
1403 * @return String: HTML fragment
1405 public function generateTOC( $tree ) {
1408 foreach ( $tree as $section ) {
1409 if ( $section['toclevel'] > $lastLevel )
1410 $toc .= $this->tocIndent();
1411 else if ( $section['toclevel'] < $lastLevel )
1412 $toc .= $this->tocUnindent(
1413 $lastLevel - $section['toclevel'] );
1415 $toc .= $this->tocLineEnd();
1417 $toc .= $this->tocLine( $section['anchor'],
1418 $section['line'], $section['number'],
1419 $section['toclevel'], $section['index'] );
1420 $lastLevel = $section['toclevel'];
1422 $toc .= $this->tocLineEnd();
1423 return $this->tocList( $toc );
1427 * Create a section edit link. This supersedes editSectionLink() and
1428 * editSectionLinkForOther().
1430 * @param $nt Title The title being linked to (may not be the same as
1431 * $wgTitle, if the section is included from a template)
1432 * @param $section string The designation of the section being pointed to,
1433 * to be included in the link, like "§ion=$section"
1434 * @param $tooltip string The tooltip to use for the link: will be escaped
1435 * and wrapped in the 'editsectionhint' message
1436 * @param $lang string Language code
1437 * @return string HTML to use for edit link
1439 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1440 // HTML generated here should probably have userlangattributes
1441 // added to it for LTR text on RTL pages
1443 if ( !is_null( $tooltip ) ) {
1444 # Bug 25462: undo double-escaping.
1445 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1446 $attribs['title'] = wfMsgReal( 'editsectionhint', array( $tooltip ), true, $lang );
1448 $link = $this->link( $nt, wfMsgExt( 'editsection', array( 'language' => $lang ) ),
1450 array( 'action' => 'edit', 'section' => $section ),
1451 array( 'noclasses', 'known' )
1454 # Run the old hook. This takes up half of the function . . . hopefully
1455 # we can rid of it someday.
1458 $attribs = htmlspecialchars( wfMsgReal( 'editsectionhint', array( $tooltip ), true, $lang ) );
1459 $attribs = " title=\"$attribs\"";
1462 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $link, &$result, $lang ) );
1463 if ( !is_null( $result ) ) {
1464 # For reverse compatibility, add the brackets *after* the hook is
1465 # run, and even add them to hook-provided text. (This is the main
1466 # reason that the EditSectionLink hook is deprecated in favor of
1467 # DoEditSectionLink: it can't change the brackets or the span.)
1468 $result = wfMsgExt( 'editsection-brackets', array( 'escape', 'replaceafter', 'language' => $lang ), $result );
1469 return "<span class=\"editsection\">$result</span>";
1472 # Add the brackets and the span, and *then* run the nice new hook, with
1473 # clean and non-redundant arguments.
1474 $result = wfMsgExt( 'editsection-brackets', array( 'escape', 'replaceafter', 'language' => $lang ), $link );
1475 $result = "<span class=\"editsection\">$result</span>";
1477 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
1482 * Create a headline for content
1484 * @param $level Integer: the level of the headline (1-6)
1485 * @param $attribs String: any attributes for the headline, starting with
1486 * a space and ending with '>'
1487 * This *must* be at least '>' for no attribs
1488 * @param $anchor String: the anchor to give the headline (the bit after the #)
1489 * @param $text String: the text of the header
1490 * @param $link String: HTML to add for the section edit link
1491 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1492 * backward compatibility (false to omit)
1494 * @return String: HTML headline
1496 public function makeHeadline( $level, $attribs, $anchor, $text, $link, $legacyAnchor = false ) {
1497 $ret = "<h$level$attribs"
1499 . " <span class=\"mw-headline\" id=\"$anchor\">$text</span>"
1501 if ( $legacyAnchor !== false ) {
1502 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1508 * Split a link trail, return the "inside" portion and the remainder of the trail
1509 * as a two-element array
1511 static function splitTrail( $trail ) {
1512 static $regex = false;
1513 if ( $regex === false ) {
1515 $regex = $wgContLang->linkTrail();
1518 if ( $trail !== '' ) {
1520 if ( preg_match( $regex, $trail, $m ) ) {
1525 return array( $inside, $trail );
1529 * Generate a rollback link for a given revision. Currently it's the
1530 * caller's responsibility to ensure that the revision is the top one. If
1531 * it's not, of course, the user will get an error message.
1533 * If the calling page is called with the parameter &bot=1, all rollback
1534 * links also get that parameter. It causes the edit itself and the rollback
1535 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1536 * changes, so this allows sysops to combat a busy vandal without bothering
1539 * @param $rev Revision object
1541 function generateRollback( $rev ) {
1542 return '<span class="mw-rollback-link">['
1543 . $this->buildRollbackLink( $rev )
1548 * Build a raw rollback link, useful for collections of "tool" links
1550 * @param $rev Revision object
1551 * @return String: HTML fragment
1553 public function buildRollbackLink( $rev ) {
1554 global $wgRequest, $wgUser;
1555 $title = $rev->getTitle();
1557 'action' => 'rollback',
1558 'from' => $rev->getUserText(),
1559 'token' => $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1561 if ( $wgRequest->getBool( 'bot' ) ) {
1562 $query['bot'] = '1';
1563 $query['hidediff'] = '1'; // bug 15999
1567 wfMsgHtml( 'rollbacklink' ),
1568 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1570 array( 'known', 'noclasses' )
1575 * Returns HTML for the "templates used on this page" list.
1577 * @param $templates Array of templates from Article::getUsedTemplate
1579 * @param $preview Boolean: whether this is for a preview
1580 * @param $section Boolean: whether this is for a section edit
1581 * @return String: HTML output
1583 public function formatTemplates( $templates, $preview = false, $section = false ) {
1584 wfProfileIn( __METHOD__
);
1587 if ( count( $templates ) > 0 ) {
1588 # Do a batch existence check
1589 $batch = new LinkBatch
;
1590 foreach ( $templates as $title ) {
1591 $batch->addObj( $title );
1595 # Construct the HTML
1596 $outText = '<div class="mw-templatesUsedExplanation">';
1598 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1599 } elseif ( $section ) {
1600 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1602 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1604 $outText .= "</div><ul>\n";
1606 usort( $templates, array( 'Title', 'compare' ) );
1607 foreach ( $templates as $titleObj ) {
1608 $r = $titleObj->getRestrictions( 'edit' );
1609 if ( in_array( 'sysop', $r ) ) {
1610 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1611 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1612 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1616 if ( $titleObj->quickUserCan( 'edit' ) ) {
1617 $editLink = $this->link(
1619 wfMsg( 'editlink' ),
1621 array( 'action' => 'edit' )
1624 $editLink = $this->link(
1626 wfMsg( 'viewsourcelink' ),
1628 array( 'action' => 'edit' )
1631 $outText .= '<li>' . $this->link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1633 $outText .= '</ul>';
1635 wfProfileOut( __METHOD__
);
1640 * Returns HTML for the "hidden categories on this page" list.
1642 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1644 * @return String: HTML output
1646 public function formatHiddenCategories( $hiddencats ) {
1648 wfProfileIn( __METHOD__
);
1651 if ( count( $hiddencats ) > 0 ) {
1652 # Construct the HTML
1653 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1654 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1655 $outText .= "</div><ul>\n";
1657 foreach ( $hiddencats as $titleObj ) {
1658 $outText .= '<li>' . $this->link( $titleObj, null, array(), array(), 'known' ) . "</li>\n"; # If it's hidden, it must exist - no need to check with a LinkBatch
1660 $outText .= '</ul>';
1662 wfProfileOut( __METHOD__
);
1667 * Format a size in bytes for output, using an appropriate
1668 * unit (B, KB, MB or GB) according to the magnitude in question
1670 * @param $size Size to format
1673 public function formatSize( $size ) {
1675 return htmlspecialchars( $wgLang->formatSize( $size ) );
1679 * Given the id of an interface element, constructs the appropriate title
1680 * attribute from the system messages. (Note, this is usually the id but
1681 * isn't always, because sometimes the accesskey needs to go on a different
1682 * element than the id, for reverse-compatibility, etc.)
1684 * @param $name String: id of the element, minus prefixes.
1685 * @param $options Mixed: null or the string 'withaccess' to add an access-
1687 * @return String: contents of the title attribute (which you must HTML-
1688 * escape), or false for no title attribute
1690 public function titleAttrib( $name, $options = null ) {
1691 wfProfileIn( __METHOD__
);
1693 $message = wfMessage( "tooltip-$name" );
1695 if ( !$message->exists() ) {
1698 $tooltip = $message->text();
1699 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1700 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1701 # Message equal to '-' means suppress it.
1702 if ( $tooltip == '-' ) {
1707 if ( $options == 'withaccess' ) {
1708 $accesskey = $this->accesskey( $name );
1709 if ( $accesskey !== false ) {
1710 if ( $tooltip === false ||
$tooltip === '' ) {
1711 $tooltip = "[$accesskey]";
1713 $tooltip .= " [$accesskey]";
1718 wfProfileOut( __METHOD__
);
1723 * Given the id of an interface element, constructs the appropriate
1724 * accesskey attribute from the system messages. (Note, this is usually
1725 * the id but isn't always, because sometimes the accesskey needs to go on
1726 * a different element than the id, for reverse-compatibility, etc.)
1728 * @param $name String: id of the element, minus prefixes.
1729 * @return String: contents of the accesskey attribute (which you must HTML-
1730 * escape), or false for no accesskey attribute
1732 public function accesskey( $name ) {
1733 if ( isset( $this->accesskeycache
[$name] ) ) {
1734 return $this->accesskeycache
[$name];
1736 wfProfileIn( __METHOD__
);
1738 $message = wfMessage( "accesskey-$name" );
1740 if ( !$message->exists() ) {
1743 $accesskey = $message->plain();
1744 if ( $accesskey === '' ||
$accesskey === '-' ) {
1745 # FIXME: Per standard MW behavior, a value of '-' means to suppress the
1746 # attribute, but this is broken for accesskey: that might be a useful
1752 wfProfileOut( __METHOD__
);
1753 return $this->accesskeycache
[$name] = $accesskey;
1757 * Creates a (show/hide) link for deleting revisions/log entries
1759 * @param $query Array: query parameters to be passed to link()
1760 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1761 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1763 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1764 * span to allow for customization of appearance with CSS
1766 public function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1767 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1768 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1769 $tag = $restricted ?
'strong' : 'span';
1770 $link = $this->link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1771 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1775 * Creates a dead (show/hide) link for deleting revisions/log entries
1777 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1779 * @return string HTML text wrapped in a span to allow for customization
1780 * of appearance with CSS
1782 public function revDeleteLinkDisabled( $delete = true ) {
1783 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1784 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($text)" );
1787 /* Deprecated methods */
1790 * @deprecated since 1.16 Use link()
1792 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
1793 * it if you already have a title object handy. See makeLinkObj for further documentation.
1795 * @param $title String: the text of the title
1796 * @param $text String: link text
1797 * @param $query String: optional query part
1798 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1799 * be included in the link text. Other characters will be appended after
1800 * the end of the link.
1802 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
1803 wfProfileIn( __METHOD__
);
1804 $nt = Title
::newFromText( $title );
1805 if ( $nt instanceof Title
) {
1806 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
1808 wfDebug( 'Invalid title passed to Linker::makeLink(): "' . $title . "\"\n" );
1809 $result = $text == "" ?
$title : $text;
1812 wfProfileOut( __METHOD__
);
1817 * @deprecated since 1.16 Use link()
1819 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
1820 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
1822 * @param $title String: the text of the title
1823 * @param $text String: link text
1824 * @param $query String: optional query part
1825 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1826 * be included in the link text. Other characters will be appended after
1827 * the end of the link.
1828 * @param $prefix String: Optional prefix
1829 * @param $aprops String: extra attributes to the a-element
1831 function makeKnownLink(
1832 $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = ''
1834 $nt = Title
::newFromText( $title );
1835 if ( $nt instanceof Title
) {
1836 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
1838 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "' . $title . "\"\n" );
1839 return $text == '' ?
$title : $text;
1844 * @deprecated since 1.16 Use link()
1846 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1847 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1849 * @param $title String: The text of the title
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.
1856 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1857 $nt = Title
::newFromText( $title );
1858 if ( $nt instanceof Title
) {
1859 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
1861 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "' . $title . "\"\n" );
1862 return $text == '' ?
$title : $text;
1867 * @deprecated since 1.16 Use link()
1869 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
1870 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
1872 * @param $title String: the text of the title
1873 * @param $text String: link text
1874 * @param $query String: optional query part
1875 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1876 * be included in the link text. Other characters will be appended after
1877 * the end of the link.
1879 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
1880 wfDeprecated( __METHOD__
);
1881 $nt = Title
::newFromText( $title );
1882 if ( $nt instanceof Title
) {
1883 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
1885 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "' . $title . "\"\n" );
1886 return $text == '' ?
$title : $text;
1891 * @deprecated since 1.16 Use link()
1893 * Make a link for a title which may or may not be in the database. If you need to
1894 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1895 * call to this will result in a DB query.
1897 * @param $nt Title: the title object to make the link from, e.g. from
1898 * Title::newFromText.
1899 * @param $text String: link text
1900 * @param $query String: optional query part
1901 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1902 * be included in the link text. Other characters will be appended after
1903 * the end of the link.
1904 * @param $prefix String: optional prefix. As trail, only before instead of after.
1906 function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1907 wfProfileIn( __METHOD__
);
1908 $query = wfCgiToArray( $query );
1909 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1910 if ( $text === '' ) {
1911 $text = $this->linkText( $nt );
1914 $ret = $this->link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1916 wfProfileOut( __METHOD__
);
1921 * @deprecated since 1.16 Use link()
1923 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1924 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1927 * @param $title Title object of target page
1928 * @param $text String: text to replace the title
1929 * @param $query String: link target
1930 * @param $trail String: text after link
1931 * @param $prefix String: text before link text
1932 * @param $aprops String: extra attributes to the a-element
1933 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1934 * @return the a-element
1936 function makeKnownLinkObj(
1937 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
1939 wfProfileIn( __METHOD__
);
1941 if ( $text == '' ) {
1942 $text = $this->linkText( $title );
1944 $attribs = Sanitizer
::mergeAttributes(
1945 Sanitizer
::decodeTagAttributes( $aprops ),
1946 Sanitizer
::decodeTagAttributes( $style )
1948 $query = wfCgiToArray( $query );
1949 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1951 $ret = $this->link( $title, "$prefix$text$inside", $attribs, $query,
1952 array( 'known', 'noclasses' ) ) . $trail;
1954 wfProfileOut( __METHOD__
);
1959 * @deprecated since 1.16 Use link()
1961 * Make a red link to the edit page of a given title.
1963 * @param $title Title object of the target page
1964 * @param $text String: Link text
1965 * @param $query String: Optional query part
1966 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1967 * be included in the link text. Other characters will be appended after
1968 * the end of the link.
1969 * @param $prefix String: Optional prefix
1971 function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
1972 wfProfileIn( __METHOD__
);
1974 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1975 if ( $text === '' ) {
1976 $text = $this->linkText( $title );
1979 $ret = $this->link( $title, "$prefix$text$inside", array(),
1980 wfCgiToArray( $query ), 'broken' ) . $trail;
1982 wfProfileOut( __METHOD__
);
1987 * @deprecated since 1.16 Use link()
1989 * Make a brown link to a short article.
1991 * @param $nt Title object of the target page
1992 * @param $text String: link text
1993 * @param $query String: optional query part
1994 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1995 * be included in the link text. Other characters will be appended after
1996 * the end of the link.
1997 * @param $prefix String: Optional prefix
1999 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
2000 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
2004 * @deprecated since 1.16 Use link()
2006 * Make a coloured link.
2008 * @param $nt Title object of the target page
2009 * @param $colour Integer: colour of the link
2010 * @param $text String: link text
2011 * @param $query String: optional query part
2012 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2013 * be included in the link text. Other characters will be appended after
2014 * the end of the link.
2015 * @param $prefix String: Optional prefix
2017 function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2018 if ( $colour != '' ) {
2019 $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
2023 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2026 /** Obsolete alias */
2027 function makeImage( $url, $alt = '' ) {
2028 wfDeprecated( __METHOD__
);
2029 return $this->makeExternalImage( $url, $alt );
2033 * Creates the HTML source for images
2034 * @deprecated since 1.16 use makeImageLink2
2036 * @param $title Title object
2037 * @param $label String: label text
2038 * @param $alt String: alt text
2039 * @param $align String: horizontal alignment: none, left, center, right)
2040 * @param $handlerParams Array: parameters to be passed to the media handler
2041 * @param $framed Boolean: shows image in original size in a frame
2042 * @param $thumb Boolean: shows image as thumbnail in a frame
2043 * @param $manualthumb String: image name for the manual thumbnail
2044 * @param $valign String: vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
2045 * @param $time String: timestamp of the file, set as false for current
2048 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(),
2049 $framed = false, $thumb = false, $manualthumb = '', $valign = '', $time = false )
2051 $frameParams = array( 'alt' => $alt, 'caption' => $label );
2053 $frameParams['align'] = $align;
2056 $frameParams['framed'] = true;
2059 $frameParams['thumbnail'] = true;
2061 if ( $manualthumb ) {
2062 $frameParams['manualthumb'] = $manualthumb;
2065 $frameParams['valign'] = $valign;
2067 $file = wfFindFile( $title, array( 'time' => $time ) );
2068 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
2071 /** @deprecated use Linker::makeMediaLinkObj() */
2072 function makeMediaLink( $name, $unused = '', $text = '', $time = false ) {
2073 $nt = Title
::makeTitleSafe( NS_FILE
, $name );
2074 return $this->makeMediaLinkObj( $nt, $text, $time );
2078 * Returns the attributes for the tooltip and access key.
2080 public function tooltipAndAccesskeyAttribs( $name ) {
2081 global $wgEnableTooltipsAndAccesskeys;
2082 if ( !$wgEnableTooltipsAndAccesskeys )
2084 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2085 # no attribute" instead of "output '' as value for attribute", this
2086 # would be three lines.
2088 'title' => $this->titleAttrib( $name, 'withaccess' ),
2089 'accesskey' => $this->accesskey( $name )
2091 if ( $attribs['title'] === false ) {
2092 unset( $attribs['title'] );
2094 if ( $attribs['accesskey'] === false ) {
2095 unset( $attribs['accesskey'] );
2101 * @deprecated since 1.14
2102 * Returns raw bits of HTML, use titleAttrib() and accesskey()
2104 public function tooltipAndAccesskey( $name ) {
2105 return Xml
::expandAttributes( $this->tooltipAndAccesskeyAttribs( $name ) );
2109 * @deprecated since 1.14
2110 * Returns raw bits of HTML, use titleAttrib()
2112 public function tooltip( $name, $options = null ) {
2113 global $wgEnableTooltipsAndAccesskeys;
2114 if ( !$wgEnableTooltipsAndAccesskeys )
2116 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2117 # no attribute" instead of "output '' as value for attribute", this
2118 # would be two lines.
2119 $tooltip = $this->titleAttrib( $name, $options );
2120 if ( $tooltip === false ) {
2123 return Xml
::expandAttributes( array(
2124 'title' => $this->titleAttrib( $name, $options )