3 * Some internal bits split of from Skin.php. These functions are used
4 * for primarily page content: links, embedded images, table of contents. Links
5 * are also used in the skin.
12 * Flags for userToolLinks()
14 const TOOL_LINKS_NOBLOCK
= 1;
17 * Get the appropriate HTML attributes to add to the "a" element of an ex-
18 * ternal link, as created by [wikisyntax].
20 * @param $class String: the contents of the class attribute; if an empty
21 * string is passed, which is the default value, defaults to 'external'.
22 * @deprecated since 1.18 Just pass the external class directly to something using Html::expandAttributes
24 static function getExternalLinkAttributes( $class = 'external' ) {
25 wfDeprecated( __METHOD__
);
26 return self
::getLinkAttributesInternal( '', $class );
30 * Get the appropriate HTML attributes to add to the "a" element of an in-
33 * @param $title String: the title text for the link, URL-encoded (???) but
35 * @param $unused String: unused
36 * @param $class String: the contents of the class attribute; if an empty
37 * string is passed, which is the default value, defaults to 'external'.
39 static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
42 # @todo FIXME: We have a whole bunch of handling here that doesn't happen in
43 # getExternalLinkAttributes, why?
44 $title = urldecode( $title );
45 $title = $wgContLang->checkTitleEncoding( $title );
46 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
48 return self
::getLinkAttributesInternal( $title, $class );
52 * Get the appropriate HTML attributes to add to the "a" element of an in-
55 * @param $title String: the title text for the link, URL-encoded (???) but
57 * @param $unused String: unused
58 * @param $class String: the contents of the class attribute, default none
60 static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
61 $title = urldecode( $title );
62 $title = str_replace( '_', ' ', $title );
63 return self
::getLinkAttributesInternal( $title, $class );
67 * Get the appropriate HTML attributes to add to the "a" element of an in-
68 * ternal link, given the Title object for the page we want to link to.
71 * @param $unused String: unused
72 * @param $class String: the contents of the class attribute, default none
73 * @param $title Mixed: optional (unescaped) string to use in the title
74 * attribute; if false, default to the name of the page we're linking to
76 static function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
77 if ( $title === false ) {
78 $title = $nt->getPrefixedText();
80 return self
::getLinkAttributesInternal( $title, $class );
84 * Common code for getLinkAttributesX functions
86 * @param $title string
87 * @param $class string
91 private static function getLinkAttributesInternal( $title, $class ) {
92 $title = htmlspecialchars( $title );
93 $class = htmlspecialchars( $class );
96 $r .= " class=\"$class\"";
99 $r .= " title=\"$title\"";
105 * Return the CSS colour of a known link
107 * @param $t Title object
108 * @param $threshold Integer: user defined threshold
109 * @return String: CSS class
111 static function getLinkColour( $t, $threshold ) {
113 if ( $t->isRedirect() ) {
115 $colour = 'mw-redirect';
116 } elseif ( $threshold > 0 &&
117 $t->exists() && $t->getLength() < $threshold &&
118 $t->isContentPage() ) {
126 * This function returns an HTML link to the given target. It serves a few
128 * 1) If $target is a Title, the correct URL to link to will be figured
130 * 2) It automatically adds the usual classes for various types of link
131 * targets: "new" for red links, "stub" for short articles, etc.
132 * 3) It escapes all attribute values safely so there's no risk of XSS.
133 * 4) It provides a default tooltip if the target is a Title (the page
134 * name of the target).
135 * link() replaces the old functions in the makeLink() family.
137 * @param $target Title Can currently only be a Title, but this may
138 * change to support Images, literal URLs, etc.
139 * @param $text string The HTML contents of the <a> element, i.e.,
140 * the link text. This is raw HTML and will not be escaped. If null,
141 * defaults to the prefixed text of the Title; or if the Title is just a
142 * fragment, the contents of the fragment.
143 * @param $customAttribs array A key => value array of extra HTML attri-
144 * butes, such as title and class. (href is ignored.) Classes will be
145 * merged with the default classes, while other attributes will replace
146 * default attributes. All passed attribute values will be HTML-escaped.
147 * A false attribute value means to suppress that attribute.
148 * @param $query array The query string to append to the URL
149 * you're linking to, in key => value array form. Query keys and values
150 * will be URL-encoded.
151 * @param $options string|array String or array of strings:
152 * 'known': Page is known to exist, so don't check if it does.
153 * 'broken': Page is known not to exist, so don't check if it does.
154 * 'noclasses': Don't add any classes automatically (includes "new",
155 * "stub", "mw-redirect", "extiw"). Only use the class attribute
156 * provided, if any, so you get a simple blue link with no funny i-
158 * 'forcearticlepath': Use the article path always, even with a querystring.
159 * Has compatibility issues on some setups, so avoid wherever possible.
160 * @return string HTML <a> attribute
162 public static function link(
163 $target, $html = null, $customAttribs = array(), $query = array(), $options = array()
165 wfProfileIn( __METHOD__
);
166 if ( !$target instanceof Title
) {
167 wfProfileOut( __METHOD__
);
168 return "<!-- ERROR -->$html";
170 $options = (array)$options;
172 $dummy = new DummyLinker
; // dummy linker instance for bc on the hooks
175 if ( !wfRunHooks( 'LinkBegin', array( $dummy, $target, &$html,
176 &$customAttribs, &$query, &$options, &$ret ) ) ) {
177 wfProfileOut( __METHOD__
);
181 # Normalize the Title if it's a special page
182 $target = self
::normaliseSpecialPage( $target );
184 # If we don't know whether the page exists, let's find out.
185 wfProfileIn( __METHOD__
. '-checkPageExistence' );
186 if ( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
187 if ( $target->isKnown() ) {
188 $options[] = 'known';
190 $options[] = 'broken';
193 wfProfileOut( __METHOD__
. '-checkPageExistence' );
196 if ( in_array( "forcearticlepath", $options ) && $query ) {
201 # Note: we want the href attribute first, for prettiness.
202 $attribs = array( 'href' => self
::linkUrl( $target, $query, $options ) );
203 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
204 $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
207 $attribs = array_merge(
209 self
::linkAttribs( $target, $customAttribs, $options )
211 if ( is_null( $html ) ) {
212 $html = self
::linkText( $target );
216 if ( wfRunHooks( 'LinkEnd', array( $dummy, $target, $options, &$html, &$attribs, &$ret ) ) ) {
217 $ret = Html
::rawElement( 'a', $attribs, $html );
220 wfProfileOut( __METHOD__
);
225 * Identical to link(), except $options defaults to 'known'.
227 public static function linkKnown(
228 $target, $text = null, $customAttribs = array(),
229 $query = array(), $options = array( 'known', 'noclasses' ) )
231 return self
::link( $target, $text, $customAttribs, $query, $options );
235 * Returns the Url used to link to a Title
237 * @param $target Title
239 private static function linkUrl( $target, $query, $options ) {
240 wfProfileIn( __METHOD__
);
241 # We don't want to include fragments for broken links, because they
242 # generally make no sense.
243 if ( in_array( 'broken', $options ) && $target->mFragment
!== '' ) {
244 $target = clone $target;
245 $target->mFragment
= '';
248 # If it's a broken link, add the appropriate query pieces, unless
249 # there's already an action specified, or unless 'edit' makes no sense
250 # (i.e., for a nonexistent special page).
251 if ( in_array( 'broken', $options ) && empty( $query['action'] )
252 && $target->getNamespace() != NS_SPECIAL
) {
253 $query['action'] = 'edit';
254 $query['redlink'] = '1';
256 $ret = $target->getLinkUrl( $query );
257 wfProfileOut( __METHOD__
);
262 * Returns the array of attributes used when linking to the Title $target
264 * @param $target Title
270 private static function linkAttribs( $target, $attribs, $options ) {
271 wfProfileIn( __METHOD__
);
275 if ( !in_array( 'noclasses', $options ) ) {
276 wfProfileIn( __METHOD__
. '-getClasses' );
277 # Now build the classes.
280 if ( in_array( 'broken', $options ) ) {
284 if ( $target->isExternal() ) {
285 $classes[] = 'extiw';
288 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
289 $colour = self
::getLinkColour( $target, $wgUser->getStubThreshold() );
290 if ( $colour !== '' ) {
291 $classes[] = $colour; # mw-redirect or stub
294 if ( $classes != array() ) {
295 $defaults['class'] = implode( ' ', $classes );
297 wfProfileOut( __METHOD__
. '-getClasses' );
300 # Get a default title attribute.
301 if ( $target->getPrefixedText() == '' ) {
302 # A link like [[#Foo]]. This used to mean an empty title
303 # attribute, but that's silly. Just don't output a title.
304 } elseif ( in_array( 'known', $options ) ) {
305 $defaults['title'] = $target->getPrefixedText();
307 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
310 # Finally, merge the custom attribs with the default ones, and iterate
311 # over that, deleting all "false" attributes.
313 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
314 foreach ( $merged as $key => $val ) {
315 # A false value suppresses the attribute, and we don't want the
316 # href attribute to be overridden.
317 if ( $key != 'href' and $val !== false ) {
321 wfProfileOut( __METHOD__
);
326 * Default text of the links to the Title $target
328 * @param $target Title
332 private static function linkText( $target ) {
333 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
334 if ( !$target instanceof Title
) {
338 # If the target is just a fragment, with no title, we return the frag-
339 # ment text. Otherwise, we return the title text itself.
340 if ( $target->getPrefixedText() === '' && $target->getFragment() !== '' ) {
341 return htmlspecialchars( $target->getFragment() );
343 return htmlspecialchars( $target->getPrefixedText() );
347 * Generate either a normal exists-style link or a stub link, depending
348 * on the given page size.
350 * @param $size Integer
351 * @param $nt Title object.
352 * @param $text String
353 * @param $query String
354 * @param $trail String
355 * @param $prefix String
356 * @return string HTML of link
357 * @deprecated since 1.17
359 static function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
361 wfDeprecated( __METHOD__
);
363 $threshold = $wgUser->getStubThreshold();
364 $colour = ( $size < $threshold ) ?
'stub' : '';
365 // @todo FIXME: Replace deprecated makeColouredLinkObj by link()
366 return self
::makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
370 * Make appropriate markup for a link to the current article. This is currently rendered
371 * as the bold link text. The calling sequence is the same as the other make*LinkObj static functions,
372 * despite $query not being used.
378 static function makeSelfLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
380 $text = htmlspecialchars( $nt->getPrefixedText() );
382 list( $inside, $trail ) = self
::splitTrail( $trail );
383 return "<strong class=\"selflink\">{$prefix}{$text}{$inside}</strong>{$trail}";
387 * @param $title Title
390 static function normaliseSpecialPage( Title
$title ) {
391 if ( $title->getNamespace() == NS_SPECIAL
) {
392 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
396 $ret = SpecialPage
::getTitleFor( $name, $subpage );
397 $ret->mFragment
= $title->getFragment();
405 * Returns the filename part of an url.
406 * Used as alternative text for external images.
412 static function fnamePart( $url ) {
413 $basename = strrchr( $url, '/' );
414 if ( false === $basename ) {
417 $basename = substr( $basename, 1 );
423 * Return the code for images which were added via external links,
424 * via Parser::maybeMakeExternalImage().
431 static function makeExternalImage( $url, $alt = '' ) {
433 $alt = self
::fnamePart( $url );
436 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
438 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
441 return Html
::element( 'img',
448 * Given parameters derived from [[Image:Foo|options...]], generate the
449 * HTML that that syntax inserts in the page.
451 * @param $title Title object
452 * @param $file File object, or false if it doesn't exist
453 * @param $frameParams Array: associative array of parameters external to the media handler.
454 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
455 * will often be false.
456 * thumbnail If present, downscale and frame
457 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
458 * framed Shows image in original size in a frame
459 * frameless Downscale but don't frame
460 * upright If present, tweak default sizes for portrait orientation
461 * upright_factor Fudge factor for "upright" tweak (default 0.75)
462 * border If present, show a border around the image
463 * align Horizontal alignment (left, right, center, none)
464 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
465 * bottom, text-bottom)
466 * alt Alternate text for image (i.e. alt attribute). Plain text.
467 * caption HTML for image caption.
468 * link-url URL to link to
469 * link-title Title object to link to
470 * link-target Value for the target attribue, only with link-url
471 * no-link Boolean, suppress description link
473 * @param $handlerParams Array: associative array of media handler parameters, to be passed
474 * to transform(). Typical keys are "width" and "page".
475 * @param $time String: timestamp of the file, set as false for current
476 * @param $query String: query params for desc url
477 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
478 * @return String: HTML for an image, with links, wrappers, etc.
480 static function makeImageLink2( Title
$title, $file, $frameParams = array(),
481 $handlerParams = array(), $time = false, $query = "", $widthOption = null )
484 $dummy = new DummyLinker
;
485 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
486 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
490 if ( $file && !$file->allowInlineDisplay() ) {
491 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
492 return self
::link( $title );
497 $hp =& $handlerParams;
499 // Clean up parameters
500 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
501 if ( !isset( $fp['align'] ) ) {
504 if ( !isset( $fp['alt'] ) ) {
507 if ( !isset( $fp['title'] ) ) {
511 $prefix = $postfix = '';
513 if ( 'center' == $fp['align'] ) {
514 $prefix = '<div class="center">';
516 $fp['align'] = 'none';
518 if ( $file && !isset( $hp['width'] ) ) {
519 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
520 // If its a vector image, and user only specifies height
521 // we don't want it to be limited by its "normal" width.
522 global $wgSVGMaxSize;
523 $hp['width'] = $wgSVGMaxSize;
525 $hp['width'] = $file->getWidth( $page );
528 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
529 global $wgThumbLimits, $wgThumbUpright;
530 if ( !isset( $widthOption ) ||
!isset( $wgThumbLimits[$widthOption] ) ) {
531 $widthOption = User
::getDefaultOption( 'thumbsize' );
534 // Reduce width for upright images when parameter 'upright' is used
535 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
536 $fp['upright'] = $wgThumbUpright;
538 // 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
539 $prefWidth = isset( $fp['upright'] ) ?
540 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
541 $wgThumbLimits[$widthOption];
543 // Use width which is smaller: real image width or user preference width
544 // Unless image is scalable vector.
545 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
546 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
547 $hp['width'] = $prefWidth;
552 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
554 # Create a thumbnail. Alignment depends on language
555 # writing direction, # right aligned for left-to-right-
556 # languages ("Western languages"), left-aligned
557 # for right-to-left-languages ("Semitic languages")
559 # If thumbnail width has not been provided, it is set
560 # to the default user option as specified in Language*.php
561 if ( $fp['align'] == '' ) {
562 $fp['align'] = $wgContLang->alignEnd();
564 return $prefix . self
::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
567 if ( $file && isset( $fp['frameless'] ) ) {
568 $srcWidth = $file->getWidth( $page );
569 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
570 # This is the same behaviour as the "thumb" option does it already.
571 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
572 $hp['width'] = $srcWidth;
576 if ( $file && isset( $hp['width'] ) ) {
577 # Create a resized image, without the additional thumbnail features
578 $thumb = $file->transform( $hp );
584 $s = self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
588 'title' => $fp['title'],
589 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
590 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
591 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
593 $s = $thumb->toHtml( $params );
595 if ( $fp['align'] != '' ) {
596 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
598 return str_replace( "\n", ' ', $prefix . $s . $postfix );
602 * Get the link parameters for MediaTransformOutput::toHtml() from given
603 * frame parameters supplied by the Parser.
604 * @param $frameParams The frame parameters
605 * @param $query An optional query string to add to description page links
607 static function getImageLinkMTOParams( $frameParams, $query = '' ) {
608 $mtoParams = array();
609 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
610 $mtoParams['custom-url-link'] = $frameParams['link-url'];
611 if ( isset( $frameParams['link-target'] ) ) {
612 $mtoParams['custom-target-link'] = $frameParams['link-target'];
614 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
615 $mtoParams['custom-title-link'] = self
::normaliseSpecialPage( $frameParams['link-title'] );
616 } elseif ( !empty( $frameParams['no-link'] ) ) {
619 $mtoParams['desc-link'] = true;
620 $mtoParams['desc-query'] = $query;
626 * Make HTML for a thumbnail including image, border and caption
627 * @param $title Title object
628 * @param $file File object or false if it doesn't exist
629 * @param $label String
631 * @param $align String
632 * @param $params Array
633 * @param $framed Boolean
634 * @param $manualthumb String
636 static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt,
637 $align = 'right', $params = array(), $framed = false , $manualthumb = "" )
639 $frameParams = array(
645 $frameParams['framed'] = true;
647 if ( $manualthumb ) {
648 $frameParams['manualthumb'] = $manualthumb;
650 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
654 * @param $title Title
656 * @param array $frameParams
657 * @param array $handlerParams
659 * @param string $query
662 static function makeThumbLink2( Title
$title, $file, $frameParams = array(),
663 $handlerParams = array(), $time = false, $query = "" )
665 global $wgStylePath, $wgContLang;
666 $exists = $file && $file->exists();
670 $hp =& $handlerParams;
672 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
673 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
674 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
675 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
676 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
678 if ( empty( $hp['width'] ) ) {
679 // Reduce width for upright images when parameter 'upright' is used
680 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
685 $outerWidth = $hp['width'] +
2;
687 if ( isset( $fp['manualthumb'] ) ) {
688 # Use manually specified thumbnail
689 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
690 if ( $manual_title ) {
691 $manual_img = wfFindFile( $manual_title );
693 $thumb = $manual_img->getUnscaledThumb( $hp );
698 } elseif ( isset( $fp['framed'] ) ) {
699 // Use image dimensions, don't scale
700 $thumb = $file->getUnscaledThumb( $hp );
702 # Do not present an image bigger than the source, for bitmap-style images
703 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
704 $srcWidth = $file->getWidth( $page );
705 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
706 $hp['width'] = $srcWidth;
708 $thumb = $file->transform( $hp );
712 $outerWidth = $thumb->getWidth() +
2;
714 $outerWidth = $hp['width'] +
2;
718 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
719 # So we don't need to pass it here in $query. However, the URL for the
720 # zoom icon still needs it, so we make a unique query for it. See bug 14771
721 $url = $title->getLocalURL( $query );
723 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
726 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
728 $s .= self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
730 } elseif ( !$thumb ) {
731 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
736 'title' => $fp['title'],
737 'img-class' => 'thumbimage' );
738 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
739 $s .= $thumb->toHtml( $params );
740 if ( isset( $fp['framed'] ) ) {
743 $zoomIcon = Html
::rawElement( 'div', array( 'class' => 'magnify' ),
744 Html
::rawElement( 'a', array(
746 'class' => 'internal',
747 'title' => wfMsg( 'thumbnail-more' ) ),
748 Html
::element( 'img', array(
749 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ?
'-rtl' : '' ) . '.png',
755 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
756 return str_replace( "\n", ' ', $s );
760 * Make a "broken" link to an image
762 * @param $title Title object
763 * @param $text String: link label in unescaped text form
764 * @param $query String: query string
765 * @param $trail String: link trail (HTML fragment)
766 * @param $prefix String: link prefix (HTML fragment)
767 * @param $time Boolean: a file of a certain timestamp was requested
770 public static function makeBrokenImageLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '', $time = false ) {
771 global $wgEnableUploads, $wgUploadMissingFileUrl;
772 if ( ! $title instanceof Title
) {
773 return "<!-- ERROR -->{$prefix}{$text}{$trail}";
775 wfProfileIn( __METHOD__
);
776 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
778 list( $inside, $trail ) = self
::splitTrail( $trail );
780 $text = htmlspecialchars( $title->getPrefixedText() );
782 if ( ( $wgUploadMissingFileUrl ||
$wgEnableUploads ) && !$currentExists ) {
783 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
786 wfProfileOut( __METHOD__
);
787 return self
::linkKnown( $title, "$prefix$text$inside", array(), $query ) . $trail;
790 $href = self
::getUploadUrl( $title, $query );
792 wfProfileOut( __METHOD__
);
793 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
794 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
795 "$prefix$text$inside</a>$trail";
797 wfProfileOut( __METHOD__
);
798 return self
::linkKnown( $title, "$prefix$text$inside", array(), $query ) . $trail;
803 * Get the URL to upload a certain file
805 * @param $destFile Title object of the file to upload
806 * @param $query String: urlencoded query string to prepend
807 * @return String: urlencoded URL
809 protected static function getUploadUrl( $destFile, $query = '' ) {
810 global $wgUploadMissingFileUrl;
811 $q = 'wpDestFile=' . $destFile->getPartialUrl();
815 if ( $wgUploadMissingFileUrl ) {
816 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
818 $upload = SpecialPage
::getTitleFor( 'Upload' );
819 return $upload->getLocalUrl( $q );
824 * Create a direct link to a given uploaded file.
826 * @param $title Title object.
827 * @param $text String: pre-sanitized HTML
828 * @param $time string: MW timestamp of file creation time
829 * @return String: HTML
831 public static function makeMediaLinkObj( $title, $text = '', $time = false ) {
832 $img = wfFindFile( $title, array( 'time' => $time ) );
833 return self
::makeMediaLinkFile( $title, $img, $text );
837 * Create a direct link to a given uploaded file.
838 * This will make a broken link if $file is false.
840 * @param $title Title object.
841 * @param $file File|false mixed File object or false
842 * @param $text String: pre-sanitized HTML
843 * @return String: HTML
845 * @todo Handle invalid or missing images better.
847 public static function makeMediaLinkFile( Title
$title, $file, $text = '' ) {
848 if ( $file && $file->exists() ) {
849 $url = $file->getURL();
852 $url = self
::getUploadUrl( $title );
855 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES
);
859 $u = htmlspecialchars( $url );
860 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$text}</a>";
864 * Make a link to a special page given its name and, optionally,
865 * a message key from the link text.
866 * Usage example: $skin->specialLink( 'recentchanges' )
870 static function specialLink( $name, $key = '' ) {
872 $key = strtolower( $name );
875 return self
::linkKnown( SpecialPage
::getTitleFor( $name ) , wfMsg( $key ) );
879 * Make an external link
880 * @param $url String: URL to link to
881 * @param $text String: text of link
882 * @param $escape Boolean: do we escape the link text?
883 * @param $linktype String: type of external link. Gets added to the classes
884 * @param $attribs Array of extra attributes to <a>
886 static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
888 if ( isset($linktype) && $linktype ) {
889 $class .= " $linktype";
891 if ( isset($attribs['class']) && $attribs['class'] ) {
892 $class .= " {$attribs['class']}";
894 $attribs['class'] = $class;
897 $text = htmlspecialchars( $text );
900 $success = wfRunHooks( 'LinkerMakeExternalLink',
901 array( &$url, &$text, &$link, &$attribs, $linktype ) );
903 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
906 $attribs['href'] = $url;
907 return Html
::rawElement( 'a', $attribs, $text );
911 * Make user link (or user contributions for unregistered users)
912 * @param $userId Integer: user id in database.
913 * @param $userText String: user name in database
914 * @return String: HTML fragment
917 static function userLink( $userId, $userText ) {
918 if ( $userId == 0 ) {
919 $page = SpecialPage
::getTitleFor( 'Contributions', $userText );
921 $page = Title
::makeTitle( NS_USER
, $userText );
923 return self
::link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
927 * Generate standard user tool links (talk, contributions, block link, etc.)
929 * @param $userId Integer: user identifier
930 * @param $userText String: user name or IP address
931 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
932 * red if the user has no edits?
933 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK)
934 * @param $edits Integer: user edit count (optional, for performance)
935 * @return String: HTML fragment
937 public static function userToolLinks(
938 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
940 global $wgUser, $wgDisableAnonTalk, $wgLang;
941 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
942 $blockable = !$flags & self
::TOOL_LINKS_NOBLOCK
;
946 $items[] = self
::userTalkLink( $userId, $userText );
949 // check if the user has an edit
951 if ( $redContribsWhenNoEdits ) {
952 $count = !is_null( $edits ) ?
$edits : User
::edits( $userId );
954 $attribs['class'] = 'new';
957 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
959 $items[] = self
::link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
961 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
962 $items[] = self
::blockLink( $userId, $userText );
966 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
973 * Alias for userToolLinks( $userId, $userText, true );
974 * @param $userId Integer: user identifier
975 * @param $userText String: user name or IP address
976 * @param $edits Integer: user edit count (optional, for performance)
978 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
979 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
984 * @param $userId Integer: user id in database.
985 * @param $userText String: user name in database.
986 * @return String: HTML fragment with user talk link
989 static function userTalkLink( $userId, $userText ) {
990 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
991 $userTalkLink = self
::link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
992 return $userTalkLink;
996 * @param $userId Integer: userid
997 * @param $userText String: user name in database.
998 * @return String: HTML fragment with block link
1001 static function blockLink( $userId, $userText ) {
1002 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1003 $blockLink = self
::link( $blockPage, wfMsgHtml( 'blocklink' ) );
1008 * Generate a user link if the current user is allowed to view it
1009 * @param $rev Revision object.
1010 * @param $isPublic Boolean: show only if all users can see it
1011 * @return String: HTML fragment
1013 static function revUserLink( $rev, $isPublic = false ) {
1014 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1015 $link = wfMsgHtml( 'rev-deleted-user' );
1016 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1017 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1018 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1020 $link = wfMsgHtml( 'rev-deleted-user' );
1022 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1023 return '<span class="history-deleted">' . $link . '</span>';
1029 * Generate a user tool link cluster if the current user is allowed to view it
1030 * @param $rev Revision object.
1031 * @param $isPublic Boolean: show only if all users can see it
1032 * @return string HTML
1034 static function revUserTools( $rev, $isPublic = false ) {
1035 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1036 $link = wfMsgHtml( 'rev-deleted-user' );
1037 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1038 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1039 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1040 $link = self
::userLink( $userId, $userText ) .
1041 ' ' . self
::userToolLinks( $userId, $userText );
1043 $link = wfMsgHtml( 'rev-deleted-user' );
1045 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1046 return ' <span class="history-deleted">' . $link . '</span>';
1052 * This function is called by all recent changes variants, by the page history,
1053 * and by the user contributions list. It is responsible for formatting edit
1054 * comments. It escapes any HTML in the comment, but adds some CSS to format
1055 * auto-generated comments (from section editing) and formats [[wikilinks]].
1057 * @author Erik Moeller <moeller@scireview.de>
1059 * Note: there's not always a title to pass to this function.
1060 * Since you can't set a default parameter for a reference, I've turned it
1061 * temporarily to a value pass. Should be adjusted further. --brion
1063 * @param $comment String
1064 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1065 * @param $local Boolean: whether section links should refer to local page
1067 static function formatComment( $comment, $title = null, $local = false ) {
1068 wfProfileIn( __METHOD__
);
1070 # Sanitize text a bit:
1071 $comment = str_replace( "\n", " ", $comment );
1072 # Allow HTML entities (for bug 13815)
1073 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1075 # Render autocomments and make links:
1076 $comment = self
::formatAutocomments( $comment, $title, $local );
1077 $comment = self
::formatLinksInComment( $comment, $title, $local );
1079 wfProfileOut( __METHOD__
);
1086 static $autocommentTitle;
1087 static $autocommentLocal;
1090 * The pattern for autogen comments is / * foo * /, which makes for
1092 * We look for all comments, match any text before and after the comment,
1093 * add a separator where needed and format the comment itself with CSS
1094 * Called by Linker::formatComment.
1096 * @param $comment String: comment text
1097 * @param $title An optional title object used to links to sections
1098 * @param $local Boolean: whether section links should refer to local page
1099 * @return String: formatted comment
1101 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1103 self
::$autocommentTitle = $title;
1104 self
::$autocommentLocal = $local;
1105 $comment = preg_replace_callback(
1106 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1107 array( 'Linker', 'formatAutocommentsCallback' ),
1109 self
::$autocommentTitle = null;
1110 self
::$autocommentLocal = null;
1118 private static function formatAutocommentsCallback( $match ) {
1119 $title = self
::$autocommentTitle;
1120 $local = self
::$autocommentLocal;
1129 # Remove links that a user may have manually put in the autosummary
1130 # This could be improved by copying as much of Parser::stripSectionName as desired.
1131 $section = str_replace( '[[:', '', $section );
1132 $section = str_replace( '[[', '', $section );
1133 $section = str_replace( ']]', '', $section );
1135 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1137 $sectionTitle = Title
::newFromText( '#' . $section );
1139 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1140 $title->getDBkey(), $section );
1142 if ( $sectionTitle ) {
1143 $link = self
::link( $sectionTitle,
1144 htmlspecialchars( wfMsgForContent( 'sectionlink' ) ), array(), array(),
1150 $auto = "$link$auto";
1152 # written summary $presep autocomment (summary /* section */)
1153 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1156 # autocomment $postsep written summary (/* section */ summary)
1157 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1159 $auto = '<span class="autocomment">' . $auto . '</span>';
1160 $comment = $pre . $auto . $post;
1167 static $commentContextTitle;
1168 static $commentLocal;
1171 * Formats wiki links and media links in text; all other wiki formatting
1174 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1175 * @param $comment String: text to format links in
1176 * @param $title An optional title object used to links to sections
1177 * @param $local Boolean: whether section links should refer to local page
1180 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1181 self
::$commentContextTitle = $title;
1182 self
::$commentLocal = $local;
1183 $html = preg_replace_callback(
1184 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1185 array( 'Linker', 'formatLinksInCommentCallback' ),
1187 self
::$commentContextTitle = null;
1188 self
::$commentLocal = null;
1196 protected static function formatLinksInCommentCallback( $match ) {
1199 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1200 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1202 $comment = $match[0];
1204 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1205 if ( strpos( $match[1], '%' ) !== false ) {
1206 $match[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $match[1] ) );
1209 # Handle link renaming [[foo|text]] will show link as "text"
1210 if ( $match[3] != "" ) {
1215 $submatch = array();
1217 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1218 # Media link; trail not supported.
1219 $linkRegexp = '/\[\[(.*?)\]\]/';
1220 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1221 $thelink = self
::makeMediaLinkObj( $title, $text );
1223 # Other kind of link
1224 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1225 $trail = $submatch[1];
1229 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1230 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1231 $match[1] = substr( $match[1], 1 );
1232 list( $inside, $trail ) = self
::splitTrail( $trail );
1235 $linkTarget = self
::normalizeSubpageLink( self
::$commentContextTitle,
1236 $match[1], $linkText );
1238 $target = Title
::newFromText( $linkTarget );
1240 if ( $target->getText() == '' && $target->getInterwiki() === ''
1241 && !self
::$commentLocal && self
::$commentContextTitle )
1243 $newTarget = clone ( self
::$commentContextTitle );
1244 $newTarget->setFragment( '#' . $target->getFragment() );
1245 $target = $newTarget;
1247 $thelink = self
::link(
1254 // If the link is still valid, go ahead and replace it in!
1255 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1262 * @param $contextTitle Title
1267 static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1270 # :Foobar -- override special treatment of prefix (images, language links)
1271 # /Foobar -- convert to CurrentPage/Foobar
1272 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1273 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1274 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1276 wfProfileIn( __METHOD__
);
1277 $ret = $target; # default return value is no change
1279 # Some namespaces don't allow subpages,
1280 # so only perform processing if subpages are allowed
1281 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1282 $hash = strpos( $target, '#' );
1283 if ( $hash !== false ) {
1284 $suffix = substr( $target, $hash );
1285 $target = substr( $target, 0, $hash );
1290 $target = trim( $target );
1291 # Look at the first character
1292 if ( $target != '' && $target { 0 } === '/' ) {
1293 # / at end means we don't want the slash to be shown
1295 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1296 if ( $trailingSlashes ) {
1297 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1299 $noslash = substr( $target, 1 );
1302 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1303 if ( $text === '' ) {
1304 $text = $target . $suffix;
1305 } # this might be changed for ugliness reasons
1307 # check for .. subpage backlinks
1309 $nodotdot = $target;
1310 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1312 $nodotdot = substr( $nodotdot, 3 );
1314 if ( $dotdotcount > 0 ) {
1315 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1316 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1317 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1318 # / at the end means don't show full path
1319 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1320 $nodotdot = substr( $nodotdot, 0, -1 );
1321 if ( $text === '' ) {
1322 $text = $nodotdot . $suffix;
1325 $nodotdot = trim( $nodotdot );
1326 if ( $nodotdot != '' ) {
1327 $ret .= '/' . $nodotdot;
1335 wfProfileOut( __METHOD__
);
1340 * Wrap a comment in standard punctuation and formatting if
1341 * it's non-empty, otherwise return empty string.
1343 * @param $comment String
1344 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1345 * @param $local Boolean: whether section links should refer to local page
1349 static function commentBlock( $comment, $title = null, $local = false ) {
1350 // '*' used to be the comment inserted by the software way back
1351 // in antiquity in case none was provided, here for backwards
1352 // compatability, acc. to brion -ævar
1353 if ( $comment == '' ||
$comment == '*' ) {
1356 $formatted = self
::formatComment( $comment, $title, $local );
1357 return " <span class=\"comment\">($formatted)</span>";
1362 * Wrap and format the given revision's comment block, if the current
1363 * user is allowed to view it.
1365 * @param $rev Revision object
1366 * @param $local Boolean: whether section links should refer to local page
1367 * @param $isPublic Boolean: show only if all users can see it
1368 * @return String: HTML fragment
1370 static function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1371 if ( $rev->getRawComment() == "" ) {
1374 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1375 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1376 } elseif ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1377 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1378 $rev->getTitle(), $local );
1380 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1382 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1383 return " <span class=\"history-deleted\">$block</span>";
1392 public static function formatRevisionSize( $size ) {
1394 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1397 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1400 $stxt = htmlspecialchars( $stxt );
1401 return "<span class=\"history-size\">$stxt</span>";
1405 * Add another level to the Table of Contents
1409 static function tocIndent() {
1414 * Finish one or more sublevels on the Table of Contents
1418 static function tocUnindent( $level ) {
1419 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1423 * parameter level defines if we are on an indentation level
1427 static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1428 $classes = "toclevel-$level";
1429 if ( $sectionIndex !== false ) {
1430 $classes .= " tocsection-$sectionIndex";
1432 return "\n<li class=\"$classes\"><a href=\"#" .
1433 $anchor . '"><span class="tocnumber">' .
1434 $tocnumber . '</span> <span class="toctext">' .
1435 $tocline . '</span></a>';
1439 * End a Table Of Contents line.
1440 * tocUnindent() will be used instead if we're ending a line below
1443 static function tocLineEnd() {
1448 * Wraps the TOC in a table and provides the hide/collapse javascript.
1450 * @param $toc String: html of the Table Of Contents
1451 * @param $lang mixed: Language code for the toc title
1452 * @return String: full html of the TOC
1454 static function tocList( $toc, $lang = false ) {
1455 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1457 '<table id="toc" class="toc"><tr><td>'
1458 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1460 . "</ul>\n</td></tr></table>\n";
1464 * Generate a table of contents from a section tree
1467 * @param $tree Return value of ParserOutput::getSections()
1468 * @return String: HTML fragment
1470 public static function generateTOC( $tree ) {
1473 foreach ( $tree as $section ) {
1474 if ( $section['toclevel'] > $lastLevel )
1475 $toc .= self
::tocIndent();
1476 elseif ( $section['toclevel'] < $lastLevel )
1477 $toc .= self
::tocUnindent(
1478 $lastLevel - $section['toclevel'] );
1480 $toc .= self
::tocLineEnd();
1482 $toc .= self
::tocLine( $section['anchor'],
1483 $section['line'], $section['number'],
1484 $section['toclevel'], $section['index'] );
1485 $lastLevel = $section['toclevel'];
1487 $toc .= self
::tocLineEnd();
1488 return self
::tocList( $toc );
1492 * Create a headline for content
1494 * @param $level Integer: the level of the headline (1-6)
1495 * @param $attribs String: any attributes for the headline, starting with
1496 * a space and ending with '>'
1497 * This *must* be at least '>' for no attribs
1498 * @param $anchor String: the anchor to give the headline (the bit after the #)
1499 * @param $text String: the text of the header
1500 * @param $link String: HTML to add for the section edit link
1501 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1502 * backward compatibility (false to omit)
1504 * @return String: HTML headline
1506 public static function makeHeadline( $level, $attribs, $anchor, $text, $link, $legacyAnchor = false ) {
1507 $ret = "<h$level$attribs"
1509 . " <span class=\"mw-headline\" id=\"$anchor\">$text</span>"
1511 if ( $legacyAnchor !== false ) {
1512 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1518 * Split a link trail, return the "inside" portion and the remainder of the trail
1519 * as a two-element array
1521 static function splitTrail( $trail ) {
1523 $regex = $wgContLang->linkTrail();
1525 if ( $trail !== '' ) {
1527 if ( preg_match( $regex, $trail, $m ) ) {
1532 return array( $inside, $trail );
1536 * Generate a rollback link for a given revision. Currently it's the
1537 * caller's responsibility to ensure that the revision is the top one. If
1538 * it's not, of course, the user will get an error message.
1540 * If the calling page is called with the parameter &bot=1, all rollback
1541 * links also get that parameter. It causes the edit itself and the rollback
1542 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1543 * changes, so this allows sysops to combat a busy vandal without bothering
1546 * @param $rev Revision object
1548 static function generateRollback( $rev ) {
1549 return '<span class="mw-rollback-link">['
1550 . self
::buildRollbackLink( $rev )
1555 * Build a raw rollback link, useful for collections of "tool" links
1557 * @param $rev Revision object
1558 * @return String: HTML fragment
1560 public static function buildRollbackLink( $rev ) {
1561 global $wgRequest, $wgUser;
1562 $title = $rev->getTitle();
1564 'action' => 'rollback',
1565 'from' => $rev->getUserText(),
1566 'token' => $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1568 if ( $wgRequest->getBool( 'bot' ) ) {
1569 $query['bot'] = '1';
1570 $query['hidediff'] = '1'; // bug 15999
1574 wfMsgHtml( 'rollbacklink' ),
1575 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1577 array( 'known', 'noclasses' )
1582 * Returns HTML for the "templates used on this page" list.
1584 * @param $templates Array of templates from Article::getUsedTemplate
1586 * @param $preview Boolean: whether this is for a preview
1587 * @param $section Boolean: whether this is for a section edit
1588 * @return String: HTML output
1590 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1591 wfProfileIn( __METHOD__
);
1594 if ( count( $templates ) > 0 ) {
1595 # Do a batch existence check
1596 $batch = new LinkBatch
;
1597 foreach ( $templates as $title ) {
1598 $batch->addObj( $title );
1602 # Construct the HTML
1603 $outText = '<div class="mw-templatesUsedExplanation">';
1605 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1606 } elseif ( $section ) {
1607 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1609 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1611 $outText .= "</div><ul>\n";
1613 usort( $templates, array( 'Title', 'compare' ) );
1614 foreach ( $templates as $titleObj ) {
1615 $r = $titleObj->getRestrictions( 'edit' );
1616 if ( in_array( 'sysop', $r ) ) {
1617 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1618 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1619 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1623 if ( $titleObj->quickUserCan( 'edit' ) ) {
1624 $editLink = self
::link(
1626 wfMsg( 'editlink' ),
1628 array( 'action' => 'edit' )
1631 $editLink = self
::link(
1633 wfMsg( 'viewsourcelink' ),
1635 array( 'action' => 'edit' )
1638 $outText .= '<li>' . self
::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1640 $outText .= '</ul>';
1642 wfProfileOut( __METHOD__
);
1647 * Returns HTML for the "hidden categories on this page" list.
1649 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1651 * @return String: HTML output
1653 public static function formatHiddenCategories( $hiddencats ) {
1655 wfProfileIn( __METHOD__
);
1658 if ( count( $hiddencats ) > 0 ) {
1659 # Construct the HTML
1660 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1661 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1662 $outText .= "</div><ul>\n";
1664 foreach ( $hiddencats as $titleObj ) {
1665 $outText .= '<li>' . self
::link( $titleObj, null, array(), array(), 'known' ) . "</li>\n"; # If it's hidden, it must exist - no need to check with a LinkBatch
1667 $outText .= '</ul>';
1669 wfProfileOut( __METHOD__
);
1674 * Format a size in bytes for output, using an appropriate
1675 * unit (B, KB, MB or GB) according to the magnitude in question
1677 * @param $size Size to format
1680 public static function formatSize( $size ) {
1682 return htmlspecialchars( $wgLang->formatSize( $size ) );
1686 * Given the id of an interface element, constructs the appropriate title
1687 * attribute from the system messages. (Note, this is usually the id but
1688 * isn't always, because sometimes the accesskey needs to go on a different
1689 * element than the id, for reverse-compatibility, etc.)
1691 * @param $name String: id of the element, minus prefixes.
1692 * @param $options Mixed: null or the string 'withaccess' to add an access-
1694 * @return String: contents of the title attribute (which you must HTML-
1695 * escape), or false for no title attribute
1697 public static function titleAttrib( $name, $options = null ) {
1698 wfProfileIn( __METHOD__
);
1700 $message = wfMessage( "tooltip-$name" );
1702 if ( !$message->exists() ) {
1705 $tooltip = $message->text();
1706 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1707 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1708 # Message equal to '-' means suppress it.
1709 if ( $tooltip == '-' ) {
1714 if ( $options == 'withaccess' ) {
1715 $accesskey = self
::accesskey( $name );
1716 if ( $accesskey !== false ) {
1717 if ( $tooltip === false ||
$tooltip === '' ) {
1718 $tooltip = "[$accesskey]";
1720 $tooltip .= " [$accesskey]";
1725 wfProfileOut( __METHOD__
);
1729 static $accesskeycache;
1732 * Given the id of an interface element, constructs the appropriate
1733 * accesskey attribute from the system messages. (Note, this is usually
1734 * the id but isn't always, because sometimes the accesskey needs to go on
1735 * a different element than the id, for reverse-compatibility, etc.)
1737 * @param $name String: id of the element, minus prefixes.
1738 * @return String: contents of the accesskey attribute (which you must HTML-
1739 * escape), or false for no accesskey attribute
1741 public static function accesskey( $name ) {
1742 if ( isset( self
::$accesskeycache[$name] ) ) {
1743 return self
::$accesskeycache[$name];
1745 wfProfileIn( __METHOD__
);
1747 $message = wfMessage( "accesskey-$name" );
1749 if ( !$message->exists() ) {
1752 $accesskey = $message->plain();
1753 if ( $accesskey === '' ||
$accesskey === '-' ) {
1754 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
1755 # attribute, but this is broken for accesskey: that might be a useful
1761 wfProfileOut( __METHOD__
);
1762 return self
::$accesskeycache[$name] = $accesskey;
1766 * Creates a (show/hide) link for deleting revisions/log entries
1768 * @param $query Array: query parameters to be passed to link()
1769 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1770 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1772 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1773 * span to allow for customization of appearance with CSS
1775 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1776 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1777 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1778 $tag = $restricted ?
'strong' : 'span';
1779 $link = self
::link( $sp, $text, array(), $query, array( 'known', 'noclasses' ) );
1780 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1784 * Creates a dead (show/hide) link for deleting revisions/log entries
1786 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1788 * @return string HTML text wrapped in a span to allow for customization
1789 * of appearance with CSS
1791 public static function revDeleteLinkDisabled( $delete = true ) {
1792 $text = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1793 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($text)" );
1796 /* Deprecated methods */
1799 * @deprecated since 1.16 Use link()
1801 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1802 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1804 * @param $title String: The text of the title
1805 * @param $text String: Link text
1806 * @param $query String: Optional query part
1807 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1808 * be included in the link text. Other characters will be appended after
1809 * the end of the link.
1811 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1812 $nt = Title
::newFromText( $title );
1813 if ( $nt instanceof Title
) {
1814 return self
::makeBrokenLinkObj( $nt, $text, $query, $trail );
1816 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
1817 return $text == '' ?
$title : $text;
1822 * @deprecated since 1.16 Use link()
1824 * Make a link for a title which may or may not be in the database. If you need to
1825 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1826 * call to this will result in a DB query.
1828 * @param $nt Title: the title object to make the link from, e.g. from
1829 * Title::newFromText.
1830 * @param $text String: link text
1831 * @param $query String: optional query part
1832 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1833 * be included in the link text. Other characters will be appended after
1834 * the end of the link.
1835 * @param $prefix String: optional prefix. As trail, only before instead of after.
1837 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1838 wfProfileIn( __METHOD__
);
1839 $query = wfCgiToArray( $query );
1840 list( $inside, $trail ) = self
::splitTrail( $trail );
1841 if ( $text === '' ) {
1842 $text = self
::linkText( $nt );
1845 $ret = self
::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1847 wfProfileOut( __METHOD__
);
1852 * @deprecated since 1.16 Use link()
1854 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1855 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1858 * @param $title Title object of target page
1859 * @param $text String: text to replace the title
1860 * @param $query String: link target
1861 * @param $trail String: text after link
1862 * @param $prefix String: text before link text
1863 * @param $aprops String: extra attributes to the a-element
1864 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1865 * @return the a-element
1867 static function makeKnownLinkObj(
1868 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
1870 wfProfileIn( __METHOD__
);
1872 if ( $text == '' ) {
1873 $text = self
::linkText( $title );
1875 $attribs = Sanitizer
::mergeAttributes(
1876 Sanitizer
::decodeTagAttributes( $aprops ),
1877 Sanitizer
::decodeTagAttributes( $style )
1879 $query = wfCgiToArray( $query );
1880 list( $inside, $trail ) = self
::splitTrail( $trail );
1882 $ret = self
::link( $title, "$prefix$text$inside", $attribs, $query,
1883 array( 'known', 'noclasses' ) ) . $trail;
1885 wfProfileOut( __METHOD__
);
1890 * @deprecated since 1.16 Use link()
1892 * Make a red link to the edit page of a given title.
1894 * @param $title Title object of the target page
1895 * @param $text String: Link text
1896 * @param $query String: Optional query part
1897 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1898 * be included in the link text. Other characters will be appended after
1899 * the end of the link.
1900 * @param $prefix String: Optional prefix
1902 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
1903 wfProfileIn( __METHOD__
);
1905 list( $inside, $trail ) = self
::splitTrail( $trail );
1906 if ( $text === '' ) {
1907 $text = self
::linkText( $title );
1910 $ret = self
::link( $title, "$prefix$text$inside", array(),
1911 wfCgiToArray( $query ), 'broken' ) . $trail;
1913 wfProfileOut( __METHOD__
);
1918 * @deprecated since 1.16 Use link()
1920 * Make a coloured link.
1922 * @param $nt Title object of the target page
1923 * @param $colour Integer: colour of the link
1924 * @param $text String: link text
1925 * @param $query String: optional query part
1926 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1927 * be included in the link text. Other characters will be appended after
1928 * the end of the link.
1929 * @param $prefix String: Optional prefix
1931 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
1932 if ( $colour != '' ) {
1933 $style = self
::getInternalLinkAttributesObj( $nt, $text, $colour );
1937 return self
::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
1941 * Returns the attributes for the tooltip and access key.
1943 public static function tooltipAndAccesskeyAttribs( $name ) {
1944 global $wgEnableTooltipsAndAccesskeys;
1945 if ( !$wgEnableTooltipsAndAccesskeys )
1947 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
1948 # no attribute" instead of "output '' as value for attribute", this
1949 # would be three lines.
1951 'title' => self
::titleAttrib( $name, 'withaccess' ),
1952 'accesskey' => self
::accesskey( $name )
1954 if ( $attribs['title'] === false ) {
1955 unset( $attribs['title'] );
1957 if ( $attribs['accesskey'] === false ) {
1958 unset( $attribs['accesskey'] );
1964 * @deprecated since 1.14
1965 * Returns raw bits of HTML, use titleAttrib()
1967 public static function tooltip( $name, $options = null ) {
1968 global $wgEnableTooltipsAndAccesskeys;
1969 if ( !$wgEnableTooltipsAndAccesskeys )
1971 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
1972 # no attribute" instead of "output '' as value for attribute", this
1973 # would be two lines.
1974 $tooltip = self
::titleAttrib( $name, $options );
1975 if ( $tooltip === false ) {
1978 return Xml
::expandAttributes( array(
1990 * Use PHP's magic __call handler to transform instance calls to a dummy instance
1991 * into static calls to the new Linker for backwards compatibility.
1993 * @param $fname String Name of called method
1994 * @param $args Array Arguments to the method
1996 function __call( $fname, $args ) {
1997 return call_user_func_array( array( 'Linker', $fname ), $args );