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: time image was created
798 * @return String: HTML
800 * @todo Handle invalid or missing images better.
802 public function makeMediaLinkObj( $title, $text = '', $time = false ) {
803 if ( is_null( $title ) ) {
804 # # # HOTFIX. Instead of breaking, return empty string.
807 $img = wfFindFile( $title, array( 'time' => $time ) );
809 $url = $img->getURL();
812 $url = $this->getUploadUrl( $title );
815 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES
);
819 $u = htmlspecialchars( $url );
820 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
825 * Make a link to a special page given its name and, optionally,
826 * a message key from the link text.
827 * Usage example: $skin->specialLink( 'recentchanges' )
829 function specialLink( $name, $key = '' ) {
830 if ( $key == '' ) { $key = strtolower( $name ); }
832 return $this->linkKnown( SpecialPage
::getTitleFor( $name ) , wfMsg( $key ) );
836 * Make an external link
837 * @param $url String: URL to link to
838 * @param $text String: text of link
839 * @param $escape Boolean: do we escape the link text?
840 * @param $linktype String: type of external link. Gets added to the classes
841 * @param $attribs Array of extra attributes to <a>
843 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
845 if ( isset($linktype) && $linktype ) {
846 $class .= " $linktype";
848 if ( isset($attribs['class']) && $attribs['class'] ) {
849 $class .= " {$attribs['class']}";
851 $attribs['class'] = $class;
854 $text = htmlspecialchars( $text );
857 $success = wfRunHooks( 'LinkerMakeExternalLink',
858 array( &$url, &$text, &$link, &$attribs, $linktype ) );
860 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
863 $attribs['href'] = $url;
864 return Html
::rawElement( 'a', $attribs, $text );
868 * Make user link (or user contributions for unregistered users)
869 * @param $userId Integer: user id in database.
870 * @param $userText String: user name in database
871 * @return String: HTML fragment
874 function userLink( $userId, $userText ) {
875 if ( $userId == 0 ) {
876 $page = SpecialPage
::getTitleFor( 'Contributions', $userText );
878 $page = Title
::makeTitle( NS_USER
, $userText );
880 return $this->link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
884 * Generate standard user tool links (talk, contributions, block link, etc.)
886 * @param $userId Integer: user identifier
887 * @param $userText String: user name or IP address
888 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
889 * red if the user has no edits?
890 * @param $flags Integer: customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
891 * @param $edits Integer: user edit count (optional, for performance)
892 * @return String: HTML fragment
894 public function userToolLinks(
895 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
897 global $wgUser, $wgDisableAnonTalk, $wgLang;
898 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
899 $blockable = !$flags & self
::TOOL_LINKS_NOBLOCK
;
903 $items[] = $this->userTalkLink( $userId, $userText );
906 // check if the user has an edit
908 if ( $redContribsWhenNoEdits ) {
909 $count = !is_null( $edits ) ?
$edits : User
::edits( $userId );
911 $attribs['class'] = 'new';
914 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
916 $items[] = $this->link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
918 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
919 $items[] = $this->blockLink( $userId, $userText );
923 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
930 * Alias for userToolLinks( $userId, $userText, true );
931 * @param $userId Integer: user identifier
932 * @param $userText String: user name or IP address
933 * @param $edits Integer: user edit count (optional, for performance)
935 public function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
936 return $this->userToolLinks( $userId, $userText, true, 0, $edits );
941 * @param $userId Integer: user id in database.
942 * @param $userText String: user name in database.
943 * @return String: HTML fragment with user talk link
946 function userTalkLink( $userId, $userText ) {
947 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
948 $userTalkLink = $this->link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
949 return $userTalkLink;
953 * @param $userId Integer: userid
954 * @param $userText String: user name in database.
955 * @return String: HTML fragment with block link
958 function blockLink( $userId, $userText ) {
959 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
960 $blockLink = $this->link( $blockPage, wfMsgHtml( 'blocklink' ) );
965 * Generate a user link if the current user is allowed to view it
966 * @param $rev Revision object.
967 * @param $isPublic Boolean: show only if all users can see it
968 * @return String: HTML fragment
970 function revUserLink( $rev, $isPublic = false ) {
971 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
972 $link = wfMsgHtml( 'rev-deleted-user' );
973 } else if ( $rev->userCan( Revision
::DELETED_USER
) ) {
974 $link = $this->userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
975 $rev->getUserText( Revision
::FOR_THIS_USER
) );
977 $link = wfMsgHtml( 'rev-deleted-user' );
979 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
980 return '<span class="history-deleted">' . $link . '</span>';
986 * Generate a user tool link cluster if the current user is allowed to view it
987 * @param $rev Revision object.
988 * @param $isPublic Boolean: show only if all users can see it
989 * @return string HTML
991 function revUserTools( $rev, $isPublic = false ) {
992 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
993 $link = wfMsgHtml( 'rev-deleted-user' );
994 } else if ( $rev->userCan( Revision
::DELETED_USER
) ) {
995 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
996 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
997 $link = $this->userLink( $userId, $userText ) .
998 ' ' . $this->userToolLinks( $userId, $userText );
1000 $link = wfMsgHtml( 'rev-deleted-user' );
1002 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1003 return ' <span class="history-deleted">' . $link . '</span>';
1009 * This function is called by all recent changes variants, by the page history,
1010 * and by the user contributions list. It is responsible for formatting edit
1011 * comments. It escapes any HTML in the comment, but adds some CSS to format
1012 * auto-generated comments (from section editing) and formats [[wikilinks]].
1014 * @author Erik Moeller <moeller@scireview.de>
1016 * Note: there's not always a title to pass to this function.
1017 * Since you can't set a default parameter for a reference, I've turned it
1018 * temporarily to a value pass. Should be adjusted further. --brion
1020 * @param $comment String
1021 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1022 * @param $local Boolean: whether section links should refer to local page
1024 function formatComment( $comment, $title = null, $local = false ) {
1025 wfProfileIn( __METHOD__
);
1027 # Sanitize text a bit:
1028 $comment = str_replace( "\n", " ", $comment );
1029 # Allow HTML entities (for bug 13815)
1030 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1032 # Render autocomments and make links:
1033 $comment = $this->formatAutocomments( $comment, $title, $local );
1034 $comment = $this->formatLinksInComment( $comment, $title, $local );
1036 wfProfileOut( __METHOD__
);
1041 * The pattern for autogen comments is / * foo * /, which makes for
1043 * We look for all comments, match any text before and after the comment,
1044 * add a separator where needed and format the comment itself with CSS
1045 * Called by Linker::formatComment.
1047 * @param $comment String: comment text
1048 * @param $title An optional title object used to links to sections
1049 * @param $local Boolean: whether section links should refer to local page
1050 * @return String: formatted comment
1052 private function formatAutocomments( $comment, $title = null, $local = false ) {
1054 $this->autocommentTitle
= $title;
1055 $this->autocommentLocal
= $local;
1056 $comment = preg_replace_callback(
1057 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1058 array( $this, 'formatAutocommentsCallback' ),
1060 unset( $this->autocommentTitle
);
1061 unset( $this->autocommentLocal
);
1065 private function formatAutocommentsCallback( $match ) {
1066 $title = $this->autocommentTitle
;
1067 $local = $this->autocommentLocal
;
1076 # Remove links that a user may have manually put in the autosummary
1077 # This could be improved by copying as much of Parser::stripSectionName as desired.
1078 $section = str_replace( '[[:', '', $section );
1079 $section = str_replace( '[[', '', $section );
1080 $section = str_replace( ']]', '', $section );
1082 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1084 $sectionTitle = Title
::newFromText( '#' . $section );
1086 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1087 $title->getDBkey(), $section );
1089 if ( $sectionTitle ) {
1090 $link = $this->link( $sectionTitle,
1091 htmlspecialchars( wfMsgForContent( 'sectionlink' ) ), array(), array(),
1097 $auto = "$link$auto";
1099 # written summary $presep autocomment (summary /* section */)
1100 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1103 # autocomment $postsep written summary (/* section */ summary)
1104 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1106 $auto = '<span class="autocomment">' . $auto . '</span>';
1107 $comment = $pre . $auto . $post;
1112 * Formats wiki links and media links in text; all other wiki formatting
1115 * @todo Fixme: doesn't handle sub-links as in image thumb texts like the main parser
1116 * @param $comment String: text to format links in
1117 * @param $title An optional title object used to links to sections
1118 * @param $local Boolean: whether section links should refer to local page
1121 public function formatLinksInComment( $comment, $title = null, $local = false ) {
1122 $this->commentContextTitle
= $title;
1123 $this->commentLocal
= $local;
1124 $html = preg_replace_callback(
1125 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1126 array( $this, 'formatLinksInCommentCallback' ),
1128 unset( $this->commentContextTitle
);
1129 unset( $this->commentLocal
);
1133 protected function formatLinksInCommentCallback( $match ) {
1136 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1137 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1139 $comment = $match[0];
1141 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1142 if ( strpos( $match[1], '%' ) !== false ) {
1143 $match[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $match[1] ) );
1146 # Handle link renaming [[foo|text]] will show link as "text"
1147 if ( $match[3] != "" ) {
1152 $submatch = array();
1154 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1155 # Media link; trail not supported.
1156 $linkRegexp = '/\[\[(.*?)\]\]/';
1157 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1158 $thelink = $this->makeMediaLinkObj( $title, $text );
1160 # Other kind of link
1161 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1162 $trail = $submatch[1];
1166 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1167 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1168 $match[1] = substr( $match[1], 1 );
1169 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1172 $linkTarget = Linker
::normalizeSubpageLink( $this->commentContextTitle
,
1173 $match[1], $linkText );
1175 $target = Title
::newFromText( $linkTarget );
1177 if ( $target->getText() == '' && $target->getInterwiki() === ''
1178 && !$this->commentLocal
&& $this->commentContextTitle
)
1180 $newTarget = clone ( $this->commentContextTitle
);
1181 $newTarget->setFragment( '#' . $target->getFragment() );
1182 $target = $newTarget;
1184 $thelink = $this->link(
1191 // If the link is still valid, go ahead and replace it in!
1192 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1200 * @param $contextTitle Title
1205 static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1208 # :Foobar -- override special treatment of prefix (images, language links)
1209 # /Foobar -- convert to CurrentPage/Foobar
1210 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1211 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1212 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1214 wfProfileIn( __METHOD__
);
1215 $ret = $target; # default return value is no change
1217 # Some namespaces don't allow subpages,
1218 # so only perform processing if subpages are allowed
1219 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1220 $hash = strpos( $target, '#' );
1221 if ( $hash !== false ) {
1222 $suffix = substr( $target, $hash );
1223 $target = substr( $target, 0, $hash );
1228 $target = trim( $target );
1229 # Look at the first character
1230 if ( $target != '' && $target { 0 } === '/' ) {
1231 # / at end means we don't want the slash to be shown
1233 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1234 if ( $trailingSlashes ) {
1235 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1237 $noslash = substr( $target, 1 );
1240 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1241 if ( $text === '' ) {
1242 $text = $target . $suffix;
1243 } # this might be changed for ugliness reasons
1245 # check for .. subpage backlinks
1247 $nodotdot = $target;
1248 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1250 $nodotdot = substr( $nodotdot, 3 );
1252 if ( $dotdotcount > 0 ) {
1253 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1254 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1255 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1256 # / at the end means don't show full path
1257 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1258 $nodotdot = substr( $nodotdot, 0, -1 );
1259 if ( $text === '' ) {
1260 $text = $nodotdot . $suffix;
1263 $nodotdot = trim( $nodotdot );
1264 if ( $nodotdot != '' ) {
1265 $ret .= '/' . $nodotdot;
1273 wfProfileOut( __METHOD__
);
1278 * Wrap a comment in standard punctuation and formatting if
1279 * it's non-empty, otherwise return empty string.
1281 * @param $comment String
1282 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1283 * @param $local Boolean: whether section links should refer to local page
1287 function commentBlock( $comment, $title = null, $local = false ) {
1288 // '*' used to be the comment inserted by the software way back
1289 // in antiquity in case none was provided, here for backwards
1290 // compatability, acc. to brion -ævar
1291 if ( $comment == '' ||
$comment == '*' ) {
1294 $formatted = $this->formatComment( $comment, $title, $local );
1295 return " <span class=\"comment\">($formatted)</span>";
1300 * Wrap and format the given revision's comment block, if the current
1301 * user is allowed to view it.
1303 * @param $rev Revision object
1304 * @param $local Boolean: whether section links should refer to local page
1305 * @param $isPublic Boolean: show only if all users can see it
1306 * @return String: HTML fragment
1308 function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1309 if ( $rev->getRawComment() == "" ) {
1312 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1313 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1314 } else if ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1315 $block = $this->commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1316 $rev->getTitle(), $local );
1318 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1320 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1321 return " <span class=\"history-deleted\">$block</span>";
1326 public function formatRevisionSize( $size ) {
1328 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1331 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1334 $stxt = htmlspecialchars( $stxt );
1335 return "<span class=\"history-size\">$stxt</span>";
1339 * Add another level to the Table of Contents
1341 function tocIndent() {
1346 * Finish one or more sublevels on the Table of Contents
1348 function tocUnindent( $level ) {
1349 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1353 * parameter level defines if we are on an indentation level
1355 function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1356 $classes = "toclevel-$level";
1357 if ( $sectionIndex !== false )
1358 $classes .= " tocsection-$sectionIndex";
1359 return "\n<li class=\"$classes\"><a href=\"#" .
1360 $anchor . '"><span class="tocnumber">' .
1361 $tocnumber . '</span> <span class="toctext">' .
1362 $tocline . '</span></a>';
1366 * End a Table Of Contents line.
1367 * tocUnindent() will be used instead if we're ending a line below
1370 function tocLineEnd() {
1375 * Wraps the TOC in a table and provides the hide/collapse javascript.
1377 * @param $toc String: html of the Table Of Contents
1378 * @param $lang mixed: Language code for the toc title
1379 * @return String: full html of the TOC
1381 function tocList( $toc, $lang = false ) {
1382 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1384 '<table id="toc" class="toc"><tr><td>'
1385 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1387 . "</ul>\n</td></tr></table>\n";
1391 * Generate a table of contents from a section tree
1394 * @param $tree Return value of ParserOutput::getSections()
1395 * @return String: HTML fragment
1397 public function generateTOC( $tree ) {
1400 foreach ( $tree as $section ) {
1401 if ( $section['toclevel'] > $lastLevel )
1402 $toc .= $this->tocIndent();
1403 else if ( $section['toclevel'] < $lastLevel )
1404 $toc .= $this->tocUnindent(
1405 $lastLevel - $section['toclevel'] );
1407 $toc .= $this->tocLineEnd();
1409 $toc .= $this->tocLine( $section['anchor'],
1410 $section['line'], $section['number'],
1411 $section['toclevel'], $section['index'] );
1412 $lastLevel = $section['toclevel'];
1414 $toc .= $this->tocLineEnd();
1415 return $this->tocList( $toc );
1419 * Create a section edit link. This supersedes editSectionLink() and
1420 * editSectionLinkForOther().
1422 * @param $nt Title The title being linked to (may not be the same as
1423 * $wgTitle, if the section is included from a template)
1424 * @param $section string The designation of the section being pointed to,
1425 * to be included in the link, like "§ion=$section"
1426 * @param $tooltip string The tooltip to use for the link: will be escaped
1427 * and wrapped in the 'editsectionhint' message
1428 * @param $lang string Language code
1429 * @return string HTML to use for edit link
1431 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1432 // HTML generated here should probably have userlangattributes
1433 // added to it for LTR text on RTL pages
1435 if ( !is_null( $tooltip ) ) {
1436 # Bug 25462: undo double-escaping.
1437 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1438 $attribs['title'] = wfMsgReal( 'editsectionhint', array( $tooltip ), true, $lang );
1440 $link = $this->link( $nt, wfMsgExt( 'editsection', array( 'language' => $lang ) ),
1442 array( 'action' => 'edit', 'section' => $section ),
1443 array( 'noclasses', 'known' )
1446 # Run the old hook. This takes up half of the function . . . hopefully
1447 # we can rid of it someday.
1450 $attribs = htmlspecialchars( wfMsgReal( 'editsectionhint', array( $tooltip ), true, $lang ) );
1451 $attribs = " title=\"$attribs\"";
1454 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $link, &$result, $lang ) );
1455 if ( !is_null( $result ) ) {
1456 # For reverse compatibility, add the brackets *after* the hook is
1457 # run, and even add them to hook-provided text. (This is the main
1458 # reason that the EditSectionLink hook is deprecated in favor of
1459 # DoEditSectionLink: it can't change the brackets or the span.)
1460 $result = wfMsgExt( 'editsection-brackets', array( 'escape', 'replaceafter', 'language' => $lang ), $result );
1461 return "<span class=\"editsection\">$result</span>";
1464 # Add the brackets and the span, and *then* run the nice new hook, with
1465 # clean and non-redundant arguments.
1466 $result = wfMsgExt( 'editsection-brackets', array( 'escape', 'replaceafter', 'language' => $lang ), $link );
1467 $result = "<span class=\"editsection\">$result</span>";
1469 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
1474 * Create a headline for content
1476 * @param $level Integer: the level of the headline (1-6)
1477 * @param $attribs String: any attributes for the headline, starting with
1478 * a space and ending with '>'
1479 * This *must* be at least '>' for no attribs
1480 * @param $anchor String: the anchor to give the headline (the bit after the #)
1481 * @param $text String: the text of the header
1482 * @param $link String: HTML to add for the section edit link
1483 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1484 * backward compatibility (false to omit)
1486 * @return String: HTML headline
1488 public function makeHeadline( $level, $attribs, $anchor, $text, $link, $legacyAnchor = false ) {
1489 $ret = "<h$level$attribs"
1491 . " <span class=\"mw-headline\" id=\"$anchor\">$text</span>"
1493 if ( $legacyAnchor !== false ) {
1494 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1500 * Split a link trail, return the "inside" portion and the remainder of the trail
1501 * as a two-element array
1503 static function splitTrail( $trail ) {
1504 static $regex = false;
1505 if ( $regex === false ) {
1507 $regex = $wgContLang->linkTrail();
1510 if ( $trail !== '' ) {
1512 if ( preg_match( $regex, $trail, $m ) ) {
1517 return array( $inside, $trail );
1521 * Generate a rollback link for a given revision. Currently it's the
1522 * caller's responsibility to ensure that the revision is the top one. If
1523 * it's not, of course, the user will get an error message.
1525 * If the calling page is called with the parameter &bot=1, all rollback
1526 * links also get that parameter. It causes the edit itself and the rollback
1527 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1528 * changes, so this allows sysops to combat a busy vandal without bothering
1531 * @param $rev Revision object
1533 function generateRollback( $rev ) {
1534 return '<span class="mw-rollback-link">['
1535 . $this->buildRollbackLink( $rev )
1540 * Build a raw rollback link, useful for collections of "tool" links
1542 * @param $rev Revision object
1543 * @return String: HTML fragment
1545 public function buildRollbackLink( $rev ) {
1546 global $wgRequest, $wgUser;
1547 $title = $rev->getTitle();
1549 'action' => 'rollback',
1550 'from' => $rev->getUserText(),
1551 'token' => $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1553 if ( $wgRequest->getBool( 'bot' ) ) {
1554 $query['bot'] = '1';
1555 $query['hidediff'] = '1'; // bug 15999
1559 wfMsgHtml( 'rollbacklink' ),
1560 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1562 array( 'known', 'noclasses' )
1567 * Returns HTML for the "templates used on this page" list.
1569 * @param $templates Array of templates from Article::getUsedTemplate
1571 * @param $preview Boolean: whether this is for a preview
1572 * @param $section Boolean: whether this is for a section edit
1573 * @return String: HTML output
1575 public function formatTemplates( $templates, $preview = false, $section = false ) {
1576 wfProfileIn( __METHOD__
);
1579 if ( count( $templates ) > 0 ) {
1580 # Do a batch existence check
1581 $batch = new LinkBatch
;
1582 foreach ( $templates as $title ) {
1583 $batch->addObj( $title );
1587 # Construct the HTML
1588 $outText = '<div class="mw-templatesUsedExplanation">';
1590 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1591 } elseif ( $section ) {
1592 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1594 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1596 $outText .= "</div><ul>\n";
1598 usort( $templates, array( 'Title', 'compare' ) );
1599 foreach ( $templates as $titleObj ) {
1600 $r = $titleObj->getRestrictions( 'edit' );
1601 if ( in_array( 'sysop', $r ) ) {
1602 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1603 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1604 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1608 if ( $titleObj->quickUserCan( 'edit' ) ) {
1609 $editLink = $this->link(
1611 wfMsg( 'editlink' ),
1613 array( 'action' => 'edit' )
1616 $editLink = $this->link(
1618 wfMsg( 'viewsourcelink' ),
1620 array( 'action' => 'edit' )
1623 $outText .= '<li>' . $this->link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1625 $outText .= '</ul>';
1627 wfProfileOut( __METHOD__
);
1632 * Returns HTML for the "hidden categories on this page" list.
1634 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1636 * @return String: HTML output
1638 public function formatHiddenCategories( $hiddencats ) {
1640 wfProfileIn( __METHOD__
);
1643 if ( count( $hiddencats ) > 0 ) {
1644 # Construct the HTML
1645 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1646 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1647 $outText .= "</div><ul>\n";
1649 foreach ( $hiddencats as $titleObj ) {
1650 $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
1652 $outText .= '</ul>';
1654 wfProfileOut( __METHOD__
);
1659 * Format a size in bytes for output, using an appropriate
1660 * unit (B, KB, MB or GB) according to the magnitude in question
1662 * @param $size Size to format
1665 public function formatSize( $size ) {
1667 return htmlspecialchars( $wgLang->formatSize( $size ) );
1671 * Given the id of an interface element, constructs the appropriate title
1672 * attribute from the system messages. (Note, this is usually the id but
1673 * isn't always, because sometimes the accesskey needs to go on a different
1674 * element than the id, for reverse-compatibility, etc.)
1676 * @param $name String: id of the element, minus prefixes.
1677 * @param $options Mixed: null or the string 'withaccess' to add an access-
1679 * @return String: contents of the title attribute (which you must HTML-
1680 * escape), or false for no title attribute
1682 public function titleAttrib( $name, $options = null ) {
1683 wfProfileIn( __METHOD__
);
1685 $message = wfMessage( "tooltip-$name" );
1687 if ( !$message->exists() ) {
1690 $tooltip = $message->text();
1691 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1692 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1693 # Message equal to '-' means suppress it.
1694 if ( $tooltip == '-' ) {
1699 if ( $options == 'withaccess' ) {
1700 $accesskey = $this->accesskey( $name );
1701 if ( $accesskey !== false ) {
1702 if ( $tooltip === false ||
$tooltip === '' ) {
1703 $tooltip = "[$accesskey]";
1705 $tooltip .= " [$accesskey]";
1710 wfProfileOut( __METHOD__
);
1715 * Given the id of an interface element, constructs the appropriate
1716 * accesskey attribute from the system messages. (Note, this is usually
1717 * the id but isn't always, because sometimes the accesskey needs to go on
1718 * a different element than the id, for reverse-compatibility, etc.)
1720 * @param $name String: id of the element, minus prefixes.
1721 * @return String: contents of the accesskey attribute (which you must HTML-
1722 * escape), or false for no accesskey attribute
1724 public function accesskey( $name ) {
1725 if ( isset( $this->accesskeycache
[$name] ) ) {
1726 return $this->accesskeycache
[$name];
1728 wfProfileIn( __METHOD__
);
1730 $message = wfMessage( "accesskey-$name" );
1732 if ( !$message->exists() ) {
1735 $accesskey = $message->plain();
1736 if ( $accesskey === '' ||
$accesskey === '-' ) {
1737 # FIXME: Per standard MW behavior, a value of '-' means to suppress the
1738 # attribute, but this is broken for accesskey: that might be a useful
1744 wfProfileOut( __METHOD__
);
1745 return $this->accesskeycache
[$name] = $accesskey;
1749 * Creates a (show/hide) link for deleting revisions/log entries
1751 * @param $query Array: query parameters to be passed to link()
1752 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1753 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1755 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1756 * span to allow for customization of appearance with CSS
1758 public function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1759 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1760 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1761 $tag = $restricted ?
'strong' : 'span';
1762 $link = $this->link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1763 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1767 * Creates a dead (show/hide) link for deleting revisions/log entries
1769 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1771 * @return string HTML text wrapped in a span to allow for customization
1772 * of appearance with CSS
1774 public function revDeleteLinkDisabled( $delete = true ) {
1775 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1776 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($text)" );
1779 /* Deprecated methods */
1782 * @deprecated since 1.16 Use link()
1784 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
1785 * it if you already have a title object handy. See makeLinkObj for further documentation.
1787 * @param $title String: the text of the title
1788 * @param $text String: link text
1789 * @param $query String: optional query part
1790 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1791 * be included in the link text. Other characters will be appended after
1792 * the end of the link.
1794 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
1795 wfProfileIn( __METHOD__
);
1796 $nt = Title
::newFromText( $title );
1797 if ( $nt instanceof Title
) {
1798 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
1800 wfDebug( 'Invalid title passed to Linker::makeLink(): "' . $title . "\"\n" );
1801 $result = $text == "" ?
$title : $text;
1804 wfProfileOut( __METHOD__
);
1809 * @deprecated since 1.16 Use link()
1811 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
1812 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
1814 * @param $title String: the text of the title
1815 * @param $text String: link text
1816 * @param $query String: optional query part
1817 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1818 * be included in the link text. Other characters will be appended after
1819 * the end of the link.
1820 * @param $prefix String: Optional prefix
1821 * @param $aprops String: extra attributes to the a-element
1823 function makeKnownLink(
1824 $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = ''
1826 $nt = Title
::newFromText( $title );
1827 if ( $nt instanceof Title
) {
1828 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
1830 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "' . $title . "\"\n" );
1831 return $text == '' ?
$title : $text;
1836 * @deprecated since 1.16 Use link()
1838 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1839 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1841 * @param $title String: The text of the title
1842 * @param $text String: Link text
1843 * @param $query String: Optional query part
1844 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1845 * be included in the link text. Other characters will be appended after
1846 * the end of the link.
1848 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1849 $nt = Title
::newFromText( $title );
1850 if ( $nt instanceof Title
) {
1851 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
1853 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "' . $title . "\"\n" );
1854 return $text == '' ?
$title : $text;
1859 * @deprecated since 1.16 Use link()
1861 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
1862 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
1864 * @param $title String: the text of the title
1865 * @param $text String: link text
1866 * @param $query String: optional query part
1867 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1868 * be included in the link text. Other characters will be appended after
1869 * the end of the link.
1871 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
1872 wfDeprecated( __METHOD__
);
1873 $nt = Title
::newFromText( $title );
1874 if ( $nt instanceof Title
) {
1875 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
1877 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "' . $title . "\"\n" );
1878 return $text == '' ?
$title : $text;
1883 * @deprecated since 1.16 Use link()
1885 * Make a link for a title which may or may not be in the database. If you need to
1886 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1887 * call to this will result in a DB query.
1889 * @param $nt Title: the title object to make the link from, e.g. from
1890 * Title::newFromText.
1891 * @param $text String: link text
1892 * @param $query String: optional query part
1893 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1894 * be included in the link text. Other characters will be appended after
1895 * the end of the link.
1896 * @param $prefix String: optional prefix. As trail, only before instead of after.
1898 function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1899 wfProfileIn( __METHOD__
);
1900 $query = wfCgiToArray( $query );
1901 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1902 if ( $text === '' ) {
1903 $text = $this->linkText( $nt );
1906 $ret = $this->link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1908 wfProfileOut( __METHOD__
);
1913 * @deprecated since 1.16 Use link()
1915 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1916 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1919 * @param $title Title object of target page
1920 * @param $text String: text to replace the title
1921 * @param $query String: link target
1922 * @param $trail String: text after link
1923 * @param $prefix String: text before link text
1924 * @param $aprops String: extra attributes to the a-element
1925 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1926 * @return the a-element
1928 function makeKnownLinkObj(
1929 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
1931 wfProfileIn( __METHOD__
);
1933 if ( $text == '' ) {
1934 $text = $this->linkText( $title );
1936 $attribs = Sanitizer
::mergeAttributes(
1937 Sanitizer
::decodeTagAttributes( $aprops ),
1938 Sanitizer
::decodeTagAttributes( $style )
1940 $query = wfCgiToArray( $query );
1941 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1943 $ret = $this->link( $title, "$prefix$text$inside", $attribs, $query,
1944 array( 'known', 'noclasses' ) ) . $trail;
1946 wfProfileOut( __METHOD__
);
1951 * @deprecated since 1.16 Use link()
1953 * Make a red link to the edit page of a given title.
1955 * @param $title Title object of the target page
1956 * @param $text String: Link text
1957 * @param $query String: Optional query part
1958 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1959 * be included in the link text. Other characters will be appended after
1960 * the end of the link.
1961 * @param $prefix String: Optional prefix
1963 function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
1964 wfProfileIn( __METHOD__
);
1966 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1967 if ( $text === '' ) {
1968 $text = $this->linkText( $title );
1971 $ret = $this->link( $title, "$prefix$text$inside", array(),
1972 wfCgiToArray( $query ), 'broken' ) . $trail;
1974 wfProfileOut( __METHOD__
);
1979 * @deprecated since 1.16 Use link()
1981 * Make a brown link to a short article.
1983 * @param $nt Title object of the target page
1984 * @param $text String: link text
1985 * @param $query String: optional query part
1986 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1987 * be included in the link text. Other characters will be appended after
1988 * the end of the link.
1989 * @param $prefix String: Optional prefix
1991 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1992 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
1996 * @deprecated since 1.16 Use link()
1998 * Make a coloured link.
2000 * @param $nt Title object of the target page
2001 * @param $colour Integer: colour of the link
2002 * @param $text String: link text
2003 * @param $query String: optional query part
2004 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2005 * be included in the link text. Other characters will be appended after
2006 * the end of the link.
2007 * @param $prefix String: Optional prefix
2009 function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2010 if ( $colour != '' ) {
2011 $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
2015 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2018 /** Obsolete alias */
2019 function makeImage( $url, $alt = '' ) {
2020 wfDeprecated( __METHOD__
);
2021 return $this->makeExternalImage( $url, $alt );
2025 * Creates the HTML source for images
2026 * @deprecated since 1.16 use makeImageLink2
2028 * @param $title Title object
2029 * @param $label String: label text
2030 * @param $alt String: alt text
2031 * @param $align String: horizontal alignment: none, left, center, right)
2032 * @param $handlerParams Array: parameters to be passed to the media handler
2033 * @param $framed Boolean: shows image in original size in a frame
2034 * @param $thumb Boolean: shows image as thumbnail in a frame
2035 * @param $manualthumb String: image name for the manual thumbnail
2036 * @param $valign String: vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
2037 * @param $time String: timestamp of the file, set as false for current
2040 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(),
2041 $framed = false, $thumb = false, $manualthumb = '', $valign = '', $time = false )
2043 $frameParams = array( 'alt' => $alt, 'caption' => $label );
2045 $frameParams['align'] = $align;
2048 $frameParams['framed'] = true;
2051 $frameParams['thumbnail'] = true;
2053 if ( $manualthumb ) {
2054 $frameParams['manualthumb'] = $manualthumb;
2057 $frameParams['valign'] = $valign;
2059 $file = wfFindFile( $title, array( 'time' => $time ) );
2060 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
2063 /** @deprecated use Linker::makeMediaLinkObj() */
2064 function makeMediaLink( $name, $unused = '', $text = '', $time = false ) {
2065 $nt = Title
::makeTitleSafe( NS_FILE
, $name );
2066 return $this->makeMediaLinkObj( $nt, $text, $time );
2070 * Returns the attributes for the tooltip and access key.
2072 public function tooltipAndAccesskeyAttribs( $name ) {
2073 global $wgEnableTooltipsAndAccesskeys;
2074 if ( !$wgEnableTooltipsAndAccesskeys )
2076 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2077 # no attribute" instead of "output '' as value for attribute", this
2078 # would be three lines.
2080 'title' => $this->titleAttrib( $name, 'withaccess' ),
2081 'accesskey' => $this->accesskey( $name )
2083 if ( $attribs['title'] === false ) {
2084 unset( $attribs['title'] );
2086 if ( $attribs['accesskey'] === false ) {
2087 unset( $attribs['accesskey'] );
2093 * @deprecated since 1.14
2094 * Returns raw bits of HTML, use titleAttrib() and accesskey()
2096 public function tooltipAndAccesskey( $name ) {
2097 return Xml
::expandAttributes( $this->tooltipAndAccesskeyAttribs( $name ) );
2101 * @deprecated since 1.14
2102 * Returns raw bits of HTML, use titleAttrib()
2104 public function tooltip( $name, $options = null ) {
2105 global $wgEnableTooltipsAndAccesskeys;
2106 if ( !$wgEnableTooltipsAndAccesskeys )
2108 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2109 # no attribute" instead of "output '' as value for attribute", this
2110 # would be two lines.
2111 $tooltip = $this->titleAttrib( $name, $options );
2112 if ( $tooltip === false ) {
2115 return Xml
::expandAttributes( array(
2116 'title' => $this->titleAttrib( $name, $options )