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.
289 $known = in_array( 'known', $options );
290 if ( $target->getPrefixedText() == '' ) {
291 # A link like [[#Foo]]. This used to mean an empty title
292 # attribute, but that's silly. Just don't output a title.
293 } elseif ( $known && strtolower($linkText) !== strtolower($target->getPrefixedText() ) ) {
294 $defaults['title'] = $target->getPrefixedText();
295 } elseif ( !$known ) {
296 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
299 # Finally, merge the custom attribs with the default ones, and iterate
300 # over that, deleting all "false" attributes.
302 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
303 foreach ( $merged as $key => $val ) {
304 # A false value suppresses the attribute, and we don't want the
305 # href attribute to be overridden.
306 if ( $key != 'href' and $val !== false ) {
310 wfProfileOut( __METHOD__
);
315 * Default text of the links to the Title $target
317 * @param $target Title
319 private function linkText( $target ) {
320 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
321 if ( !$target instanceof Title
) {
325 # If the target is just a fragment, with no title, we return the frag-
326 # ment text. Otherwise, we return the title text itself.
327 if ( $target->getPrefixedText() === '' && $target->getFragment() !== '' ) {
328 return htmlspecialchars( $target->getFragment() );
330 return htmlspecialchars( $target->getPrefixedText() );
334 * Generate either a normal exists-style link or a stub link, depending
335 * on the given page size.
337 * @param $size Integer
338 * @param $nt Title object.
339 * @param $text String
340 * @param $query String
341 * @param $trail String
342 * @param $prefix String
343 * @return string HTML of link
344 * @deprecated @since 1.17
346 function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
348 wfDeprecated( __METHOD__
);
350 $threshold = $wgUser->getStubThreshold();
351 $colour = ( $size < $threshold ) ?
'stub' : '';
352 // FIXME: replace deprecated makeColouredLinkObj by link()
353 return $this->makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
357 * Make appropriate markup for a link to the current article. This is currently rendered
358 * as the bold link text. The calling sequence is the same as the other make*LinkObj functions,
359 * despite $query not being used.
363 function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
365 $text = htmlspecialchars( $nt->getPrefixedText() );
367 list( $inside, $trail ) = Linker
::splitTrail( $trail );
368 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
371 function normaliseSpecialPage( Title
$title ) {
372 if ( $title->getNamespace() == NS_SPECIAL
) {
373 list( $name, $subpage ) = SpecialPage
::resolveAliasWithSubpage( $title->getDBkey() );
377 $ret = SpecialPage
::getTitleFor( $name, $subpage );
378 $ret->mFragment
= $title->getFragment();
386 * Returns the filename part of an url.
387 * Used as alternative text for external images.
389 function fnamePart( $url ) {
390 $basename = strrchr( $url, '/' );
391 if ( false === $basename ) {
394 $basename = substr( $basename, 1 );
400 * Return the code for images which were added via external links,
401 * via Parser::maybeMakeExternalImage().
403 function makeExternalImage( $url, $alt = '' ) {
405 $alt = $this->fnamePart( $url );
408 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
410 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
413 return Html
::element( 'img',
420 * Given parameters derived from [[Image:Foo|options...]], generate the
421 * HTML that that syntax inserts in the page.
423 * @param $title Title object
424 * @param $file File object, or false if it doesn't exist
425 * @param $frameParams Array: associative array of parameters external to the media handler.
426 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
427 * will often be false.
428 * thumbnail If present, downscale and frame
429 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
430 * framed Shows image in original size in a frame
431 * frameless Downscale but don't frame
432 * upright If present, tweak default sizes for portrait orientation
433 * upright_factor Fudge factor for "upright" tweak (default 0.75)
434 * border If present, show a border around the image
435 * align Horizontal alignment (left, right, center, none)
436 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
437 * bottom, text-bottom)
438 * alt Alternate text for image (i.e. alt attribute). Plain text.
439 * caption HTML for image caption.
440 * link-url URL to link to
441 * link-title Title object to link to
442 * link-target Value for the target attribue, only with link-url
443 * no-link Boolean, suppress description link
445 * @param $handlerParams Array: associative array of media handler parameters, to be passed
446 * to transform(). Typical keys are "width" and "page".
447 * @param $time String: timestamp of the file, set as false for current
448 * @param $query String: query params for desc url
449 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
450 * @return String: HTML for an image, with links, wrappers, etc.
452 function makeImageLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "", $widthOption = null ) {
454 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$this, &$title,
455 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
459 if ( $file && !$file->allowInlineDisplay() ) {
460 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
461 return $this->link( $title );
466 $hp =& $handlerParams;
468 // Clean up parameters
469 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
470 if ( !isset( $fp['align'] ) ) {
473 if ( !isset( $fp['alt'] ) ) {
476 if ( !isset( $fp['title'] ) ) {
480 $prefix = $postfix = '';
482 if ( 'center' == $fp['align'] ) {
483 $prefix = '<div class="center">';
485 $fp['align'] = 'none';
487 if ( $file && !isset( $hp['width'] ) ) {
488 $hp['width'] = $file->getWidth( $page );
490 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
491 global $wgThumbLimits, $wgThumbUpright;
492 if ( !isset( $widthOption ) ||
!isset( $wgThumbLimits[$widthOption] ) ) {
493 $widthOption = User
::getDefaultOption( 'thumbsize' );
496 // Reduce width for upright images when parameter 'upright' is used
497 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
498 $fp['upright'] = $wgThumbUpright;
500 // 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
501 $prefWidth = isset( $fp['upright'] ) ?
502 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
503 $wgThumbLimits[$widthOption];
505 // Use width which is smaller: real image width or user preference width
506 // Unless image is scalable vector.
507 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
508 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
509 $hp['width'] = $prefWidth;
514 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
516 # Create a thumbnail. Alignment depends on language
517 # writing direction, # right aligned for left-to-right-
518 # languages ("Western languages"), left-aligned
519 # for right-to-left-languages ("Semitic languages")
521 # If thumbnail width has not been provided, it is set
522 # to the default user option as specified in Language*.php
523 if ( $fp['align'] == '' ) {
524 $fp['align'] = $wgContLang->alignEnd();
526 return $prefix . $this->makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
529 if ( $file && isset( $fp['frameless'] ) ) {
530 $srcWidth = $file->getWidth( $page );
531 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
532 # This is the same behaviour as the "thumb" option does it already.
533 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
534 $hp['width'] = $srcWidth;
538 if ( $file && isset( $hp['width'] ) ) {
539 # Create a resized image, without the additional thumbnail features
540 $thumb = $file->transform( $hp );
546 $s = $this->makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
550 'title' => $fp['title'],
551 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
552 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
553 $params = $this->getImageLinkMTOParams( $fp, $query ) +
$params;
555 $s = $thumb->toHtml( $params );
557 if ( $fp['align'] != '' ) {
558 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
560 return str_replace( "\n", ' ', $prefix . $s . $postfix );
564 * Get the link parameters for MediaTransformOutput::toHtml() from given
565 * frame parameters supplied by the Parser.
566 * @param $frameParams The frame parameters
567 * @param $query An optional query string to add to description page links
569 function getImageLinkMTOParams( $frameParams, $query = '' ) {
570 $mtoParams = array();
571 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
572 $mtoParams['custom-url-link'] = $frameParams['link-url'];
573 if ( isset( $frameParams['link-target'] ) ) {
574 $mtoParams['custom-target-link'] = $frameParams['link-target'];
576 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
577 $mtoParams['custom-title-link'] = $this->normaliseSpecialPage( $frameParams['link-title'] );
578 } elseif ( !empty( $frameParams['no-link'] ) ) {
581 $mtoParams['desc-link'] = true;
582 $mtoParams['desc-query'] = $query;
588 * Make HTML for a thumbnail including image, border and caption
589 * @param $title Title object
590 * @param $file File object or false if it doesn't exist
591 * @param $label String
593 * @param $align String
594 * @param $params Array
595 * @param $framed Boolean
596 * @param $manualthumb String
598 function makeThumbLinkObj( Title
$title, $file, $label = '', $alt, $align = 'right', $params = array(), $framed = false , $manualthumb = "" ) {
599 $frameParams = array(
605 $frameParams['framed'] = true;
607 if ( $manualthumb ) {
608 $frameParams['manualthumb'] = $manualthumb;
610 return $this->makeThumbLink2( $title, $file, $frameParams, $params );
614 * @param $title Title
616 * @param array $frameParams
617 * @param array $handlerParams
619 * @param string $query
622 function makeThumbLink2( Title
$title, $file, $frameParams = array(), $handlerParams = array(), $time = false, $query = "" ) {
624 $exists = $file && $file->exists();
628 $hp =& $handlerParams;
630 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
631 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
632 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
633 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
634 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
636 if ( empty( $hp['width'] ) ) {
637 // Reduce width for upright images when parameter 'upright' is used
638 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
643 $outerWidth = $hp['width'] +
2;
645 if ( isset( $fp['manualthumb'] ) ) {
646 # Use manually specified thumbnail
647 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
648 if ( $manual_title ) {
649 $manual_img = wfFindFile( $manual_title );
651 $thumb = $manual_img->getUnscaledThumb( $hp );
656 } elseif ( isset( $fp['framed'] ) ) {
657 // Use image dimensions, don't scale
658 $thumb = $file->getUnscaledThumb( $hp );
660 # Do not present an image bigger than the source, for bitmap-style images
661 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
662 $srcWidth = $file->getWidth( $page );
663 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
664 $hp['width'] = $srcWidth;
666 $thumb = $file->transform( $hp );
670 $outerWidth = $thumb->getWidth() +
2;
672 $outerWidth = $hp['width'] +
2;
676 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
677 # So we don't need to pass it here in $query. However, the URL for the
678 # zoom icon still needs it, so we make a unique query for it. See bug 14771
679 $url = $title->getLocalURL( $query );
681 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
684 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
686 $s .= $this->makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
688 } elseif ( !$thumb ) {
689 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
694 'title' => $fp['title'],
695 'img-class' => 'thumbimage' );
696 $params = $this->getImageLinkMTOParams( $fp, $query ) +
$params;
697 $s .= $thumb->toHtml( $params );
698 if ( isset( $fp['framed'] ) ) {
701 $zoomIcon = '<div class="magnify">' .
702 '<a href="' . htmlspecialchars( $url ) . '" class="internal" ' .
703 'title="' . htmlspecialchars( wfMsg( 'thumbnail-more' ) ) . '">' .
704 '<img src="' . htmlspecialchars( $wgStylePath ) . '/common/images/magnify-clip.png" ' .
705 'width="15" height="11" alt="" /></a></div>';
708 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
709 return str_replace( "\n", ' ', $s );
713 * Make a "broken" link to an image
715 * @param $title Title object
716 * @param $text String: link label in unescaped text form
717 * @param $query String: query string
718 * @param $trail String: link trail (HTML fragment)
719 * @param $prefix String: link prefix (HTML fragment)
720 * @param $time Boolean: a file of a certain timestamp was requested
723 public function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
724 global $wgEnableUploads, $wgUploadMissingFileUrl;
725 if ( $title instanceof Title
) {
726 wfProfileIn( __METHOD__
);
727 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
729 list( $inside, $trail ) = self
::splitTrail( $trail );
731 $text = htmlspecialchars( $title->getPrefixedText() );
733 if ( ( $wgUploadMissingFileUrl ||
$wgEnableUploads ) && !$currentExists ) {
734 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
737 wfProfileOut( __METHOD__
);
738 return $this->linkKnown( $title, "$prefix$text$inside", array(), $query ) . $trail;
741 $href = $this->getUploadUrl( $title, $query );
743 wfProfileOut( __METHOD__
);
744 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
745 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
746 "$prefix$text$inside</a>$trail";
748 wfProfileOut( __METHOD__
);
749 return $this->linkKnown( $title, "$prefix$text$inside", array(), $query ) . $trail;
752 wfProfileOut( __METHOD__
);
753 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
758 * Get the URL to upload a certain file
760 * @param $destFile Title object of the file to upload
761 * @param $query String: urlencoded query string to prepend
762 * @return String: urlencoded URL
764 protected function getUploadUrl( $destFile, $query = '' ) {
765 global $wgUploadMissingFileUrl;
766 $q = 'wpDestFile=' . $destFile->getPartialUrl();
770 if ( $wgUploadMissingFileUrl ) {
771 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
773 $upload = SpecialPage
::getTitleFor( 'Upload' );
774 return $upload->getLocalUrl( $q );
779 * Create a direct link to a given uploaded file.
781 * @param $title Title object.
782 * @param $text String: pre-sanitized HTML
783 * @param $time string: time image was created
784 * @return String: HTML
786 * @todo Handle invalid or missing images better.
788 public function makeMediaLinkObj( $title, $text = '', $time = false ) {
789 if ( is_null( $title ) ) {
790 # # # HOTFIX. Instead of breaking, return empty string.
793 $img = wfFindFile( $title, array( 'time' => $time ) );
795 $url = $img->getURL();
798 $url = $this->getUploadUrl( $title );
801 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES
);
805 $u = htmlspecialchars( $url );
806 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
811 * Make a link to a special page given its name and, optionally,
812 * a message key from the link text.
813 * Usage example: $skin->specialLink( 'recentchanges' )
815 function specialLink( $name, $key = '' ) {
816 if ( $key == '' ) { $key = strtolower( $name ); }
818 return $this->linkKnown( SpecialPage
::getTitleFor( $name ) , wfMsg( $key ) );
822 * Make an external link
823 * @param $url String: URL to link to
824 * @param $text String: text of link
825 * @param $escape Boolean: do we escape the link text?
826 * @param $linktype String: type of external link. Gets added to the classes
827 * @param $attribs Array of extra attributes to <a>
829 function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
831 if ( isset($linktype) && $linktype ) {
832 $class .= " $linktype";
834 if ( isset($attribs['class']) && $attribs['class'] ) {
835 $class .= " {$attribs['class']}";
837 $attribs['class'] = $class;
840 $text = htmlspecialchars( $text );
843 $success = wfRunHooks( 'LinkerMakeExternalLink', array( &$url, &$text, &$link, &$attribs, $linktype ) );
845 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
848 $attribs['href'] = $url;
849 return Html
::rawElement( 'a', $attribs, $text );
853 * Make user link (or user contributions for unregistered users)
854 * @param $userId Integer: user id in database.
855 * @param $userText String: user name in database
856 * @return String: HTML fragment
859 function userLink( $userId, $userText ) {
860 if ( $userId == 0 ) {
861 $page = SpecialPage
::getTitleFor( 'Contributions', $userText );
863 $page = Title
::makeTitle( NS_USER
, $userText );
865 return $this->link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
869 * Generate standard user tool links (talk, contributions, block link, etc.)
871 * @param $userId Integer: user identifier
872 * @param $userText String: user name or IP address
873 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
874 * red if the user has no edits?
875 * @param $flags Integer: customisation flags (e.g. self::TOOL_LINKS_NOBLOCK)
876 * @param $edits Integer: user edit count (optional, for performance)
877 * @return String: HTML fragment
879 public function userToolLinks( $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null ) {
880 global $wgUser, $wgDisableAnonTalk, $wgSysopUserBans, $wgLang;
881 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
882 $blockable = ( $wgSysopUserBans ||
0 == $userId ) && !$flags & self
::TOOL_LINKS_NOBLOCK
;
886 $items[] = $this->userTalkLink( $userId, $userText );
889 // check if the user has an edit
891 if ( $redContribsWhenNoEdits ) {
892 $count = !is_null( $edits ) ?
$edits : User
::edits( $userId );
894 $attribs['class'] = 'new';
897 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
899 $items[] = $this->link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
901 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
902 $items[] = $this->blockLink( $userId, $userText );
906 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
913 * Alias for userToolLinks( $userId, $userText, true );
914 * @param $userId Integer: user identifier
915 * @param $userText String: user name or IP address
916 * @param $edits Integer: user edit count (optional, for performance)
918 public function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
919 return $this->userToolLinks( $userId, $userText, true, 0, $edits );
924 * @param $userId Integer: user id in database.
925 * @param $userText String: user name in database.
926 * @return String: HTML fragment with user talk link
929 function userTalkLink( $userId, $userText ) {
930 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
931 $userTalkLink = $this->link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
932 return $userTalkLink;
936 * @param $userId Integer: userid
937 * @param $userText String: user name in database.
938 * @return String: HTML fragment with block link
941 function blockLink( $userId, $userText ) {
942 $blockPage = SpecialPage
::getTitleFor( 'Blockip', $userText );
943 $blockLink = $this->link( $blockPage, wfMsgHtml( 'blocklink' ) );
948 * Generate a user link if the current user is allowed to view it
949 * @param $rev Revision object.
950 * @param $isPublic Boolean: show only if all users can see it
951 * @return String: HTML fragment
953 function revUserLink( $rev, $isPublic = false ) {
954 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
955 $link = wfMsgHtml( 'rev-deleted-user' );
956 } else if ( $rev->userCan( Revision
::DELETED_USER
) ) {
957 $link = $this->userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
958 $rev->getUserText( Revision
::FOR_THIS_USER
) );
960 $link = wfMsgHtml( 'rev-deleted-user' );
962 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
963 return '<span class="history-deleted">' . $link . '</span>';
969 * Generate a user tool link cluster if the current user is allowed to view it
970 * @param $rev Revision object.
971 * @param $isPublic Boolean: show only if all users can see it
972 * @return string HTML
974 function revUserTools( $rev, $isPublic = false ) {
975 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
976 $link = wfMsgHtml( 'rev-deleted-user' );
977 } else if ( $rev->userCan( Revision
::DELETED_USER
) ) {
978 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
979 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
980 $link = $this->userLink( $userId, $userText ) .
981 ' ' . $this->userToolLinks( $userId, $userText );
983 $link = wfMsgHtml( 'rev-deleted-user' );
985 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
986 return ' <span class="history-deleted">' . $link . '</span>';
992 * This function is called by all recent changes variants, by the page history,
993 * and by the user contributions list. It is responsible for formatting edit
994 * comments. It escapes any HTML in the comment, but adds some CSS to format
995 * auto-generated comments (from section editing) and formats [[wikilinks]].
997 * @author Erik Moeller <moeller@scireview.de>
999 * Note: there's not always a title to pass to this function.
1000 * Since you can't set a default parameter for a reference, I've turned it
1001 * temporarily to a value pass. Should be adjusted further. --brion
1003 * @param $comment String
1004 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1005 * @param $local Boolean: whether section links should refer to local page
1007 function formatComment( $comment, $title = null, $local = false ) {
1008 wfProfileIn( __METHOD__
);
1010 # Sanitize text a bit:
1011 $comment = str_replace( "\n", " ", $comment );
1012 # Allow HTML entities (for bug 13815)
1013 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1015 # Render autocomments and make links:
1016 $comment = $this->formatAutocomments( $comment, $title, $local );
1017 $comment = $this->formatLinksInComment( $comment, $title, $local );
1019 wfProfileOut( __METHOD__
);
1024 * The pattern for autogen comments is / * foo * /, which makes for
1026 * We look for all comments, match any text before and after the comment,
1027 * add a separator where needed and format the comment itself with CSS
1028 * Called by Linker::formatComment.
1030 * @param $comment String: comment text
1031 * @param $title An optional title object used to links to sections
1032 * @param $local Boolean: whether section links should refer to local page
1033 * @return String: formatted comment
1035 private function formatAutocomments( $comment, $title = null, $local = false ) {
1037 $this->autocommentTitle
= $title;
1038 $this->autocommentLocal
= $local;
1039 $comment = preg_replace_callback(
1040 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1041 array( $this, 'formatAutocommentsCallback' ),
1043 unset( $this->autocommentTitle
);
1044 unset( $this->autocommentLocal
);
1048 private function formatAutocommentsCallback( $match ) {
1049 $title = $this->autocommentTitle
;
1050 $local = $this->autocommentLocal
;
1059 # Remove links that a user may have manually put in the autosummary
1060 # This could be improved by copying as much of Parser::stripSectionName as desired.
1061 $section = str_replace( '[[:', '', $section );
1062 $section = str_replace( '[[', '', $section );
1063 $section = str_replace( ']]', '', $section );
1065 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1067 $sectionTitle = Title
::newFromText( '#' . $section );
1069 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1070 $title->getDBkey(), $section );
1072 if ( $sectionTitle ) {
1073 $link = $this->link( $sectionTitle,
1074 htmlspecialchars( wfMsgForContent( 'sectionlink' ) ), array(), array(),
1080 $auto = "$link$auto";
1082 # written summary $presep autocomment (summary /* section */)
1083 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1086 # autocomment $postsep written summary (/* section */ summary)
1087 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1089 $auto = '<span class="autocomment">' . $auto . '</span>';
1090 $comment = $pre . $auto . $post;
1095 * Formats wiki links and media links in text; all other wiki formatting
1098 * @todo Fixme: doesn't handle sub-links as in image thumb texts like the main parser
1099 * @param $comment String: text to format links in
1100 * @param $title An optional title object used to links to sections
1101 * @param $local Boolean: whether section links should refer to local page
1104 public function formatLinksInComment( $comment, $title = null, $local = false ) {
1105 $this->commentContextTitle
= $title;
1106 $this->commentLocal
= $local;
1107 $html = preg_replace_callback(
1108 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1109 array( $this, 'formatLinksInCommentCallback' ),
1111 unset( $this->commentContextTitle
);
1112 unset( $this->commentLocal
);
1116 protected function formatLinksInCommentCallback( $match ) {
1119 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1120 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1122 $comment = $match[0];
1124 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1125 if ( strpos( $match[1], '%' ) !== false ) {
1126 $match[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $match[1] ) );
1129 # Handle link renaming [[foo|text]] will show link as "text"
1130 if ( $match[3] != "" ) {
1135 $submatch = array();
1137 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1138 # Media link; trail not supported.
1139 $linkRegexp = '/\[\[(.*?)\]\]/';
1140 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1141 $thelink = $this->makeMediaLinkObj( $title, $text );
1143 # Other kind of link
1144 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1145 $trail = $submatch[1];
1149 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1150 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1151 $match[1] = substr( $match[1], 1 );
1152 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1155 $linkTarget = Linker
::normalizeSubpageLink( $this->commentContextTitle
,
1156 $match[1], $linkText );
1158 $target = Title
::newFromText( $linkTarget );
1160 if ( $target->getText() == '' && $target->getInterwiki() === ''
1161 && !$this->commentLocal
&& $this->commentContextTitle
)
1163 $newTarget = clone ( $this->commentContextTitle
);
1164 $newTarget->setFragment( '#' . $target->getFragment() );
1165 $target = $newTarget;
1167 $thelink = $this->link(
1174 // If the link is still valid, go ahead and replace it in!
1175 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1183 * @param $contextTitle Title
1188 static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1191 # :Foobar -- override special treatment of prefix (images, language links)
1192 # /Foobar -- convert to CurrentPage/Foobar
1193 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1194 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1195 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1197 wfProfileIn( __METHOD__
);
1198 $ret = $target; # default return value is no change
1200 # Some namespaces don't allow subpages,
1201 # so only perform processing if subpages are allowed
1202 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1203 $hash = strpos( $target, '#' );
1204 if ( $hash !== false ) {
1205 $suffix = substr( $target, $hash );
1206 $target = substr( $target, 0, $hash );
1211 $target = trim( $target );
1212 # Look at the first character
1213 if ( $target != '' && $target { 0 } === '/' ) {
1214 # / at end means we don't want the slash to be shown
1216 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1217 if ( $trailingSlashes ) {
1218 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1220 $noslash = substr( $target, 1 );
1223 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1224 if ( $text === '' ) {
1225 $text = $target . $suffix;
1226 } # this might be changed for ugliness reasons
1228 # check for .. subpage backlinks
1230 $nodotdot = $target;
1231 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1233 $nodotdot = substr( $nodotdot, 3 );
1235 if ( $dotdotcount > 0 ) {
1236 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1237 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1238 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1239 # / at the end means don't show full path
1240 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1241 $nodotdot = substr( $nodotdot, 0, -1 );
1242 if ( $text === '' ) {
1243 $text = $nodotdot . $suffix;
1246 $nodotdot = trim( $nodotdot );
1247 if ( $nodotdot != '' ) {
1248 $ret .= '/' . $nodotdot;
1256 wfProfileOut( __METHOD__
);
1261 * Wrap a comment in standard punctuation and formatting if
1262 * it's non-empty, otherwise return empty string.
1264 * @param $comment String
1265 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1266 * @param $local Boolean: whether section links should refer to local page
1270 function commentBlock( $comment, $title = null, $local = false ) {
1271 // '*' used to be the comment inserted by the software way back
1272 // in antiquity in case none was provided, here for backwards
1273 // compatability, acc. to brion -ævar
1274 if ( $comment == '' ||
$comment == '*' ) {
1277 $formatted = $this->formatComment( $comment, $title, $local );
1278 return " <span class=\"comment\">($formatted)</span>";
1283 * Wrap and format the given revision's comment block, if the current
1284 * user is allowed to view it.
1286 * @param $rev Revision object
1287 * @param $local Boolean: whether section links should refer to local page
1288 * @param $isPublic Boolean: show only if all users can see it
1289 * @return String: HTML fragment
1291 function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1292 if ( $rev->getRawComment() == "" ) {
1295 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1296 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1297 } else if ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1298 $block = $this->commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1299 $rev->getTitle(), $local );
1301 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1303 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1304 return " <span class=\"history-deleted\">$block</span>";
1309 public function formatRevisionSize( $size ) {
1311 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1314 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1317 $stxt = htmlspecialchars( $stxt );
1318 return "<span class=\"history-size\">$stxt</span>";
1322 * Add another level to the Table of Contents
1324 function tocIndent() {
1329 * Finish one or more sublevels on the Table of Contents
1331 function tocUnindent( $level ) {
1332 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1336 * parameter level defines if we are on an indentation level
1338 function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1339 $classes = "toclevel-$level";
1340 if ( $sectionIndex !== false )
1341 $classes .= " tocsection-$sectionIndex";
1342 return "\n<li class=\"$classes\"><a href=\"#" .
1343 $anchor . '"><span class="tocnumber">' .
1344 $tocnumber . '</span> <span class="toctext">' .
1345 $tocline . '</span></a>';
1349 * End a Table Of Contents line.
1350 * tocUnindent() will be used instead if we're ending a line below
1353 function tocLineEnd() {
1358 * Wraps the TOC in a table and provides the hide/collapse javascript.
1360 * @param $toc String: html of the Table Of Contents
1361 * @param $lang mixed: Language code for the toc title
1362 * @return String: full html of the TOC
1364 function tocList( $toc, $lang = false ) {
1365 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1367 '<table id="toc" class="toc"><tr><td>'
1368 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1370 . "</ul>\n</td></tr></table>\n";
1374 * Generate a table of contents from a section tree
1377 * @param $tree Return value of ParserOutput::getSections()
1378 * @return String: HTML fragment
1380 public function generateTOC( $tree ) {
1383 foreach ( $tree as $section ) {
1384 if ( $section['toclevel'] > $lastLevel )
1385 $toc .= $this->tocIndent();
1386 else if ( $section['toclevel'] < $lastLevel )
1387 $toc .= $this->tocUnindent(
1388 $lastLevel - $section['toclevel'] );
1390 $toc .= $this->tocLineEnd();
1392 $toc .= $this->tocLine( $section['anchor'],
1393 $section['line'], $section['number'],
1394 $section['toclevel'], $section['index'] );
1395 $lastLevel = $section['toclevel'];
1397 $toc .= $this->tocLineEnd();
1398 return $this->tocList( $toc );
1402 * Create a section edit link. This supersedes editSectionLink() and
1403 * editSectionLinkForOther().
1405 * @param $nt Title The title being linked to (may not be the same as
1406 * $wgTitle, if the section is included from a template)
1407 * @param $section string The designation of the section being pointed to,
1408 * to be included in the link, like "§ion=$section"
1409 * @param $tooltip string The tooltip to use for the link: will be escaped
1410 * and wrapped in the 'editsectionhint' message
1411 * @param $lang string Language code
1412 * @return string HTML to use for edit link
1414 public function doEditSectionLink( Title
$nt, $section, $tooltip = null, $lang = false ) {
1415 // HTML generated here should probably have userlangattributes
1416 // added to it for LTR text on RTL pages
1418 if ( !is_null( $tooltip ) ) {
1419 # Bug 25462: undo double-escaping.
1420 $tooltip = Sanitizer
::decodeCharReferences( $tooltip );
1421 $attribs['title'] = wfMsgReal( 'editsectionhint', array( $tooltip ), true, $lang );
1423 $link = $this->link( $nt, wfMsgExt( 'editsection', array( 'language' => $lang ) ),
1425 array( 'action' => 'edit', 'section' => $section ),
1426 array( 'noclasses', 'known' )
1429 # Run the old hook. This takes up half of the function . . . hopefully
1430 # we can rid of it someday.
1433 $attribs = htmlspecialchars( wfMsgReal( 'editsectionhint', array( $tooltip ), true, $lang ) );
1434 $attribs = " title=\"$attribs\"";
1437 wfRunHooks( 'EditSectionLink', array( &$this, $nt, $section, $attribs, $link, &$result, $lang ) );
1438 if ( !is_null( $result ) ) {
1439 # For reverse compatibility, add the brackets *after* the hook is
1440 # run, and even add them to hook-provided text. (This is the main
1441 # reason that the EditSectionLink hook is deprecated in favor of
1442 # DoEditSectionLink: it can't change the brackets or the span.)
1443 $result = wfMsgExt( 'editsection-brackets', array( 'escape', 'replaceafter', 'language' => $lang ), $result );
1444 return "<span class=\"editsection\">$result</span>";
1447 # Add the brackets and the span, and *then* run the nice new hook, with
1448 # clean and non-redundant arguments.
1449 $result = wfMsgExt( 'editsection-brackets', array( 'escape', 'replaceafter', 'language' => $lang ), $link );
1450 $result = "<span class=\"editsection\">$result</span>";
1452 wfRunHooks( 'DoEditSectionLink', array( $this, $nt, $section, $tooltip, &$result, $lang ) );
1457 * Create a headline for content
1459 * @param $level Integer: the level of the headline (1-6)
1460 * @param $attribs String: any attributes for the headline, starting with
1461 * a space and ending with '>'
1462 * This *must* be at least '>' for no attribs
1463 * @param $anchor String: the anchor to give the headline (the bit after the #)
1464 * @param $text String: the text of the header
1465 * @param $link String: HTML to add for the section edit link
1466 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1467 * backward compatibility (false to omit)
1469 * @return String: HTML headline
1471 public function makeHeadline( $level, $attribs, $anchor, $text, $link, $legacyAnchor = false ) {
1472 $ret = "<h$level$attribs"
1474 . " <span class=\"mw-headline\" id=\"$anchor\">$text</span>"
1476 if ( $legacyAnchor !== false ) {
1477 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1483 * Split a link trail, return the "inside" portion and the remainder of the trail
1484 * as a two-element array
1486 static function splitTrail( $trail ) {
1487 static $regex = false;
1488 if ( $regex === false ) {
1490 $regex = $wgContLang->linkTrail();
1493 if ( $trail !== '' ) {
1495 if ( preg_match( $regex, $trail, $m ) ) {
1500 return array( $inside, $trail );
1504 * Generate a rollback link for a given revision. Currently it's the
1505 * caller's responsibility to ensure that the revision is the top one. If
1506 * it's not, of course, the user will get an error message.
1508 * If the calling page is called with the parameter &bot=1, all rollback
1509 * links also get that parameter. It causes the edit itself and the rollback
1510 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1511 * changes, so this allows sysops to combat a busy vandal without bothering
1514 * @param $rev Revision object
1516 function generateRollback( $rev ) {
1517 return '<span class="mw-rollback-link">['
1518 . $this->buildRollbackLink( $rev )
1523 * Build a raw rollback link, useful for collections of "tool" links
1525 * @param $rev Revision object
1526 * @return String: HTML fragment
1528 public function buildRollbackLink( $rev ) {
1529 global $wgRequest, $wgUser;
1530 $title = $rev->getTitle();
1532 'action' => 'rollback',
1533 'from' => $rev->getUserText(),
1534 'token' => $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1536 if ( $wgRequest->getBool( 'bot' ) ) {
1537 $query['bot'] = '1';
1538 $query['hidediff'] = '1'; // bug 15999
1542 wfMsgHtml( 'rollbacklink' ),
1543 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1545 array( 'known', 'noclasses' )
1550 * Returns HTML for the "templates used on this page" list.
1552 * @param $templates Array of templates from Article::getUsedTemplate
1554 * @param $preview Boolean: whether this is for a preview
1555 * @param $section Boolean: whether this is for a section edit
1556 * @return String: HTML output
1558 public function formatTemplates( $templates, $preview = false, $section = false ) {
1559 wfProfileIn( __METHOD__
);
1562 if ( count( $templates ) > 0 ) {
1563 # Do a batch existence check
1564 $batch = new LinkBatch
;
1565 foreach ( $templates as $title ) {
1566 $batch->addObj( $title );
1570 # Construct the HTML
1571 $outText = '<div class="mw-templatesUsedExplanation">';
1573 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1574 } elseif ( $section ) {
1575 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1577 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1579 $outText .= "</div><ul>\n";
1581 usort( $templates, array( 'Title', 'compare' ) );
1582 foreach ( $templates as $titleObj ) {
1583 $r = $titleObj->getRestrictions( 'edit' );
1584 if ( in_array( 'sysop', $r ) ) {
1585 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1586 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1587 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1591 if ( $titleObj->quickUserCan( 'edit' ) ) {
1592 $editLink = $this->link(
1594 wfMsg( 'editlink' ),
1596 array( 'action' => 'edit' )
1599 $editLink = $this->link(
1601 wfMsg( 'viewsourcelink' ),
1603 array( 'action' => 'edit' )
1606 $outText .= '<li>' . $this->link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1608 $outText .= '</ul>';
1610 wfProfileOut( __METHOD__
);
1615 * Returns HTML for the "hidden categories on this page" list.
1617 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1619 * @return String: HTML output
1621 public function formatHiddenCategories( $hiddencats ) {
1623 wfProfileIn( __METHOD__
);
1626 if ( count( $hiddencats ) > 0 ) {
1627 # Construct the HTML
1628 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1629 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1630 $outText .= "</div><ul>\n";
1632 foreach ( $hiddencats as $titleObj ) {
1633 $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
1635 $outText .= '</ul>';
1637 wfProfileOut( __METHOD__
);
1642 * Format a size in bytes for output, using an appropriate
1643 * unit (B, KB, MB or GB) according to the magnitude in question
1645 * @param $size Size to format
1648 public function formatSize( $size ) {
1650 return htmlspecialchars( $wgLang->formatSize( $size ) );
1654 * Given the id of an interface element, constructs the appropriate title
1655 * attribute from the system messages. (Note, this is usually the id but
1656 * isn't always, because sometimes the accesskey needs to go on a different
1657 * element than the id, for reverse-compatibility, etc.)
1659 * @param $name String: id of the element, minus prefixes.
1660 * @param $options Mixed: null or the string 'withaccess' to add an access-
1662 * @return String: contents of the title attribute (which you must HTML-
1663 * escape), or false for no title attribute
1665 public function titleAttrib( $name, $options = null ) {
1666 wfProfileIn( __METHOD__
);
1668 $message = wfMessage( "tooltip-$name" );
1670 if ( !$message->exists() ) {
1673 $tooltip = $message->text();
1674 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1675 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1676 # Message equal to '-' means suppress it.
1677 if ( $tooltip == '-' ) {
1682 if ( $options == 'withaccess' ) {
1683 $accesskey = $this->accesskey( $name );
1684 if ( $accesskey !== false ) {
1685 if ( $tooltip === false ||
$tooltip === '' ) {
1686 $tooltip = "[$accesskey]";
1688 $tooltip .= " [$accesskey]";
1693 wfProfileOut( __METHOD__
);
1698 * Given the id of an interface element, constructs the appropriate
1699 * accesskey attribute from the system messages. (Note, this is usually
1700 * the id but isn't always, because sometimes the accesskey needs to go on
1701 * a different element than the id, for reverse-compatibility, etc.)
1703 * @param $name String: id of the element, minus prefixes.
1704 * @return String: contents of the accesskey attribute (which you must HTML-
1705 * escape), or false for no accesskey attribute
1707 public function accesskey( $name ) {
1708 if ( isset( $this->accesskeycache
[$name] ) ) {
1709 return $this->accesskeycache
[$name];
1711 wfProfileIn( __METHOD__
);
1713 $message = wfMessage( "accesskey-$name" );
1715 if ( !$message->exists() ) {
1718 $accesskey = $message->plain();
1719 if ( $accesskey === '' ||
$accesskey === '-' ) {
1720 # FIXME: Per standard MW behavior, a value of '-' means to suppress the
1721 # attribute, but this is broken for accesskey: that might be a useful
1727 wfProfileOut( __METHOD__
);
1728 return $this->accesskeycache
[$name] = $accesskey;
1732 * Creates a (show/hide) link for deleting revisions/log entries
1734 * @param $query Array: query parameters to be passed to link()
1735 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1736 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1738 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1739 * span to allow for customization of appearance with CSS
1741 public function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1742 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1743 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1744 $tag = $restricted ?
'strong' : 'span';
1745 $link = $this->link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1746 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1750 * Creates a dead (show/hide) link for deleting revisions/log entries
1752 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1754 * @return string HTML text wrapped in a span to allow for customization
1755 * of appearance with CSS
1757 public function revDeleteLinkDisabled( $delete = true ) {
1758 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1759 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($text)" );
1762 /* Deprecated methods */
1765 * @deprecated @since 1.16 Use link()
1767 * This function is a shortcut to makeLinkObj(Title::newFromText($title),...). Do not call
1768 * it if you already have a title object handy. See makeLinkObj for further documentation.
1770 * @param $title String: the text of the title
1771 * @param $text String: link text
1772 * @param $query String: optional query part
1773 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1774 * be included in the link text. Other characters will be appended after
1775 * the end of the link.
1777 function makeLink( $title, $text = '', $query = '', $trail = '' ) {
1778 wfProfileIn( __METHOD__
);
1779 $nt = Title
::newFromText( $title );
1780 if ( $nt instanceof Title
) {
1781 $result = $this->makeLinkObj( $nt, $text, $query, $trail );
1783 wfDebug( 'Invalid title passed to Linker::makeLink(): "' . $title . "\"\n" );
1784 $result = $text == "" ?
$title : $text;
1787 wfProfileOut( __METHOD__
);
1792 * @deprecated @since 1.16 Use link()
1794 * This function is a shortcut to makeKnownLinkObj(Title::newFromText($title),...). Do not call
1795 * it if you already have a title object handy. See makeKnownLinkObj for further documentation.
1797 * @param $title String: the text of the title
1798 * @param $text String: link text
1799 * @param $query String: optional query part
1800 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1801 * be included in the link text. Other characters will be appended after
1802 * the end of the link.
1803 * @param $prefix String: Optional prefix
1804 * @param $aprops String: extra attributes to the a-element
1806 function makeKnownLink( $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = '' ) {
1807 $nt = Title
::newFromText( $title );
1808 if ( $nt instanceof Title
) {
1809 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix , $aprops );
1811 wfDebug( 'Invalid title passed to Linker::makeKnownLink(): "' . $title . "\"\n" );
1812 return $text == '' ?
$title : $text;
1817 * @deprecated @since 1.16 Use link()
1819 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1820 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1822 * @param $title String: The text of the title
1823 * @param $text String: Link text
1824 * @param $query String: Optional query part
1825 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1826 * be included in the link text. Other characters will be appended after
1827 * the end of the link.
1829 function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1830 $nt = Title
::newFromText( $title );
1831 if ( $nt instanceof Title
) {
1832 return $this->makeBrokenLinkObj( $nt, $text, $query, $trail );
1834 wfDebug( 'Invalid title passed to Linker::makeBrokenLink(): "' . $title . "\"\n" );
1835 return $text == '' ?
$title : $text;
1840 * @deprecated @since 1.16 Use link()
1842 * This function is a shortcut to makeStubLinkObj(Title::newFromText($title),...). Do not call
1843 * it if you already have a title object handy. See makeStubLinkObj for further documentation.
1845 * @param $title String: the text of the title
1846 * @param $text String: link text
1847 * @param $query String: optional query part
1848 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1849 * be included in the link text. Other characters will be appended after
1850 * the end of the link.
1852 function makeStubLink( $title, $text = '', $query = '', $trail = '' ) {
1853 wfDeprecated( __METHOD__
);
1854 $nt = Title
::newFromText( $title );
1855 if ( $nt instanceof Title
) {
1856 return $this->makeStubLinkObj( $nt, $text, $query, $trail );
1858 wfDebug( 'Invalid title passed to Linker::makeStubLink(): "' . $title . "\"\n" );
1859 return $text == '' ?
$title : $text;
1864 * @deprecated @since 1.16 Use link()
1866 * Make a link for a title which may or may not be in the database. If you need to
1867 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1868 * call to this will result in a DB query.
1870 * @param $nt Title: the title object to make the link from, e.g. from
1871 * Title::newFromText.
1872 * @param $text String: link text
1873 * @param $query String: optional query part
1874 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1875 * be included in the link text. Other characters will be appended after
1876 * the end of the link.
1877 * @param $prefix String: optional prefix. As trail, only before instead of after.
1879 function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1880 wfProfileIn( __METHOD__
);
1881 $query = wfCgiToArray( $query );
1882 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1883 if ( $text === '' ) {
1884 $text = $this->linkText( $nt );
1887 $ret = $this->link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1889 wfProfileOut( __METHOD__
);
1894 * @deprecated @since 1.16 Use link()
1896 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1897 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1900 * @param $title Title object of target page
1901 * @param $text String: text to replace the title
1902 * @param $query String: link target
1903 * @param $trail String: text after link
1904 * @param $prefix String: text before link text
1905 * @param $aprops String: extra attributes to the a-element
1906 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1907 * @return the a-element
1909 function makeKnownLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = '' ) {
1910 wfProfileIn( __METHOD__
);
1912 if ( $text == '' ) {
1913 $text = $this->linkText( $title );
1915 $attribs = Sanitizer
::mergeAttributes(
1916 Sanitizer
::decodeTagAttributes( $aprops ),
1917 Sanitizer
::decodeTagAttributes( $style )
1919 $query = wfCgiToArray( $query );
1920 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1922 $ret = $this->link( $title, "$prefix$text$inside", $attribs, $query,
1923 array( 'known', 'noclasses' ) ) . $trail;
1925 wfProfileOut( __METHOD__
);
1930 * @deprecated @since 1.16 Use link()
1932 * Make a red link to the edit page of a given title.
1934 * @param $title Title object of the target page
1935 * @param $text String: Link text
1936 * @param $query String: Optional query part
1937 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1938 * be included in the link text. Other characters will be appended after
1939 * the end of the link.
1940 * @param $prefix String: Optional prefix
1942 function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
1943 wfProfileIn( __METHOD__
);
1945 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1946 if ( $text === '' ) {
1947 $text = $this->linkText( $title );
1950 $ret = $this->link( $title, "$prefix$text$inside", array(),
1951 wfCgiToArray( $query ), 'broken' ) . $trail;
1953 wfProfileOut( __METHOD__
);
1958 * @deprecated @since 1.16 Use link()
1960 * Make a brown link to a short article.
1962 * @param $nt Title object of the target page
1963 * @param $text String: link text
1964 * @param $query String: optional query part
1965 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1966 * be included in the link text. Other characters will be appended after
1967 * the end of the link.
1968 * @param $prefix String: Optional prefix
1970 function makeStubLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1971 return $this->makeColouredLinkObj( $nt, 'stub', $text, $query, $trail, $prefix );
1975 * @deprecated @since 1.16 Use link()
1977 * Make a coloured link.
1979 * @param $nt Title object of the target page
1980 * @param $colour Integer: colour of the link
1981 * @param $text String: link text
1982 * @param $query String: optional query part
1983 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1984 * be included in the link text. Other characters will be appended after
1985 * the end of the link.
1986 * @param $prefix String: Optional prefix
1988 function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
1989 if ( $colour != '' ) {
1990 $style = $this->getInternalLinkAttributesObj( $nt, $text, $colour );
1994 return $this->makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
1997 /** Obsolete alias */
1998 function makeImage( $url, $alt = '' ) {
1999 wfDeprecated( __METHOD__
);
2000 return $this->makeExternalImage( $url, $alt );
2004 * Creates the HTML source for images
2005 * @deprecated @since 1.16 use makeImageLink2
2007 * @param $title Title object
2008 * @param $label String: label text
2009 * @param $alt String: alt text
2010 * @param $align String: horizontal alignment: none, left, center, right)
2011 * @param $handlerParams Array: parameters to be passed to the media handler
2012 * @param $framed Boolean: shows image in original size in a frame
2013 * @param $thumb Boolean: shows image as thumbnail in a frame
2014 * @param $manualthumb String: image name for the manual thumbnail
2015 * @param $valign String: vertical alignment: baseline, sub, super, top, text-top, middle, bottom, text-bottom
2016 * @param $time String: timestamp of the file, set as false for current
2019 function makeImageLinkObj( $title, $label, $alt, $align = '', $handlerParams = array(), $framed = false,
2020 $thumb = false, $manualthumb = '', $valign = '', $time = false ) {
2021 $frameParams = array( 'alt' => $alt, 'caption' => $label );
2023 $frameParams['align'] = $align;
2026 $frameParams['framed'] = true;
2029 $frameParams['thumbnail'] = true;
2031 if ( $manualthumb ) {
2032 $frameParams['manualthumb'] = $manualthumb;
2035 $frameParams['valign'] = $valign;
2037 $file = wfFindFile( $title, array( 'time' => $time ) );
2038 return $this->makeImageLink2( $title, $file, $frameParams, $handlerParams, $time );
2041 /** @deprecated use Linker::makeMediaLinkObj() */
2042 function makeMediaLink( $name, $unused = '', $text = '', $time = false ) {
2043 $nt = Title
::makeTitleSafe( NS_FILE
, $name );
2044 return $this->makeMediaLinkObj( $nt, $text, $time );
2048 * Returns the attributes for the tooltip and access key.
2050 public function tooltipAndAccesskeyAttribs( $name ) {
2051 global $wgEnableTooltipsAndAccesskeys;
2052 if ( !$wgEnableTooltipsAndAccesskeys )
2054 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2055 # no attribute" instead of "output '' as value for attribute", this
2056 # would be three lines.
2058 'title' => $this->titleAttrib( $name, 'withaccess' ),
2059 'accesskey' => $this->accesskey( $name )
2061 if ( $attribs['title'] === false ) {
2062 unset( $attribs['title'] );
2064 if ( $attribs['accesskey'] === false ) {
2065 unset( $attribs['accesskey'] );
2071 * @deprecated @since 1.14
2072 * Returns raw bits of HTML, use titleAttrib() and accesskey()
2074 public function tooltipAndAccesskey( $name ) {
2075 return Xml
::expandAttributes( $this->tooltipAndAccesskeyAttribs( $name ) );
2079 * @deprecated @since 1.14
2080 * Returns raw bits of HTML, use titleAttrib()
2082 public function tooltip( $name, $options = null ) {
2083 global $wgEnableTooltipsAndAccesskeys;
2084 if ( !$wgEnableTooltipsAndAccesskeys )
2086 # FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2087 # no attribute" instead of "output '' as value for attribute", this
2088 # would be two lines.
2089 $tooltip = $this->titleAttrib( $name, $options );
2090 if ( $tooltip === false ) {
2093 return Xml
::expandAttributes( array(
2094 'title' => $this->titleAttrib( $name, $options )