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( $target, $text = null, $customAttribs = array(), $query = array(), $options = array() ) {
162 wfProfileIn( __METHOD__
);
163 if ( !$target instanceof Title
) {
164 wfProfileOut( __METHOD__
);
165 return "<!-- ERROR -->$text";
167 $options = (array)$options;
170 if ( !wfRunHooks( 'LinkBegin', array( $this, $target, &$text,
171 &$customAttribs, &$query, &$options, &$ret ) ) ) {
172 wfProfileOut( __METHOD__
);
176 # Normalize the Title if it's a special page
177 $target = $this->normaliseSpecialPage( $target );
179 # If we don't know whether the page exists, let's find out.
180 wfProfileIn( __METHOD__
. '-checkPageExistence' );
181 if ( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
182 if ( $target->isKnown() ) {
183 $options[] = 'known';
185 $options[] = 'broken';
188 wfProfileOut( __METHOD__
. '-checkPageExistence' );
191 if ( in_array( "forcearticlepath", $options ) && $query ) {
196 # Note: we want the href attribute first, for prettiness.
197 $attribs = array( 'href' => $this->linkUrl( $target, $query, $options ) );
198 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
199 $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
202 $attribs = array_merge(
204 $this->linkAttribs( $target, $customAttribs, $options, $text )
206 if ( is_null( $text ) ) {
207 $text = $this->linkText( $target );
211 if ( wfRunHooks( 'LinkEnd', array( $this, $target, $options, &$text, &$attribs, &$ret ) ) ) {
212 $ret = Html
::rawElement( 'a', $attribs, $text );
215 wfProfileOut( __METHOD__
);
220 * Identical to link(), except $options defaults to 'known'.
222 public function linkKnown( $target, $text = null, $customAttribs = array(), $query = array(), $options = array( 'known', 'noclasses' ) ) {
223 return $this->link( $target, $text, $customAttribs, $query, $options );
227 * Returns the Url used to link to a Title
229 * @param $target Title
231 private function linkUrl( $target, $query, $options ) {
232 wfProfileIn( __METHOD__
);
233 # We don't want to include fragments for broken links, because they
234 # generally make no sense.
235 if ( in_array( 'broken', $options ) && $target->mFragment
!== '' ) {
236 $target = clone $target;
237 $target->mFragment
= '';
240 # If it's a broken link, add the appropriate query pieces, unless
241 # there's already an action specified, or unless 'edit' makes no sense
242 # (i.e., for a nonexistent special page).
243 if ( in_array( 'broken', $options ) && empty( $query['action'] )
244 && $target->getNamespace() != NS_SPECIAL
) {
245 $query['action'] = 'edit';
246 $query['redlink'] = '1';
248 $ret = $target->getLinkUrl( $query );
249 wfProfileOut( __METHOD__
);
254 * Returns the array of attributes used when linking to the Title $target
256 * @param $target Title
258 private function linkAttribs( $target, $attribs, $options, $linkText ) {
259 wfProfileIn( __METHOD__
);
263 if ( !in_array( 'noclasses', $options ) ) {
264 wfProfileIn( __METHOD__
. '-getClasses' );
265 # Now build the classes.
268 if ( in_array( 'broken', $options ) ) {
272 if ( $target->isExternal() ) {
273 $classes[] = 'extiw';
276 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
277 $colour = $this->getLinkColour( $target, $wgUser->getStubThreshold() );
278 if ( $colour !== '' ) {
279 $classes[] = $colour; # mw-redirect or stub
282 if ( $classes != array() ) {
283 $defaults['class'] = implode( ' ', $classes );
285 wfProfileOut( __METHOD__
. '-getClasses' );
288 # Get a default title attribute.
290 $known = in_array( 'known', $options );
291 if ( $target->getPrefixedText() == '' ) {
292 # A link like [[#Foo]]. This used to mean an empty title
293 # attribute, but that's silly. Just don't output a title.
295 $wgLang->caseFold($linkText) !== $wgLang->caseFold($target->getPrefixedText() ) )
297 $defaults['title'] = $target->getPrefixedText();
298 } elseif ( !$known ) {
299 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
302 # Finally, merge the custom attribs with the default ones, and iterate
303 # over that, deleting all "false" attributes.
305 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
306 foreach ( $merged as $key => $val ) {
307 # A false value suppresses the attribute, and we don't want the
308 # href attribute to be overridden.
309 if ( $key != 'href' and $val !== false ) {
313 wfProfileOut( __METHOD__
);
318 * Default text of the links to the Title $target
320 * @param $target Title
322 private function linkText( $target ) {
323 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
324 if ( !$target instanceof Title
) {
328 # If the target is just a fragment, with no title, we return the frag-
329 # ment text. Otherwise, we return the title text itself.
330 if ( $target->getPrefixedText() === '' && $target->getFragment() !== '' ) {
331 return htmlspecialchars( $target->getFragment() );
333 return htmlspecialchars( $target->getPrefixedText() );
337 * Generate either a normal exists-style link or a stub link, depending
338 * on the given page size.
340 * @param $size Integer
341 * @param $nt Title object.
342 * @param $text String
343 * @param $query String
344 * @param $trail String
345 * @param $prefix String
346 * @return string HTML of link
347 * @deprecated since 1.17
349 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
351 wfDeprecated( __METHOD__
);
353 $threshold = $wgUser->getStubThreshold();
354 $colour = ( $size < $threshold ) ?
'stub' : '';
355 // FIXME: replace deprecated makeColouredLinkObj by link()
356 return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
360 * Make appropriate markup for a link to the current article. This is currently rendered
361 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
362 * despite $query not being used.
366 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
368 $text = htmlspecialchars( $nt->getPrefixedText() );
370 list( $inside, $trail ) = Linker
::splitTrail( $trail );
371 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
374 function normaliseSpecialPage( Title
$title ) {
375 if ( $title->getNamespace() == NS_SPECIAL
) {
376 list( $name, $subpage ) = SpecialPage
::resolveAliasWithSubpage( $title->getDBkey() );
380 $ret = SpecialPage
::getTitleFor( $name, $subpage );
381 $ret->mFragment
= $title->getFragment();
389 * Returns the filename part of an url.
390 * Used as alternative text for external images.
392 function fnamePart( $url ) {
393 $basename = strrchr( $url, '/' );
394 if ( false === $basename ) {
397 $basename = substr( $basename, 1 );
403 * Return the code for images which were added via external links,
404 * via Parser::maybeMakeExternalImage().
406 function makeExternalImage( $url, $alt = '' ) {
408 $alt = $this->fnamePart( $url );
411 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
413 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
416 return Html
::element( 'img',
423 * Given parameters derived from [[Image:Foo|options...]], generate the
424 * HTML that that syntax inserts in the page.
426 * @param $title Title object
427 * @param $file File object, or false if it doesn't exist
428 * @param $frameParams Array: associative array of parameters external to the media handler.
429 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
430 * will often be false.
431 * thumbnail If present, downscale and frame
432 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
433 * framed Shows image in original size in a frame
434 * frameless Downscale but don't frame
435 * upright If present, tweak default sizes for portrait orientation
436 * upright_factor Fudge factor for "upright" tweak (default 0.75)
437 * border If present, show a border around the image
438 * align Horizontal alignment (left, right, center, none)
439 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
440 * bottom, text-bottom)
441 * alt Alternate text for image (i.e. alt attribute). Plain text.
442 * caption HTML for image caption.
443 * link-url URL to link to
444 * link-title Title object to link to
445 * link-target Value for the target attribue, only with link-url
446 * no-link Boolean, suppress description link
448 * @param $handlerParams Array: associative array of media handler parameters, to be passed
449 * to transform(). Typical keys are "width" and "page".
450 * @param $time String: timestamp of the file, set as false for current
451 * @param $query String: query params for desc url
452 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
453 * @return String: HTML for an image, with links, wrappers, etc.
455 function makeImageLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "", $widthOption = null ) {
457 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$this, &$title,
458 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
462 if ( $file && !$file->allowInlineDisplay() ) {
463 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
464 return $this->link( $title );
469 $hp =& $handlerParams;
471 // Clean up parameters
472 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
473 if ( !isset( $fp['align'] ) ) {
476 if ( !isset( $fp['alt'] ) ) {
479 if ( !isset( $fp['title'] ) ) {
483 $prefix = $postfix = '';
485 if ( 'center' == $fp['align'] ) {
486 $prefix = '<div class="center">';
488 $fp['align'] = 'none';
490 if ( $file && !isset( $hp['width'] ) ) {
491 $hp['width'] = $file->getWidth( $page );
493 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
494 global $wgThumbLimits, $wgThumbUpright;
495 if ( !isset( $widthOption ) ||
!isset( $wgThumbLimits[$widthOption] ) ) {
496 $widthOption = User
::getDefaultOption( 'thumbsize' );
499 // Reduce width for upright images when parameter 'upright' is used
500 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
501 $fp['upright'] = $wgThumbUpright;
503 // 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
504 $prefWidth = isset( $fp['upright'] ) ?
505 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
506 $wgThumbLimits[$widthOption];
508 // Use width which is smaller: real image width or user preference width
509 // Unless image is scalable vector.
510 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
511 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
512 $hp['width'] = $prefWidth;
517 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
519 # Create a thumbnail. Alignment depends on language
520 # writing direction, # right aligned for left-to-right-
521 # languages ("Western languages"), left-aligned
522 # for right-to-left-languages ("Semitic languages")
524 # If thumbnail width has not been provided, it is set
525 # to the default user option as specified in Language*.php
526 if ( $fp['align'] == '' ) {
527 $fp['align'] = $wgContLang->alignEnd();
529 return $prefix . $this->makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
532 if ( $file && isset( $fp['frameless'] ) ) {
533 $srcWidth = $file->getWidth( $page );
534 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
535 # This is the same behaviour as the "thumb" option does it already.
536 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
537 $hp['width'] = $srcWidth;
541 if ( $file && isset( $hp['width'] ) ) {
542 # Create a resized image, without the additional thumbnail features
543 $thumb = $file->transform( $hp );
549 $s = $this->makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
553 'title' => $fp['title'],
554 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
555 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
556 $params = $this->getImageLinkMTOParams( $fp, $query ) +
$params;
558 $s = $thumb->toHtml( $params );
560 if ( $fp['align'] != '' ) {
561 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
563 return str_replace( "\n", ' ', $prefix . $s . $postfix );
567 * Get the link parameters for MediaTransformOutput::toHtml() from given
568 * frame parameters supplied by the Parser.
569 * @param $frameParams The frame parameters
570 * @param $query An optional query string to add to description page links
572 function getImageLinkMTOParams( $frameParams, $query = '' ) {
573 $mtoParams = array();
574 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
575 $mtoParams['custom-url-link'] = $frameParams['link-url'];
576 if ( isset( $frameParams['link-target'] ) ) {
577 $mtoParams['custom-target-link'] = $frameParams['link-target'];
579 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
580 $mtoParams['custom-title-link'] = $this->normaliseSpecialPage( $frameParams['link-title'] );
581 } elseif ( !empty( $frameParams['no-link'] ) ) {
584 $mtoParams['desc-link'] = true;
585 $mtoParams['desc-query'] = $query;
591 * Make HTML for a thumbnail including image, border and caption
592 * @param $title Title object
593 * @param $file File object or false if it doesn't exist
594 * @param $label String
596 * @param $align String
597 * @param $params Array
598 * @param $framed Boolean
599 * @param $manualthumb String
601 function makeThumbLinkObj( Title
$title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed = false , $manualthumb = "" ) {
602 $frameParams = array(
608 $frameParams['framed'] = true;
610 if ( $manualthumb ) {
611 $frameParams['manualthumb'] = $manualthumb;
613 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
617 * @param $title Title
619 * @param array $frameParams
620 * @param array $handlerParams
622 * @param string $query
625 function makeThumbLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
627 $exists = $file && $file->exists();
631 $hp =& $handlerParams;
633 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
634 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
635 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
636 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
637 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
639 if ( empty( $hp['width'] ) ) {
640 // Reduce width for upright images when parameter 'upright' is used
641 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
646 $outerWidth = $hp['width'] +
2;
648 if ( isset( $fp['manualthumb'] ) ) {
649 # Use manually specified thumbnail
650 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
651 if ( $manual_title ) {
652 $manual_img = wfFindFile( $manual_title );
654 $thumb = $manual_img->getUnscaledThumb( $hp );
659 } elseif ( isset( $fp['framed'] ) ) {
660 // Use image dimensions, don't scale
661 $thumb = $file->getUnscaledThumb( $hp );
663 # Do not present an image bigger than the source, for bitmap-style images
664 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
665 $srcWidth = $file->getWidth( $page );
666 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
667 $hp['width'] = $srcWidth;
669 $thumb = $file->transform( $hp );
673 $outerWidth = $thumb->getWidth() +
2;
675 $outerWidth = $hp['width'] +
2;
679 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
680 # So we don't need to pass it here in $query. However, the URL for the
681 # zoom icon still needs it, so we make a unique query for it. See bug 14771
682 $url = $title->getLocalURL( $query );
684 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
687 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
689 $s .= $this->makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
691 } elseif ( !$thumb ) {
692 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
697 'title' => $fp['title'],
698 'img-class' => 'thumbimage' );
699 $params = $this->getImageLinkMTOParams( $fp, $query ) +
$params;
700 $s .= $thumb->toHtml( $params );
701 if ( isset( $fp['framed'] ) ) {
704 $zoomIcon = '<div class="magnify">' .
705 '<a href="' . htmlspecialchars( $url ) . '" class="internal" ' .
706 'title="' . htmlspecialchars( wfMsg( 'thumbnail-more' ) ) . '">' .
707 '<img src="' . htmlspecialchars( $wgStylePath ) . '/common/images/magnify-clip.png" ' .
708 'width="15" height="11" alt="" /></a></div>';
711 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
712 return str_replace( "\n", ' ', $s );
716 * Make a "broken" link to an image
718 * @param $title Title object
719 * @param $text String: link label in unescaped text form
720 * @param $query String: query string
721 * @param $trail String: link trail (HTML fragment)
722 * @param $prefix String: link prefix (HTML fragment)
723 * @param $time Boolean: a file of a certain timestamp was requested
726 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
727 global $wgEnableUploads, $wgUploadMissingFileUrl;
728 if ( $title instanceof Title
) {
729 wfProfileIn( __METHOD__
);
730 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
732 list( $inside, $trail ) = self
::splitTrail( $trail );
734 $text = htmlspecialchars( $title->getPrefixedText() );
736 if ( ( $wgUploadMissingFileUrl ||
$wgEnableUploads ) && !$currentExists ) {
737 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
740 wfProfileOut( __METHOD__
);
741 return $this->linkKnown( $title, "$prefix$text$inside", array(), $query ) . $trail;
744 $href = $this->getUploadUrl( $title, $query );
746 wfProfileOut( __METHOD__
);
747 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
748 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
749 "$prefix$text$inside</a>$trail";
751 wfProfileOut( __METHOD__
);
752 return $this->linkKnown( $title, "$prefix$text$inside", array(), $query ) . $trail;
755 wfProfileOut( __METHOD__
);
756 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
761 * Get the URL to upload a certain file
763 * @param $destFile Title object of the file to upload
764 * @param $query String: urlencoded query string to prepend
765 * @return String: urlencoded URL
767 protected function getUploadUrl( $destFile, $query = '' ) {
768 global $wgUploadMissingFileUrl;
769 $q = 'wpDestFile=' . $destFile->getPartialUrl();
773 if ( $wgUploadMissingFileUrl ) {
774 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
776 $upload = SpecialPage
::getTitleFor( 'Upload' );
777 return $upload->getLocalUrl( $q );
782 * Create a direct link to a given uploaded file.
784 * @param $title Title object.
785 * @param $text String: pre-sanitized HTML
786 * @param $time string: time image was created
787 * @return String: HTML
789 * @todo Handle invalid or missing images better.
791 public function makeMediaLinkObj( $title, $text = '', $time = false ) {
792 if ( is_null( $title ) ) {
793 # # # HOTFIX. Instead of breaking, return empty string.
796 $img = wfFindFile( $title, array( 'time' => $time ) );
798 $url = $img->getURL();
801 $url = $this->getUploadUrl( $title );
804 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES
);
808 $u = htmlspecialchars( $url );
809 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
814 * Make a link to a special page given its name and, optionally,
815 * a message key from the link text.
816 * Usage example: $skin->specialLink( 'recentchanges' )
818 function specialLink( $name, $key = '' ) {
819 if ( $key == '' ) { $key = strtolower( $name ); }
821 return $this->linkKnown( SpecialPage
::getTitleFor( $name ) , wfMsg( $key ) );
825 * Make an external link
826 * @param $url String: URL to link to
827 * @param $text String: text of link
828 * @param $escape Boolean: do we escape the link text?
829 * @param $linktype String: type of external link. Gets added to the classes
830 * @param $attribs Array of extra attributes to <a>
832 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
834 if ( isset($linktype) && $linktype ) {
835 $class .= " $linktype";
837 if ( isset($attribs['class']) && $attribs['class'] ) {
838 $class .= " {$attribs['class']}";
840 $attribs['class'] = $class;
843 $text = htmlspecialchars( $text );
846 $success = wfRunHooks( 'LinkerMakeExternalLink', array( &$url, &$text, &$link, &$attribs, $linktype ) );
848 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
851 $attribs['href'] = $url;
852 return Html
::rawElement( 'a', $attribs, $text );
856 * Make user link (or user contributions for unregistered users)
857 * @param $userId Integer: user id in database.
858 * @param $userText String: user name in database
859 * @return String: HTML fragment
862 function userLink( $userId, $userText ) {
863 if ( $userId == 0 ) {
864 $page = SpecialPage
::getTitleFor( 'Contributions', $userText );
866 $page = Title
::makeTitle( NS_USER
, $userText );
868 return $this->link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
872 * Generate standard user tool links (talk, contributions, block link, etc.)
874 * @param $userId Integer: user identifier
875 * @param $userText String: user name or IP address
876 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
877 * red if the user has no edits?
878 * @param $flags Integer: customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
879 * @param $edits Integer: user edit count (optional, for performance)
880 * @return String: HTML fragment
882 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null ) {
883 global $wgUser, $wgDisableAnonTalk, $wgLang;
884 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
885 $blockable = !$flags & self
::TOOL_LINKS_NOBLOCK
;
889 $items[] = $this->userTalkLink( $userId, $userText );
892 // check if the user has an edit
894 if ( $redContribsWhenNoEdits ) {
895 $count = !is_null( $edits ) ?
$edits : User
::edits( $userId );
897 $attribs['class'] = 'new';
900 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
902 $items[] = $this->link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
904 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
905 $items[] = $this->blockLink( $userId, $userText );
909 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
916 * Alias for userToolLinks( $userId, $userText, true );
917 * @param $userId Integer: user identifier
918 * @param $userText String: user name or IP address
919 * @param $edits Integer: user edit count (optional, for performance)
921 public function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
922 return $this->userToolLinks( $userId, $userText, true, 0, $edits );
927 * @param $userId Integer: user id in database.
928 * @param $userText String: user name in database.
929 * @return String: HTML fragment with user talk link
932 function userTalkLink( $userId, $userText ) {
933 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
934 $userTalkLink = $this->link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
935 return $userTalkLink;
939 * @param $userId Integer: userid
940 * @param $userText String: user name in database.
941 * @return String: HTML fragment with block link
944 function blockLink( $userId, $userText ) {
945 $blockPage = SpecialPage
::getTitleFor( 'Blockip', $userText );
946 $blockLink = $this->link( $blockPage, wfMsgHtml( 'blocklink' ) );
951 * Generate a user link if the current user is allowed to view it
952 * @param $rev Revision object.
953 * @param $isPublic Boolean: show only if all users can see it
954 * @return String: HTML fragment
956 function revUserLink( $rev, $isPublic = false ) {
957 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
958 $link = wfMsgHtml( 'rev-deleted-user' );
959 } else if ( $rev->userCan( Revision
::DELETED_USER
) ) {
960 $link = $this->userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
961 $rev->getUserText( Revision
::FOR_THIS_USER
) );
963 $link = wfMsgHtml( 'rev-deleted-user' );
965 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
966 return '<span class="history-deleted">' . $link . '</span>';
972 * Generate a user tool link cluster if the current user is allowed to view it
973 * @param $rev Revision object.
974 * @param $isPublic Boolean: show only if all users can see it
975 * @return string HTML
977 function revUserTools( $rev, $isPublic = false ) {
978 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
979 $link = wfMsgHtml( 'rev-deleted-user' );
980 } else if ( $rev->userCan( Revision
::DELETED_USER
) ) {
981 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
982 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
983 $link = $this->userLink( $userId, $userText ) .
984 ' ' . $this->userToolLinks( $userId, $userText );
986 $link = wfMsgHtml( 'rev-deleted-user' );
988 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
989 return ' <span class="history-deleted">' . $link . '</span>';
995 * This function is called by all recent changes variants, by the page history,
996 * and by the user contributions list. It is responsible for formatting edit
997 * comments. It escapes any HTML in the comment, but adds some CSS to format
998 * auto-generated comments (from section editing) and formats [[wikilinks]].
1000 * @author Erik Moeller <moeller@scireview.de>
1002 * Note: there's not always a title to pass to this function.
1003 * Since you can't set a default parameter for a reference, I've turned it
1004 * temporarily to a value pass. Should be adjusted further. --brion
1006 * @param $comment String
1007 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1008 * @param $local Boolean: whether section links should refer to local page
1010 function formatComment( $comment, $title = null, $local = false ) {
1011 wfProfileIn( __METHOD__
);
1013 # Sanitize text a bit:
1014 $comment = str_replace( "\n", " ", $comment );
1015 # Allow HTML entities (for bug 13815)
1016 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1018 # Render autocomments and make links:
1019 $comment = $this->formatAutocomments( $comment, $title, $local );
1020 $comment = $this->formatLinksInComment( $comment, $title, $local );
1022 wfProfileOut( __METHOD__
);
1027 * The pattern for autogen comments is / * foo * /, which makes for
1029 * We look for all comments, match any text before and after the comment,
1030 * add a separator where needed and format the comment itself with CSS
1031 * Called by Linker::formatComment.
1033 * @param $comment String: comment text
1034 * @param $title An optional title object used to links to sections
1035 * @param $local Boolean: whether section links should refer to local page
1036 * @return String: formatted comment
1038 private function formatAutocomments( $comment, $title = null, $local = false ) {
1040 $this->autocommentTitle
= $title;
1041 $this->autocommentLocal
= $local;
1042 $comment = preg_replace_callback(
1043 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1044 array( $this, 'formatAutocommentsCallback' ),
1046 unset( $this->autocommentTitle
);
1047 unset( $this->autocommentLocal
);
1051 private function formatAutocommentsCallback( $match ) {
1052 $title = $this->autocommentTitle
;
1053 $local = $this->autocommentLocal
;
1062 # Remove links that a user may have manually put in the autosummary
1063 # This could be improved by copying as much of Parser::stripSectionName as desired.
1064 $section = str_replace( '[[:', '', $section );
1065 $section = str_replace( '[[', '', $section );
1066 $section = str_replace( ']]', '', $section );
1068 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1070 $sectionTitle = Title
::newFromText( '#' . $section );
1072 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1073 $title->getDBkey(), $section );
1075 if ( $sectionTitle ) {
1076 $link = $this->link( $sectionTitle,
1077 htmlspecialchars( wfMsgForContent( 'sectionlink' ) ), array(), array(),
1083 $auto = "$link$auto";
1085 # written summary $presep autocomment (summary /* section */)
1086 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1089 # autocomment $postsep written summary (/* section */ summary)
1090 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1092 $auto = '<span class="autocomment">' . $auto . '</span>';
1093 $comment = $pre . $auto . $post;
1098 * Formats wiki links and media links in text; all other wiki formatting
1101 * @todo Fixme: doesn't handle sub-links as in image thumb texts like the main parser
1102 * @param $comment String: text to format links in
1103 * @param $title An optional title object used to links to sections
1104 * @param $local Boolean: whether section links should refer to local page
1107 public function formatLinksInComment( $comment, $title = null, $local = false ) {
1108 $this->commentContextTitle
= $title;
1109 $this->commentLocal
= $local;
1110 $html = preg_replace_callback(
1111 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1112 array( $this, 'formatLinksInCommentCallback' ),
1114 unset( $this->commentContextTitle
);
1115 unset( $this->commentLocal
);
1119 protected function formatLinksInCommentCallback( $match ) {
1122 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1123 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1125 $comment = $match[0];
1127 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1128 if ( strpos( $match[1], '%' ) !== false ) {
1129 $match[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $match[1] ) );
1132 # Handle link renaming [[foo|text]] will show link as "text"
1133 if ( $match[3] != "" ) {
1138 $submatch = array();
1140 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1141 # Media link; trail not supported.
1142 $linkRegexp = '/\[\[(.*?)\]\]/';
1143 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1144 $thelink = $this->makeMediaLinkObj( $title, $text );
1146 # Other kind of link
1147 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1148 $trail = $submatch[1];
1152 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1153 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1154 $match[1] = substr( $match[1], 1 );
1155 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1158 $linkTarget = Linker
::normalizeSubpageLink( $this->commentContextTitle
,
1159 $match[1], $linkText );
1161 $target = Title
::newFromText( $linkTarget );
1163 if ( $target->getText() == '' && $target->getInterwiki() === ''
1164 && !$this->commentLocal
&& $this->commentContextTitle
)
1166 $newTarget = clone ( $this->commentContextTitle
);
1167 $newTarget->setFragment( '#' . $target->getFragment() );
1168 $target = $newTarget;
1170 $thelink = $this->link(
1177 // If the link is still valid, go ahead and replace it in!
1178 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1186 * @param $contextTitle Title
1191 static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1194 # :Foobar -- override special treatment of prefix (images, language links)
1195 # /Foobar -- convert to CurrentPage/Foobar
1196 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1197 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1198 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1200 wfProfileIn( __METHOD__
);
1201 $ret = $target; # default return value is no change
1203 # Some namespaces don't allow subpages,
1204 # so only perform processing if subpages are allowed
1205 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1206 $hash = strpos( $target, '#' );
1207 if ( $hash !== false ) {
1208 $suffix = substr( $target, $hash );
1209 $target = substr( $target, 0, $hash );
1214 $target = trim( $target );
1215 # Look at the first character
1216 if ( $target != '' && $target { 0 } === '/' ) {
1217 # / at end means we don't want the slash to be shown
1219 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1220 if ( $trailingSlashes ) {
1221 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1223 $noslash = substr( $target, 1 );
1226 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1227 if ( $text === '' ) {
1228 $text = $target . $suffix;
1229 } # this might be changed for ugliness reasons
1231 # check for .. subpage backlinks
1233 $nodotdot = $target;
1234 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1236 $nodotdot = substr( $nodotdot, 3 );
1238 if ( $dotdotcount > 0 ) {
1239 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1240 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1241 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1242 # / at the end means don't show full path
1243 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1244 $nodotdot = substr( $nodotdot, 0, -1 );
1245 if ( $text === '' ) {
1246 $text = $nodotdot . $suffix;
1249 $nodotdot = trim( $nodotdot );
1250 if ( $nodotdot != '' ) {
1251 $ret .= '/' . $nodotdot;
1259 wfProfileOut( __METHOD__
);
1264 * Wrap a comment in standard punctuation and formatting if
1265 * it's non-empty, otherwise return empty string.
1267 * @param $comment String
1268 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1269 * @param $local Boolean: whether section links should refer to local page
1273 function commentBlock( $comment, $title = null, $local = false ) {
1274 // '*' used to be the comment inserted by the software way back
1275 // in antiquity in case none was provided, here for backwards
1276 // compatability, acc. to brion -ævar
1277 if ( $comment == '' ||
$comment == '*' ) {
1280 $formatted = $this->formatComment( $comment, $title, $local );
1281 return " <span class=\"comment\">($formatted)</span>";
1286 * Wrap and format the given revision's comment block, if the current
1287 * user is allowed to view it.
1289 * @param $rev Revision object
1290 * @param $local Boolean: whether section links should refer to local page
1291 * @param $isPublic Boolean: show only if all users can see it
1292 * @return String: HTML fragment
1294 function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1295 if ( $rev->getRawComment() == "" ) {
1298 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1299 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1300 } else if ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1301 $block = $this->commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1302 $rev->getTitle(), $local );
1304 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1306 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1307 return " <span class=\"history-deleted\">$block</span>";
1312 public function formatRevisionSize( $size ) {
1314 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1317 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1320 $stxt = htmlspecialchars( $stxt );
1321 return "<span class=\"history-size\">$stxt</span>";
1325 * Add another level to the Table of Contents
1327 function tocIndent() {
1332 * Finish one or more sublevels on the Table of Contents
1334 function tocUnindent( $level ) {
1335 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1339 * parameter level defines if we are on an indentation level
1341 function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1342 $classes = "toclevel-$level";
1343 if ( $sectionIndex !== false )
1344 $classes .= " tocsection-$sectionIndex";
1345 return "\n<li class=\"$classes\"><a href=\"#" .
1346 $anchor . '"><span class="tocnumber">' .
1347 $tocnumber . '</span> <span class="toctext">' .
1348 $tocline . '</span></a>';
1352 * End a Table Of Contents line.
1353 * tocUnindent() will be used instead if we're ending a line below
1356 function tocLineEnd() {
1361 * Wraps the TOC in a table and provides the hide/collapse javascript.
1363 * @param $toc String: html of the Table Of Contents
1364 * @param $lang mixed: Language code for the toc title
1365 * @return String: full html of the TOC
1367 function tocList( $toc, $lang = false ) {
1368 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1370 '<table id="toc" class="toc"><tr><td>'
1371 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1373 . "</ul>\n</td></tr></table>\n";
1377 * Generate a table of contents from a section tree
1380 * @param $tree Return value of ParserOutput::getSections()
1381 * @return String: HTML fragment
1383 public function generateTOC( $tree ) {
1386 foreach ( $tree as $section ) {
1387 if ( $section['toclevel'] > $lastLevel )
1388 $toc .= $this->tocIndent();
1389 else if ( $section['toclevel'] < $lastLevel )
1390 $toc .= $this->tocUnindent(
1391 $lastLevel - $section['toclevel'] );
1393 $toc .= $this->tocLineEnd();
1395 $toc .= $this->tocLine( $section['anchor'],
1396 $section['line'], $section['number'],
1397 $section['toclevel'], $section['index'] );
1398 $lastLevel = $section['toclevel'];
1400 $toc .= $this->tocLineEnd();
1401 return $this->tocList( $toc );
1405 * Create a section edit link. This supersedes editSectionLink() and
1406 * editSectionLinkForOther().
1408 * @param $nt Title The title being linked to (may not be the same as
1409 * $wgTitle, if the section is included from a template)
1410 * @param $section string The designation of the section being pointed to,
1411 * to be included in the link, like "§ion=$section"
1412 * @param $tooltip string The tooltip to use for the link: will be escaped
1413 * and wrapped in the 'editsectionhint' message
1414 * @param $lang string Language code
1415 * @return string HTML to use for edit link
1417 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1418 // HTML generated here should probably have userlangattributes
1419 // added to it for LTR text on RTL pages
1421 if ( !is_null( $tooltip ) ) {
1422 # Bug 25462: undo double-escaping.
1423 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1424 $attribs['title'] = wfMsgReal( 'editsectionhint', array( $tooltip ), true, $lang );
1426 $link = $this->link( $nt, wfMsgExt( 'editsection', array( 'language' => $lang ) ),
1428 array( 'action' => 'edit', 'section' => $section ),
1429 array( 'noclasses', 'known' )
1432 # Run the old hook. This takes up half of the function . . . hopefully
1433 # we can rid of it someday.
1436 $attribs = htmlspecialchars( wfMsgReal( 'editsectionhint', array( $tooltip ), true, $lang ) );
1437 $attribs = " title=\"$attribs\"";
1440 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $link, &$result, $lang ) );
1441 if ( !is_null( $result ) ) {
1442 # For reverse compatibility, add the brackets *after* the hook is
1443 # run, and even add them to hook-provided text. (This is the main
1444 # reason that the EditSectionLink hook is deprecated in favor of
1445 # DoEditSectionLink: it can't change the brackets or the span.)
1446 $result = wfMsgExt( 'editsection-brackets', array( 'escape', 'replaceafter', 'language' => $lang ), $result );
1447 return "<span class=\"editsection\">$result</span>";
1450 # Add the brackets and the span, and *then* run the nice new hook, with
1451 # clean and non-redundant arguments.
1452 $result = wfMsgExt( 'editsection-brackets', array( 'escape', 'replaceafter', 'language' => $lang ), $link );
1453 $result = "<span class=\"editsection\">$result</span>";
1455 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
1460 * Create a headline for content
1462 * @param $level Integer: the level of the headline (1-6)
1463 * @param $attribs String: any attributes for the headline, starting with
1464 * a space and ending with '>'
1465 * This *must* be at least '>' for no attribs
1466 * @param $anchor String: the anchor to give the headline (the bit after the #)
1467 * @param $text String: the text of the header
1468 * @param $link String: HTML to add for the section edit link
1469 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1470 * backward compatibility (false to omit)
1472 * @return String: HTML headline
1474 public function makeHeadline( $level, $attribs, $anchor, $text, $link, $legacyAnchor = false ) {
1475 $ret = "<h$level$attribs"
1477 . " <span class=\"mw-headline\" id=\"$anchor\">$text</span>"
1479 if ( $legacyAnchor !== false ) {
1480 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1486 * Split a link trail, return the "inside" portion and the remainder of the trail
1487 * as a two-element array
1489 static function splitTrail( $trail ) {
1490 static $regex = false;
1491 if ( $regex === false ) {
1493 $regex = $wgContLang->linkTrail();
1496 if ( $trail !== '' ) {
1498 if ( preg_match( $regex, $trail, $m ) ) {
1503 return array( $inside, $trail );
1507 * Generate a rollback link for a given revision. Currently it's the
1508 * caller's responsibility to ensure that the revision is the top one. If
1509 * it's not, of course, the user will get an error message.
1511 * If the calling page is called with the parameter &bot=1, all rollback
1512 * links also get that parameter. It causes the edit itself and the rollback
1513 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1514 * changes, so this allows sysops to combat a busy vandal without bothering
1517 * @param $rev Revision object
1519 function generateRollback( $rev ) {
1520 return '<span class="mw-rollback-link">['
1521 . $this->buildRollbackLink( $rev )
1526 * Build a raw rollback link, useful for collections of "tool" links
1528 * @param $rev Revision object
1529 * @return String: HTML fragment
1531 public function buildRollbackLink( $rev ) {
1532 global $wgRequest, $wgUser;
1533 $title = $rev->getTitle();
1535 'action' => 'rollback',
1536 'from' => $rev->getUserText(),
1537 'token' => $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1539 if ( $wgRequest->getBool( 'bot' ) ) {
1540 $query['bot'] = '1';
1541 $query['hidediff'] = '1'; // bug 15999
1545 wfMsgHtml( 'rollbacklink' ),
1546 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1548 array( 'known', 'noclasses' )
1553 * Returns HTML for the "templates used on this page" list.
1555 * @param $templates Array of templates from Article::getUsedTemplate
1557 * @param $preview Boolean: whether this is for a preview
1558 * @param $section Boolean: whether this is for a section edit
1559 * @return String: HTML output
1561 public function formatTemplates( $templates, $preview = false, $section = false ) {
1562 wfProfileIn( __METHOD__
);
1565 if ( count( $templates ) > 0 ) {
1566 # Do a batch existence check
1567 $batch = new LinkBatch
;
1568 foreach ( $templates as $title ) {
1569 $batch->addObj( $title );
1573 # Construct the HTML
1574 $outText = '<div class="mw-templatesUsedExplanation">';
1576 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1577 } elseif ( $section ) {
1578 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1580 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1582 $outText .= "</div><ul>\n";
1584 usort( $templates, array( 'Title', 'compare' ) );
1585 foreach ( $templates as $titleObj ) {
1586 $r = $titleObj->getRestrictions( 'edit' );
1587 if ( in_array( 'sysop', $r ) ) {
1588 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1589 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1590 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1594 if ( $titleObj->quickUserCan( 'edit' ) ) {
1595 $editLink = $this->link(
1597 wfMsg( 'editlink' ),
1599 array( 'action' => 'edit' )
1602 $editLink = $this->link(
1604 wfMsg( 'viewsourcelink' ),
1606 array( 'action' => 'edit' )
1609 $outText .= '<li>' . $this->link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1611 $outText .= '</ul>';
1613 wfProfileOut( __METHOD__
);
1618 * Returns HTML for the "hidden categories on this page" list.
1620 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1622 * @return String: HTML output
1624 public function formatHiddenCategories( $hiddencats ) {
1626 wfProfileIn( __METHOD__
);
1629 if ( count( $hiddencats ) > 0 ) {
1630 # Construct the HTML
1631 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1632 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1633 $outText .= "</div><ul>\n";
1635 foreach ( $hiddencats as $titleObj ) {
1636 $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
1638 $outText .= '</ul>';
1640 wfProfileOut( __METHOD__
);
1645 * Format a size in bytes for output, using an appropriate
1646 * unit (B, KB, MB or GB) according to the magnitude in question
1648 * @param $size Size to format
1651 public function formatSize( $size ) {
1653 return htmlspecialchars( $wgLang->formatSize( $size ) );
1657 * Given the id of an interface element, constructs the appropriate title
1658 * attribute from the system messages. (Note, this is usually the id but
1659 * isn't always, because sometimes the accesskey needs to go on a different
1660 * element than the id, for reverse-compatibility, etc.)
1662 * @param $name String: id of the element, minus prefixes.
1663 * @param $options Mixed: null or the string 'withaccess' to add an access-
1665 * @return String: contents of the title attribute (which you must HTML-
1666 * escape), or false for no title attribute
1668 public function titleAttrib( $name, $options = null ) {
1669 wfProfileIn( __METHOD__
);
1671 $message = wfMessage( "tooltip-$name" );
1673 if ( !$message->exists() ) {
1676 $tooltip = $message->text();
1677 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1678 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1679 # Message equal to '-' means suppress it.
1680 if ( $tooltip == '-' ) {
1685 if ( $options == 'withaccess' ) {
1686 $accesskey = $this->accesskey( $name );
1687 if ( $accesskey !== false ) {
1688 if ( $tooltip === false ||
$tooltip === '' ) {
1689 $tooltip = "[$accesskey]";
1691 $tooltip .= " [$accesskey]";
1696 wfProfileOut( __METHOD__
);
1701 * Given the id of an interface element, constructs the appropriate
1702 * accesskey attribute from the system messages. (Note, this is usually
1703 * the id but isn't always, because sometimes the accesskey needs to go on
1704 * a different element than the id, for reverse-compatibility, etc.)
1706 * @param $name String: id of the element, minus prefixes.
1707 * @return String: contents of the accesskey attribute (which you must HTML-
1708 * escape), or false for no accesskey attribute
1710 public function accesskey( $name ) {
1711 if ( isset( $this->accesskeycache
[$name] ) ) {
1712 return $this->accesskeycache
[$name];
1714 wfProfileIn( __METHOD__
);
1716 $message = wfMessage( "accesskey-$name" );
1718 if ( !$message->exists() ) {
1721 $accesskey = $message->plain();
1722 if ( $accesskey === '' ||
$accesskey === '-' ) {
1723 # FIXME: Per standard MW behavior, a value of '-' means to suppress the
1724 # attribute, but this is broken for accesskey: that might be a useful
1730 wfProfileOut( __METHOD__
);
1731 return $this->accesskeycache
[$name] = $accesskey;
1735 * Creates a (show/hide) link for deleting revisions/log entries
1737 * @param $query Array: query parameters to be passed to link()
1738 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1739 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1741 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1742 * span to allow for customization of appearance with CSS
1744 public function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1745 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1746 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1747 $tag = $restricted ?
'strong' : 'span';
1748 $link = $this->link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1749 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1753 * Creates a dead (show/hide) link for deleting revisions/log entries
1755 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1757 * @return string HTML text wrapped in a span to allow for customization
1758 * of appearance with CSS
1760 public function revDeleteLinkDisabled( $delete = true ) {
1761 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1762 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($text)" );
1765 /* Deprecated methods */
1768 * @deprecated since 1.16 Use link()
1770 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
1771 * it if you already have a title object handy. See makeLinkObj for further documentation.
1773 * @param $title String: the text of the title
1774 * @param $text String: link text
1775 * @param $query String: optional query part
1776 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1777 * be included in the link text. Other characters will be appended after
1778 * the end of the link.
1780 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
1781 wfProfileIn( __METHOD__
);
1782 $nt = Title
::newFromText( $title );
1783 if ( $nt instanceof Title
) {
1784 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
1786 wfDebug( 'Invalid title passed to Linker::makeLink(): "' . $title . "\"\n" );
1787 $result = $text == "" ?
$title : $text;
1790 wfProfileOut( __METHOD__
);
1795 * @deprecated since 1.16 Use link()
1797 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
1798 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
1800 * @param $title String: the text of the title
1801 * @param $text String: link text
1802 * @param $query String: optional query part
1803 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1804 * be included in the link text. Other characters will be appended after
1805 * the end of the link.
1806 * @param $prefix String: Optional prefix
1807 * @param $aprops String: extra attributes to the a-element
1809 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = '' ) {
1810 $nt = Title
::newFromText( $title );
1811 if ( $nt instanceof Title
) {
1812 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
1814 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "' . $title . "\"\n" );
1815 return $text == '' ?
$title : $text;
1820 * @deprecated since 1.16 Use link()
1822 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1823 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1825 * @param $title String: The text of the title
1826 * @param $text String: Link text
1827 * @param $query String: Optional query part
1828 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1829 * be included in the link text. Other characters will be appended after
1830 * the end of the link.
1832 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1833 $nt = Title
::newFromText( $title );
1834 if ( $nt instanceof Title
) {
1835 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
1837 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "' . $title . "\"\n" );
1838 return $text == '' ?
$title : $text;
1843 * @deprecated since 1.16 Use link()
1845 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
1846 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
1848 * @param $title String: the text of the title
1849 * @param $text String: link text
1850 * @param $query String: optional query part
1851 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1852 * be included in the link text. Other characters will be appended after
1853 * the end of the link.
1855 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
1856 wfDeprecated( __METHOD__
);
1857 $nt = Title
::newFromText( $title );
1858 if ( $nt instanceof Title
) {
1859 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
1861 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "' . $title . "\"\n" );
1862 return $text == '' ?
$title : $text;
1867 * @deprecated since 1.16 Use link()
1869 * Make a link for a title which may or may not be in the database. If you need to
1870 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1871 * call to this will result in a DB query.
1873 * @param $nt Title: the title object to make the link from, e.g. from
1874 * Title::newFromText.
1875 * @param $text String: link text
1876 * @param $query String: optional query part
1877 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1878 * be included in the link text. Other characters will be appended after
1879 * the end of the link.
1880 * @param $prefix String: optional prefix. As trail, only before instead of after.
1882 function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1883 wfProfileIn( __METHOD__
);
1884 $query = wfCgiToArray( $query );
1885 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1886 if ( $text === '' ) {
1887 $text = $this->linkText( $nt );
1890 $ret = $this->link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1892 wfProfileOut( __METHOD__
);
1897 * @deprecated since 1.16 Use link()
1899 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1900 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1903 * @param $title Title object of target page
1904 * @param $text String: text to replace the title
1905 * @param $query String: link target
1906 * @param $trail String: text after link
1907 * @param $prefix String: text before link text
1908 * @param $aprops String: extra attributes to the a-element
1909 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1910 * @return the a-element
1912 function makeKnownLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
1913 wfProfileIn( __METHOD__
);
1915 if ( $text == '' ) {
1916 $text = $this->linkText( $title );
1918 $attribs = Sanitizer
::mergeAttributes(
1919 Sanitizer
::decodeTagAttributes( $aprops ),
1920 Sanitizer
::decodeTagAttributes( $style )
1922 $query = wfCgiToArray( $query );
1923 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1925 $ret = $this->link( $title, "$prefix$text$inside", $attribs, $query,
1926 array( 'known', 'noclasses' ) ) . $trail;
1928 wfProfileOut( __METHOD__
);
1933 * @deprecated since 1.16 Use link()
1935 * Make a red link to the edit page of a given title.
1937 * @param $title Title object of the target page
1938 * @param $text String: Link text
1939 * @param $query String: Optional query part
1940 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1941 * be included in the link text. Other characters will be appended after
1942 * the end of the link.
1943 * @param $prefix String: Optional prefix
1945 function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
1946 wfProfileIn( __METHOD__
);
1948 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1949 if ( $text === '' ) {
1950 $text = $this->linkText( $title );
1953 $ret = $this->link( $title, "$prefix$text$inside", array(),
1954 wfCgiToArray( $query ), 'broken' ) . $trail;
1956 wfProfileOut( __METHOD__
);
1961 * @deprecated since 1.16 Use link()
1963 * Make a brown link to a short article.
1965 * @param $nt Title object of the target page
1966 * @param $text String: link text
1967 * @param $query String: optional query part
1968 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1969 * be included in the link text. Other characters will be appended after
1970 * the end of the link.
1971 * @param $prefix String: Optional prefix
1973 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1974 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
1978 * @deprecated since 1.16 Use link()
1980 * Make a coloured link.
1982 * @param $nt Title object of the target page
1983 * @param $colour Integer: colour of the link
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 makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
1992 if ( $colour != '' ) {
1993 $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
1997 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2000 /** Obsolete alias */
2001 function makeImage( $url, $alt = '' ) {
2002 wfDeprecated( __METHOD__
);
2003 return $this->makeExternalImage( $url, $alt );
2007 * Creates the HTML source for images
2008 * @deprecated since 1.16 use makeImageLink2
2010 * @param $title Title object
2011 * @param $label String: label text
2012 * @param $alt String: alt text
2013 * @param $align String: horizontal alignment: none, left, center, right)
2014 * @param $handlerParams Array: parameters to be passed to the media handler
2015 * @param $framed Boolean: shows image in original size in a frame
2016 * @param $thumb Boolean: shows image as thumbnail in a frame
2017 * @param $manualthumb String: image name for the manual thumbnail
2018 * @param $valign String: vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
2019 * @param $time String: timestamp of the file, set as false for current
2022 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
2023 $thumb = false, $manualthumb = '', $valign = '', $time = false ) {
2024 $frameParams = array( 'alt' => $alt, 'caption' => $label );
2026 $frameParams['align'] = $align;
2029 $frameParams['framed'] = true;
2032 $frameParams['thumbnail'] = true;
2034 if ( $manualthumb ) {
2035 $frameParams['manualthumb'] = $manualthumb;
2038 $frameParams['valign'] = $valign;
2040 $file = wfFindFile( $title, array( 'time' => $time ) );
2041 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
2044 /** @deprecated use Linker::makeMediaLinkObj() */
2045 function makeMediaLink( $name, $unused = '', $text = '', $time = false ) {
2046 $nt = Title
::makeTitleSafe( NS_FILE
, $name );
2047 return $this->makeMediaLinkObj( $nt, $text, $time );
2051 * Returns the attributes for the tooltip and access key.
2053 public function tooltipAndAccesskeyAttribs( $name ) {
2054 global $wgEnableTooltipsAndAccesskeys;
2055 if ( !$wgEnableTooltipsAndAccesskeys )
2057 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2058 # no attribute" instead of "output '' as value for attribute", this
2059 # would be three lines.
2061 'title' => $this->titleAttrib( $name, 'withaccess' ),
2062 'accesskey' => $this->accesskey( $name )
2064 if ( $attribs['title'] === false ) {
2065 unset( $attribs['title'] );
2067 if ( $attribs['accesskey'] === false ) {
2068 unset( $attribs['accesskey'] );
2074 * @deprecated since 1.14
2075 * Returns raw bits of HTML, use titleAttrib() and accesskey()
2077 public function tooltipAndAccesskey( $name ) {
2078 return Xml
::expandAttributes( $this->tooltipAndAccesskeyAttribs( $name ) );
2082 * @deprecated since 1.14
2083 * Returns raw bits of HTML, use titleAttrib()
2085 public function tooltip( $name, $options = null ) {
2086 global $wgEnableTooltipsAndAccesskeys;
2087 if ( !$wgEnableTooltipsAndAccesskeys )
2089 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2090 # no attribute" instead of "output '' as value for attribute", this
2091 # would be two lines.
2092 $tooltip = $this->titleAttrib( $name, $options );
2093 if ( $tooltip === false ) {
2096 return Xml
::expandAttributes( array(
2097 'title' => $this->titleAttrib( $name, $options )