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;
15 const TOOL_LINKS_EMAIL
= 2;
18 * Get the appropriate HTML attributes to add to the "a" element of an ex-
19 * ternal link, as created by [wikisyntax].
21 * @param $class String: the contents of the class attribute; if an empty
22 * string is passed, which is the default value, defaults to 'external'.
24 * @deprecated since 1.18 Just pass the external class directly to something using Html::expandAttributes
26 static function getExternalLinkAttributes( $class = 'external' ) {
27 wfDeprecated( __METHOD__
, '1.18' );
28 return self
::getLinkAttributesInternal( '', $class );
32 * Get the appropriate HTML attributes to add to the "a" element of an in-
35 * @param $title String: the title text for the link, URL-encoded (???) but
37 * @param $unused String: unused
38 * @param $class String: the contents of the class attribute; if an empty
39 * string is passed, which is the default value, defaults to 'external'.
42 static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
45 # @todo FIXME: We have a whole bunch of handling here that doesn't happen in
46 # getExternalLinkAttributes, why?
47 $title = urldecode( $title );
48 $title = $wgContLang->checkTitleEncoding( $title );
49 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
51 return self
::getLinkAttributesInternal( $title, $class );
55 * Get the appropriate HTML attributes to add to the "a" element of an in-
58 * @param $title String: the title text for the link, URL-encoded (???) but
60 * @param $unused String: unused
61 * @param $class String: the contents of the class attribute, default none
64 static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
65 $title = urldecode( $title );
66 $title = str_replace( '_', ' ', $title );
67 return self
::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
81 static function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
82 if ( $title === false ) {
83 $title = $nt->getPrefixedText();
85 return self
::getLinkAttributesInternal( $title, $class );
89 * Common code for getLinkAttributesX functions
91 * @param $title string
92 * @param $class string
96 private static function getLinkAttributesInternal( $title, $class ) {
97 $title = htmlspecialchars( $title );
98 $class = htmlspecialchars( $class );
100 if ( $class != '' ) {
101 $r .= " class=\"$class\"";
103 if ( $title != '' ) {
104 $r .= " title=\"$title\"";
110 * Return the CSS colour of a known link
112 * @param $t Title object
113 * @param $threshold Integer: user defined threshold
114 * @return String: CSS class
116 public static function getLinkColour( $t, $threshold ) {
118 if ( $t->isRedirect() ) {
120 $colour = 'mw-redirect';
121 } elseif ( $threshold > 0 &&
122 $t->exists() && $t->getLength() < $threshold &&
123 $t->isContentPage() ) {
131 * This function returns an HTML link to the given target. It serves a few
133 * 1) If $target is a Title, the correct URL to link to will be figured
135 * 2) It automatically adds the usual classes for various types of link
136 * targets: "new" for red links, "stub" for short articles, etc.
137 * 3) It escapes all attribute values safely so there's no risk of XSS.
138 * 4) It provides a default tooltip if the target is a Title (the page
139 * name of the target).
140 * link() replaces the old functions in the makeLink() family.
142 * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
143 * You can call it using this if you want to keep compat with these:
144 * $linker = class_exists( 'DummyLinker' ) ? new DummyLinker() : new Linker();
145 * $linker->link( ... );
147 * @param $target Title Can currently only be a Title, but this may
148 * change to support Images, literal URLs, etc.
149 * @param $html string The HTML contents of the <a> element, i.e.,
150 * the link text. This is raw HTML and will not be escaped. If null,
151 * defaults to the prefixed text of the Title; or if the Title is just a
152 * fragment, the contents of the fragment.
153 * @param $customAttribs array A key => value array of extra HTML attri-
154 * butes, such as title and class. (href is ignored.) Classes will be
155 * merged with the default classes, while other attributes will replace
156 * default attributes. All passed attribute values will be HTML-escaped.
157 * A false attribute value means to suppress that attribute.
158 * @param $query array The query string to append to the URL
159 * you're linking to, in key => value array form. Query keys and values
160 * will be URL-encoded.
161 * @param $options string|array String or array of strings:
162 * 'known': Page is known to exist, so don't check if it does.
163 * 'broken': Page is known not to exist, so don't check if it does.
164 * 'noclasses': Don't add any classes automatically (includes "new",
165 * "stub", "mw-redirect", "extiw"). Only use the class attribute
166 * provided, if any, so you get a simple blue link with no funny i-
168 * 'forcearticlepath': Use the article path always, even with a querystring.
169 * Has compatibility issues on some setups, so avoid wherever possible.
170 * @return string HTML <a> attribute
172 public static function link(
173 $target, $html = null, $customAttribs = array(), $query = array(), $options = array()
175 wfProfileIn( __METHOD__
);
176 if ( !$target instanceof Title
) {
177 wfProfileOut( __METHOD__
);
178 return "<!-- ERROR -->$html";
180 $options = (array)$options;
182 $dummy = new DummyLinker
; // dummy linker instance for bc on the hooks
185 if ( !wfRunHooks( 'LinkBegin', array( $dummy, $target, &$html,
186 &$customAttribs, &$query, &$options, &$ret ) ) ) {
187 wfProfileOut( __METHOD__
);
191 # Normalize the Title if it's a special page
192 $target = self
::normaliseSpecialPage( $target );
194 # If we don't know whether the page exists, let's find out.
195 wfProfileIn( __METHOD__
. '-checkPageExistence' );
196 if ( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
197 if ( $target->isKnown() ) {
198 $options[] = 'known';
200 $options[] = 'broken';
203 wfProfileOut( __METHOD__
. '-checkPageExistence' );
206 if ( in_array( "forcearticlepath", $options ) && $query ) {
211 # Note: we want the href attribute first, for prettiness.
212 $attribs = array( 'href' => self
::linkUrl( $target, $query, $options ) );
213 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
214 $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
217 $attribs = array_merge(
219 self
::linkAttribs( $target, $customAttribs, $options )
221 if ( is_null( $html ) ) {
222 $html = self
::linkText( $target );
226 if ( wfRunHooks( 'LinkEnd', array( $dummy, $target, $options, &$html, &$attribs, &$ret ) ) ) {
227 $ret = Html
::rawElement( 'a', $attribs, $html );
230 wfProfileOut( __METHOD__
);
235 * Identical to link(), except $options defaults to 'known'.
238 public static function linkKnown(
239 $target, $html = null, $customAttribs = array(),
240 $query = array(), $options = array( 'known', 'noclasses' ) )
242 return self
::link( $target, $html, $customAttribs, $query, $options );
246 * Returns the Url used to link to a Title
248 * @param $target Title
249 * @param $query Array: query parameters
250 * @param $options Array
253 private static function linkUrl( $target, $query, $options ) {
254 wfProfileIn( __METHOD__
);
255 # We don't want to include fragments for broken links, because they
256 # generally make no sense.
257 if ( in_array( 'broken', $options ) && $target->mFragment
!== '' ) {
258 $target = clone $target;
259 $target->mFragment
= '';
262 # If it's a broken link, add the appropriate query pieces, unless
263 # there's already an action specified, or unless 'edit' makes no sense
264 # (i.e., for a nonexistent special page).
265 if ( in_array( 'broken', $options ) && empty( $query['action'] )
266 && !$target->isSpecialPage() ) {
267 $query['action'] = 'edit';
268 $query['redlink'] = '1';
270 $ret = $target->getLinkURL( $query );
271 wfProfileOut( __METHOD__
);
276 * Returns the array of attributes used when linking to the Title $target
278 * @param $target Title
284 private static function linkAttribs( $target, $attribs, $options ) {
285 wfProfileIn( __METHOD__
);
289 if ( !in_array( 'noclasses', $options ) ) {
290 wfProfileIn( __METHOD__
. '-getClasses' );
291 # Now build the classes.
294 if ( in_array( 'broken', $options ) ) {
298 if ( $target->isExternal() ) {
299 $classes[] = 'extiw';
302 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
303 $colour = self
::getLinkColour( $target, $wgUser->getStubThreshold() );
304 if ( $colour !== '' ) {
305 $classes[] = $colour; # mw-redirect or stub
308 if ( $classes != array() ) {
309 $defaults['class'] = implode( ' ', $classes );
311 wfProfileOut( __METHOD__
. '-getClasses' );
314 # Get a default title attribute.
315 if ( $target->getPrefixedText() == '' ) {
316 # A link like [[#Foo]]. This used to mean an empty title
317 # attribute, but that's silly. Just don't output a title.
318 } elseif ( in_array( 'known', $options ) ) {
319 $defaults['title'] = $target->getPrefixedText();
321 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
324 # Finally, merge the custom attribs with the default ones, and iterate
325 # over that, deleting all "false" attributes.
327 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
328 foreach ( $merged as $key => $val ) {
329 # A false value suppresses the attribute, and we don't want the
330 # href attribute to be overridden.
331 if ( $key != 'href' and $val !== false ) {
335 wfProfileOut( __METHOD__
);
340 * Default text of the links to the Title $target
342 * @param $target Title
346 private static function linkText( $target ) {
347 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
348 if ( !$target instanceof Title
) {
352 # If the target is just a fragment, with no title, we return the frag-
353 # ment text. Otherwise, we return the title text itself.
354 if ( $target->getPrefixedText() === '' && $target->getFragment() !== '' ) {
355 return htmlspecialchars( $target->getFragment() );
357 return htmlspecialchars( $target->getPrefixedText() );
361 * Generate either a normal exists-style link or a stub link, depending
362 * on the given page size.
364 * @param $size Integer
365 * @param $nt Title object.
366 * @param $text String
367 * @param $query String
368 * @param $trail String
369 * @param $prefix String
370 * @return string HTML of link
371 * @deprecated since 1.17
373 static function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
375 wfDeprecated( __METHOD__
, '1.17' );
377 $threshold = $wgUser->getStubThreshold();
378 $colour = ( $size < $threshold ) ?
'stub' : '';
379 // @todo FIXME: Replace deprecated makeColouredLinkObj by link()
380 return self
::makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
384 * Make appropriate markup for a link to the current article. This is currently rendered
385 * as the bold link text. The calling sequence is the same as the other make*LinkObj static functions,
386 * despite $query not being used.
392 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
394 $html = htmlspecialchars( $nt->getPrefixedText() );
396 list( $inside, $trail ) = self
::splitTrail( $trail );
397 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
401 * @param $title Title
404 static function normaliseSpecialPage( Title
$title ) {
405 if ( $title->isSpecialPage() ) {
406 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
410 $ret = SpecialPage
::getTitleFor( $name, $subpage );
411 $ret->mFragment
= $title->getFragment();
419 * Returns the filename part of an url.
420 * Used as alternative text for external images.
426 private static function fnamePart( $url ) {
427 $basename = strrchr( $url, '/' );
428 if ( false === $basename ) {
431 $basename = substr( $basename, 1 );
437 * Return the code for images which were added via external links,
438 * via Parser::maybeMakeExternalImage().
445 public static function makeExternalImage( $url, $alt = '' ) {
447 $alt = self
::fnamePart( $url );
450 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
452 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
455 return Html
::element( 'img',
462 * Given parameters derived from [[Image:Foo|options...]], generate the
463 * HTML that that syntax inserts in the page.
465 * @param $title Title object
466 * @param $file File object, or false if it doesn't exist
467 * @param $frameParams Array: associative array of parameters external to the media handler.
468 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
469 * will often be false.
470 * thumbnail If present, downscale and frame
471 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
472 * framed Shows image in original size in a frame
473 * frameless Downscale but don't frame
474 * upright If present, tweak default sizes for portrait orientation
475 * upright_factor Fudge factor for "upright" tweak (default 0.75)
476 * border If present, show a border around the image
477 * align Horizontal alignment (left, right, center, none)
478 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
479 * bottom, text-bottom)
480 * alt Alternate text for image (i.e. alt attribute). Plain text.
481 * caption HTML for image caption.
482 * link-url URL to link to
483 * link-title Title object to link to
484 * link-target Value for the target attribue, only with link-url
485 * no-link Boolean, suppress description link
487 * @param $handlerParams Array: associative array of media handler parameters, to be passed
488 * to transform(). Typical keys are "width" and "page".
489 * @param $time String: timestamp of the file, set as false for current
490 * @param $query String: query params for desc url
491 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
492 * @return String: HTML for an image, with links, wrappers, etc.
494 public static function makeImageLink2( Title
$title, $file, $frameParams = array(),
495 $handlerParams = array(), $time = false, $query = "", $widthOption = null )
498 $dummy = new DummyLinker
;
499 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
500 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
504 if ( $file && !$file->allowInlineDisplay() ) {
505 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
506 return self
::link( $title );
511 $hp =& $handlerParams;
513 // Clean up parameters
514 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
515 if ( !isset( $fp['align'] ) ) {
518 if ( !isset( $fp['alt'] ) ) {
521 if ( !isset( $fp['title'] ) ) {
525 $prefix = $postfix = '';
527 if ( 'center' == $fp['align'] ) {
528 $prefix = '<div class="center">';
530 $fp['align'] = 'none';
532 if ( $file && !isset( $hp['width'] ) ) {
533 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
534 // If its a vector image, and user only specifies height
535 // we don't want it to be limited by its "normal" width.
536 global $wgSVGMaxSize;
537 $hp['width'] = $wgSVGMaxSize;
539 $hp['width'] = $file->getWidth( $page );
542 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
543 global $wgThumbLimits, $wgThumbUpright;
544 if ( !isset( $widthOption ) ||
!isset( $wgThumbLimits[$widthOption] ) ) {
545 $widthOption = User
::getDefaultOption( 'thumbsize' );
548 // Reduce width for upright images when parameter 'upright' is used
549 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
550 $fp['upright'] = $wgThumbUpright;
552 // 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
553 $prefWidth = isset( $fp['upright'] ) ?
554 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
555 $wgThumbLimits[$widthOption];
557 // Use width which is smaller: real image width or user preference width
558 // Unless image is scalable vector.
559 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
560 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
561 $hp['width'] = $prefWidth;
566 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
568 # Create a thumbnail. Alignment depends on language
569 # writing direction, # right aligned for left-to-right-
570 # languages ("Western languages"), left-aligned
571 # for right-to-left-languages ("Semitic languages")
573 # If thumbnail width has not been provided, it is set
574 # to the default user option as specified in Language*.php
575 if ( $fp['align'] == '' ) {
576 $fp['align'] = $wgContLang->alignEnd();
578 return $prefix . self
::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
581 if ( $file && isset( $fp['frameless'] ) ) {
582 $srcWidth = $file->getWidth( $page );
583 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
584 # This is the same behaviour as the "thumb" option does it already.
585 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
586 $hp['width'] = $srcWidth;
590 if ( $file && isset( $hp['width'] ) ) {
591 # Create a resized image, without the additional thumbnail features
592 $thumb = $file->transform( $hp );
598 $s = self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
602 'title' => $fp['title'],
603 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
604 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
605 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
607 $s = $thumb->toHtml( $params );
609 if ( $fp['align'] != '' ) {
610 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
612 return str_replace( "\n", ' ', $prefix . $s . $postfix );
616 * Get the link parameters for MediaTransformOutput::toHtml() from given
617 * frame parameters supplied by the Parser.
618 * @param $frameParams array The frame parameters
619 * @param $query string An optional query string to add to description page links
622 private static function getImageLinkMTOParams( $frameParams, $query = '' ) {
623 $mtoParams = array();
624 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
625 $mtoParams['custom-url-link'] = $frameParams['link-url'];
626 if ( isset( $frameParams['link-target'] ) ) {
627 $mtoParams['custom-target-link'] = $frameParams['link-target'];
629 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
630 $mtoParams['custom-title-link'] = self
::normaliseSpecialPage( $frameParams['link-title'] );
631 } elseif ( !empty( $frameParams['no-link'] ) ) {
634 $mtoParams['desc-link'] = true;
635 $mtoParams['desc-query'] = $query;
641 * Make HTML for a thumbnail including image, border and caption
642 * @param $title Title object
643 * @param $file File object or false if it doesn't exist
644 * @param $label String
646 * @param $align String
647 * @param $params Array
648 * @param $framed Boolean
649 * @param $manualthumb String
652 public static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt,
653 $align = 'right', $params = array(), $framed = false , $manualthumb = "" )
655 $frameParams = array(
661 $frameParams['framed'] = true;
663 if ( $manualthumb ) {
664 $frameParams['manualthumb'] = $manualthumb;
666 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
670 * @param $title Title
672 * @param array $frameParams
673 * @param array $handlerParams
675 * @param string $query
678 public static function makeThumbLink2( Title
$title, $file, $frameParams = array(),
679 $handlerParams = array(), $time = false, $query = "" )
681 global $wgStylePath, $wgContLang;
682 $exists = $file && $file->exists();
686 $hp =& $handlerParams;
688 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
689 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
690 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
691 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
692 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
694 if ( empty( $hp['width'] ) ) {
695 // Reduce width for upright images when parameter 'upright' is used
696 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
701 $outerWidth = $hp['width'] +
2;
703 if ( isset( $fp['manualthumb'] ) ) {
704 # Use manually specified thumbnail
705 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
706 if ( $manual_title ) {
707 $manual_img = wfFindFile( $manual_title );
709 $thumb = $manual_img->getUnscaledThumb( $hp );
714 } elseif ( isset( $fp['framed'] ) ) {
715 // Use image dimensions, don't scale
716 $thumb = $file->getUnscaledThumb( $hp );
718 # Do not present an image bigger than the source, for bitmap-style images
719 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
720 $srcWidth = $file->getWidth( $page );
721 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
722 $hp['width'] = $srcWidth;
724 $thumb = $file->transform( $hp );
728 $outerWidth = $thumb->getWidth() +
2;
730 $outerWidth = $hp['width'] +
2;
734 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
735 # So we don't need to pass it here in $query. However, the URL for the
736 # zoom icon still needs it, so we make a unique query for it. See bug 14771
737 $url = $title->getLocalURL( $query );
739 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
742 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
744 $s .= self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
746 } elseif ( !$thumb ) {
747 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
752 'title' => $fp['title'],
753 'img-class' => 'thumbimage' );
754 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
755 $s .= $thumb->toHtml( $params );
756 if ( isset( $fp['framed'] ) ) {
759 $zoomIcon = Html
::rawElement( 'div', array( 'class' => 'magnify' ),
760 Html
::rawElement( 'a', array(
762 'class' => 'internal',
763 'title' => wfMsg( 'thumbnail-more' ) ),
764 Html
::element( 'img', array(
765 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ?
'-rtl' : '' ) . '.png',
771 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
772 return str_replace( "\n", ' ', $s );
776 * Make a "broken" link to an image
778 * @param $title Title object
779 * @param $html String: link label in htmlescaped text form
780 * @param $query String: query string
781 * @param $trail String: link trail (HTML fragment)
782 * @param $prefix String: link prefix (HTML fragment)
783 * @param $time Boolean: a file of a certain timestamp was requested
786 public static function makeBrokenImageLinkObj( $title, $html = '', $query = '', $trail = '', $prefix = '', $time = false ) {
787 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
788 if ( ! $title instanceof Title
) {
789 return "<!-- ERROR -->{$prefix}{$html}{$trail}";
791 wfProfileIn( __METHOD__
);
792 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
794 list( $inside, $trail ) = self
::splitTrail( $trail );
796 $html = htmlspecialchars( $title->getPrefixedText() );
798 if ( ( $wgUploadMissingFileUrl ||
$wgUploadNavigationUrl ||
$wgEnableUploads ) && !$currentExists ) {
799 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
802 wfProfileOut( __METHOD__
);
803 return self
::linkKnown( $title, "$prefix$html$inside", array(), $query ) . $trail;
806 $href = self
::getUploadUrl( $title, $query );
808 wfProfileOut( __METHOD__
);
809 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
810 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
811 "$prefix$html$inside</a>$trail";
813 wfProfileOut( __METHOD__
);
814 return self
::linkKnown( $title, "$prefix$html$inside", array(), $query ) . $trail;
819 * Get the URL to upload a certain file
821 * @param $destFile Title object of the file to upload
822 * @param $query String: urlencoded query string to prepend
823 * @return String: urlencoded URL
825 protected static function getUploadUrl( $destFile, $query = '' ) {
826 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
827 $q = 'wpDestFile=' . $destFile->getPartialUrl();
831 if ( $wgUploadMissingFileUrl ) {
832 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
833 } elseif( $wgUploadNavigationUrl ) {
834 return wfAppendQuery( $wgUploadNavigationUrl, $q );
836 $upload = SpecialPage
::getTitleFor( 'Upload' );
837 return $upload->getLocalUrl( $q );
842 * Create a direct link to a given uploaded file.
844 * @param $title Title object.
845 * @param $html String: pre-sanitized HTML
846 * @param $time string: MW timestamp of file creation time
847 * @return String: HTML
849 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
850 $img = wfFindFile( $title, array( 'time' => $time ) );
851 return self
::makeMediaLinkFile( $title, $img, $html );
855 * Create a direct link to a given uploaded file.
856 * This will make a broken link if $file is false.
858 * @param $title Title object.
859 * @param $file File|bool mixed File object or false
860 * @param $html String: pre-sanitized HTML
861 * @return String: HTML
863 * @todo Handle invalid or missing images better.
865 public static function makeMediaLinkFile( Title
$title, $file, $html = '' ) {
866 if ( $file && $file->exists() ) {
867 $url = $file->getURL();
870 $url = self
::getUploadUrl( $title );
873 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES
);
877 $u = htmlspecialchars( $url );
878 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$html}</a>";
882 * Make a link to a special page given its name and, optionally,
883 * a message key from the link text.
884 * Usage example: Linker::specialLink( 'Recentchanges' )
888 public static function specialLink( $name, $key = '' ) {
890 $key = strtolower( $name );
893 return self
::linkKnown( SpecialPage
::getTitleFor( $name ) , wfMsg( $key ) );
897 * Make an external link
898 * @param $url String: URL to link to
899 * @param $text String: text of link
900 * @param $escape Boolean: do we escape the link text?
901 * @param $linktype String: type of external link. Gets added to the classes
902 * @param $attribs Array of extra attributes to <a>
905 public static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
908 $class .= " $linktype";
910 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
911 $class .= " {$attribs['class']}";
913 $attribs['class'] = $class;
916 $text = htmlspecialchars( $text );
919 $success = wfRunHooks( 'LinkerMakeExternalLink',
920 array( &$url, &$text, &$link, &$attribs, $linktype ) );
922 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
925 $attribs['href'] = $url;
926 return Html
::rawElement( 'a', $attribs, $text );
930 * Make user link (or user contributions for unregistered users)
931 * @param $userId Integer: user id in database.
932 * @param $userName String: user name in database.
933 * @param $altUserName String: text to display instead of the user name (optional)
934 * @return String: HTML fragment
935 * @since 1.19 Method exists for a long time. $displayText was added in 1.19.
937 public static function userLink( $userId, $userName, $altUserName = false ) {
938 if ( $userId == 0 ) {
939 $page = SpecialPage
::getTitleFor( 'Contributions', $userName );
941 $page = Title
::makeTitle( NS_USER
, $userName );
946 htmlspecialchars( $altUserName !== false ?
$altUserName : $userName ),
947 array( 'class' => 'mw-userlink' )
952 * Generate standard user tool links (talk, contributions, block link, etc.)
954 * @param $userId Integer: user identifier
955 * @param $userText String: user name or IP address
956 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
957 * red if the user has no edits?
958 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK and Linker::TOOL_LINKS_EMAIL)
959 * @param $edits Integer: user edit count (optional, for performance)
960 * @return String: HTML fragment
962 public static function userToolLinks(
963 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
965 global $wgUser, $wgDisableAnonTalk, $wgLang;
966 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
967 $blockable = !( $flags & self
::TOOL_LINKS_NOBLOCK
);
968 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
&& $userId;
972 $items[] = self
::userTalkLink( $userId, $userText );
975 // check if the user has an edit
977 if ( $redContribsWhenNoEdits ) {
978 $count = !is_null( $edits ) ?
$edits : User
::edits( $userId );
980 $attribs['class'] = 'new';
983 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
985 $items[] = self
::link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
987 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
988 $items[] = self
::blockLink( $userId, $userText );
991 if ( $addEmailLink && $wgUser->canSendEmail() ) {
992 $items[] = self
::emailLink( $userId, $userText );
995 wfRunHooks( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
998 return ' <span class="mw-usertoollinks">' . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped() . '</span>';
1005 * Alias for userToolLinks( $userId, $userText, true );
1006 * @param $userId Integer: user identifier
1007 * @param $userText String: user name or IP address
1008 * @param $edits Integer: user edit count (optional, for performance)
1011 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1012 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
1017 * @param $userId Integer: user id in database.
1018 * @param $userText String: user name in database.
1019 * @return String: HTML fragment with user talk link
1021 public static function userTalkLink( $userId, $userText ) {
1022 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
1023 $userTalkLink = self
::link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
1024 return $userTalkLink;
1028 * @param $userId Integer: userid
1029 * @param $userText String: user name in database.
1030 * @return String: HTML fragment with block link
1032 public static function blockLink( $userId, $userText ) {
1033 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1034 $blockLink = self
::link( $blockPage, wfMsgHtml( 'blocklink' ) );
1039 * @param $userId Integer: userid
1040 * @param $userText String: user name in database.
1041 * @return String: HTML fragment with e-mail user link
1043 public static function emailLink( $userId, $userText ) {
1044 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1045 $emailLink = self
::link( $emailPage, wfMsgHtml( 'emaillink' ) );
1050 * Generate a user link if the current user is allowed to view it
1051 * @param $rev Revision object.
1052 * @param $isPublic Boolean: show only if all users can see it
1053 * @return String: HTML fragment
1055 public static function revUserLink( $rev, $isPublic = false ) {
1056 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1057 $link = wfMsgHtml( 'rev-deleted-user' );
1058 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1059 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1060 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1062 $link = wfMsgHtml( 'rev-deleted-user' );
1064 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1065 return '<span class="history-deleted">' . $link . '</span>';
1071 * Generate a user tool link cluster if the current user is allowed to view it
1072 * @param $rev Revision object.
1073 * @param $isPublic Boolean: show only if all users can see it
1074 * @return string HTML
1076 public static function revUserTools( $rev, $isPublic = false ) {
1077 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1078 $link = wfMsgHtml( 'rev-deleted-user' );
1079 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1080 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1081 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1082 $link = self
::userLink( $userId, $userText ) .
1083 ' ' . self
::userToolLinks( $userId, $userText );
1085 $link = wfMsgHtml( 'rev-deleted-user' );
1087 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1088 return ' <span class="history-deleted">' . $link . '</span>';
1094 * This function is called by all recent changes variants, by the page history,
1095 * and by the user contributions list. It is responsible for formatting edit
1096 * comments. It escapes any HTML in the comment, but adds some CSS to format
1097 * auto-generated comments (from section editing) and formats [[wikilinks]].
1099 * @author Erik Moeller <moeller@scireview.de>
1101 * Note: there's not always a title to pass to this function.
1102 * Since you can't set a default parameter for a reference, I've turned it
1103 * temporarily to a value pass. Should be adjusted further. --brion
1105 * @param $comment String
1106 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1107 * @param $local Boolean: whether section links should refer to local page
1108 * @return mixed|String
1110 public static function formatComment( $comment, $title = null, $local = false ) {
1111 wfProfileIn( __METHOD__
);
1113 # Sanitize text a bit:
1114 $comment = str_replace( "\n", " ", $comment );
1115 # Allow HTML entities (for bug 13815)
1116 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1118 # Render autocomments and make links:
1119 $comment = self
::formatAutocomments( $comment, $title, $local );
1120 $comment = self
::formatLinksInComment( $comment, $title, $local );
1122 wfProfileOut( __METHOD__
);
1129 static $autocommentTitle;
1130 static $autocommentLocal;
1133 * The pattern for autogen comments is / * foo * /, which makes for
1135 * We look for all comments, match any text before and after the comment,
1136 * add a separator where needed and format the comment itself with CSS
1137 * Called by Linker::formatComment.
1139 * @param $comment String: comment text
1140 * @param $title Title|null An optional title object used to links to sections
1141 * @param $local Boolean: whether section links should refer to local page
1142 * @return String: formatted comment
1144 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1146 self
::$autocommentTitle = $title;
1147 self
::$autocommentLocal = $local;
1148 $comment = preg_replace_callback(
1149 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1150 array( 'Linker', 'formatAutocommentsCallback' ),
1152 self
::$autocommentTitle = null;
1153 self
::$autocommentLocal = null;
1161 private static function formatAutocommentsCallback( $match ) {
1163 $title = self
::$autocommentTitle;
1164 $local = self
::$autocommentLocal;
1173 # Remove links that a user may have manually put in the autosummary
1174 # This could be improved by copying as much of Parser::stripSectionName as desired.
1175 $section = str_replace( '[[:', '', $section );
1176 $section = str_replace( '[[', '', $section );
1177 $section = str_replace( ']]', '', $section );
1179 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1181 $sectionTitle = Title
::newFromText( '#' . $section );
1183 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1184 $title->getDBkey(), $section );
1186 if ( $sectionTitle ) {
1187 $link = self
::link( $sectionTitle,
1188 $wgLang->getArrow(), array(), array(),
1195 # written summary $presep autocomment (summary /* section */)
1196 $pre .= wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) );
1199 # autocomment $postsep written summary (/* section */ summary)
1200 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1202 $auto = '<span class="autocomment">' . $auto . '</span>';
1203 $comment = $pre . $link . $wgLang->getDirMark() . '<span dir="auto">' . $auto . $post . '</span>';
1210 static $commentContextTitle;
1211 static $commentLocal;
1214 * Formats wiki links and media links in text; all other wiki formatting
1217 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1218 * @param $comment String: text to format links in
1219 * @param $title Title|null An optional title object used to links to sections
1220 * @param $local Boolean: whether section links should refer to local page
1223 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1224 self
::$commentContextTitle = $title;
1225 self
::$commentLocal = $local;
1226 $html = preg_replace_callback(
1227 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1228 array( 'Linker', 'formatLinksInCommentCallback' ),
1230 self
::$commentContextTitle = null;
1231 self
::$commentLocal = null;
1239 protected static function formatLinksInCommentCallback( $match ) {
1242 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1243 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1245 $comment = $match[0];
1247 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1248 if ( strpos( $match[1], '%' ) !== false ) {
1249 $match[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $match[1] ) );
1252 # Handle link renaming [[foo|text]] will show link as "text"
1253 if ( $match[3] != "" ) {
1258 $submatch = array();
1260 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1261 # Media link; trail not supported.
1262 $linkRegexp = '/\[\[(.*?)\]\]/';
1263 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1265 $thelink = self
::makeMediaLinkObj( $title, $text );
1268 # Other kind of link
1269 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1270 $trail = $submatch[1];
1274 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1275 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1276 $match[1] = substr( $match[1], 1 );
1277 list( $inside, $trail ) = self
::splitTrail( $trail );
1280 $linkTarget = self
::normalizeSubpageLink( self
::$commentContextTitle,
1281 $match[1], $linkText );
1283 $target = Title
::newFromText( $linkTarget );
1285 if ( $target->getText() == '' && $target->getInterwiki() === ''
1286 && !self
::$commentLocal && self
::$commentContextTitle )
1288 $newTarget = clone ( self
::$commentContextTitle );
1289 $newTarget->setFragment( '#' . $target->getFragment() );
1290 $target = $newTarget;
1292 $thelink = self
::link(
1299 // If the link is still valid, go ahead and replace it in!
1300 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1307 * @param $contextTitle Title
1312 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1315 # :Foobar -- override special treatment of prefix (images, language links)
1316 # /Foobar -- convert to CurrentPage/Foobar
1317 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1318 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1319 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1321 wfProfileIn( __METHOD__
);
1322 $ret = $target; # default return value is no change
1324 # Some namespaces don't allow subpages,
1325 # so only perform processing if subpages are allowed
1326 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1327 $hash = strpos( $target, '#' );
1328 if ( $hash !== false ) {
1329 $suffix = substr( $target, $hash );
1330 $target = substr( $target, 0, $hash );
1335 $target = trim( $target );
1336 # Look at the first character
1337 if ( $target != '' && $target[0] === '/' ) {
1338 # / at end means we don't want the slash to be shown
1340 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1341 if ( $trailingSlashes ) {
1342 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1344 $noslash = substr( $target, 1 );
1347 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1348 if ( $text === '' ) {
1349 $text = $target . $suffix;
1350 } # this might be changed for ugliness reasons
1352 # check for .. subpage backlinks
1354 $nodotdot = $target;
1355 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1357 $nodotdot = substr( $nodotdot, 3 );
1359 if ( $dotdotcount > 0 ) {
1360 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1361 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1362 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1363 # / at the end means don't show full path
1364 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1365 $nodotdot = substr( $nodotdot, 0, -1 );
1366 if ( $text === '' ) {
1367 $text = $nodotdot . $suffix;
1370 $nodotdot = trim( $nodotdot );
1371 if ( $nodotdot != '' ) {
1372 $ret .= '/' . $nodotdot;
1380 wfProfileOut( __METHOD__
);
1385 * Wrap a comment in standard punctuation and formatting if
1386 * it's non-empty, otherwise return empty string.
1388 * @param $comment String
1389 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1390 * @param $local Boolean: whether section links should refer to local page
1394 public static function commentBlock( $comment, $title = null, $local = false ) {
1395 // '*' used to be the comment inserted by the software way back
1396 // in antiquity in case none was provided, here for backwards
1397 // compatability, acc. to brion -ævar
1398 if ( $comment == '' ||
$comment == '*' ) {
1401 $formatted = self
::formatComment( $comment, $title, $local );
1402 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1403 return " <span class=\"comment\">$formatted</span>";
1408 * Wrap and format the given revision's comment block, if the current
1409 * user is allowed to view it.
1411 * @param $rev Revision object
1412 * @param $local Boolean: whether section links should refer to local page
1413 * @param $isPublic Boolean: show only if all users can see it
1414 * @return String: HTML fragment
1416 public static function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1417 if ( $rev->getRawComment() == "" ) {
1420 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1421 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1422 } elseif ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1423 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1424 $rev->getTitle(), $local );
1426 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1428 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1429 return " <span class=\"history-deleted\">$block</span>";
1438 public static function formatRevisionSize( $size ) {
1440 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1443 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1444 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1446 $stxt = htmlspecialchars( $stxt );
1447 return "<span class=\"history-size\">$stxt</span>";
1451 * Add another level to the Table of Contents
1455 public static function tocIndent() {
1460 * Finish one or more sublevels on the Table of Contents
1464 public static function tocUnindent( $level ) {
1465 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1469 * parameter level defines if we are on an indentation level
1473 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1474 $classes = "toclevel-$level";
1475 if ( $sectionIndex !== false ) {
1476 $classes .= " tocsection-$sectionIndex";
1478 return "\n<li class=\"$classes\"><a href=\"#" .
1479 $anchor . '"><span class="tocnumber">' .
1480 $tocnumber . '</span> <span class="toctext">' .
1481 $tocline . '</span></a>';
1485 * End a Table Of Contents line.
1486 * tocUnindent() will be used instead if we're ending a line below
1490 public static function tocLineEnd() {
1495 * Wraps the TOC in a table and provides the hide/collapse javascript.
1497 * @param $toc String: html of the Table Of Contents
1498 * @param $lang mixed: Language code for the toc title
1499 * @return String: full html of the TOC
1501 public static function tocList( $toc, $lang = false ) {
1502 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1504 '<table id="toc" class="toc"><tr><td>'
1505 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1507 . "</ul>\n</td></tr></table>\n";
1511 * Generate a table of contents from a section tree
1514 * @param $tree array Return value of ParserOutput::getSections()
1515 * @return String: HTML fragment
1517 public static function generateTOC( $tree ) {
1520 foreach ( $tree as $section ) {
1521 if ( $section['toclevel'] > $lastLevel )
1522 $toc .= self
::tocIndent();
1523 elseif ( $section['toclevel'] < $lastLevel )
1524 $toc .= self
::tocUnindent(
1525 $lastLevel - $section['toclevel'] );
1527 $toc .= self
::tocLineEnd();
1529 $toc .= self
::tocLine( $section['anchor'],
1530 $section['line'], $section['number'],
1531 $section['toclevel'], $section['index'] );
1532 $lastLevel = $section['toclevel'];
1534 $toc .= self
::tocLineEnd();
1535 return self
::tocList( $toc );
1539 * Create a headline for content
1541 * @param $level Integer: the level of the headline (1-6)
1542 * @param $attribs String: any attributes for the headline, starting with
1543 * a space and ending with '>'
1544 * This *must* be at least '>' for no attribs
1545 * @param $anchor String: the anchor to give the headline (the bit after the #)
1546 * @param $html String: html for the text of the header
1547 * @param $link String: HTML to add for the section edit link
1548 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1549 * backward compatibility (false to omit)
1551 * @return String: HTML headline
1553 public static function makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor = false ) {
1554 $ret = "<h$level$attribs"
1556 . " <span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1558 if ( $legacyAnchor !== false ) {
1559 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1565 * Split a link trail, return the "inside" portion and the remainder of the trail
1566 * as a two-element array
1569 static function splitTrail( $trail ) {
1571 $regex = $wgContLang->linkTrail();
1573 if ( $trail !== '' ) {
1575 if ( preg_match( $regex, $trail, $m ) ) {
1580 return array( $inside, $trail );
1584 * Generate a rollback link for a given revision. Currently it's the
1585 * caller's responsibility to ensure that the revision is the top one. If
1586 * it's not, of course, the user will get an error message.
1588 * If the calling page is called with the parameter &bot=1, all rollback
1589 * links also get that parameter. It causes the edit itself and the rollback
1590 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1591 * changes, so this allows sysops to combat a busy vandal without bothering
1594 * @param $rev Revision object
1597 public static function generateRollback( $rev ) {
1598 return '<span class="mw-rollback-link">['
1599 . self
::buildRollbackLink( $rev )
1604 * Build a raw rollback link, useful for collections of "tool" links
1606 * @param $rev Revision object
1607 * @return String: HTML fragment
1609 public static function buildRollbackLink( $rev ) {
1610 global $wgRequest, $wgUser;
1611 $title = $rev->getTitle();
1613 'action' => 'rollback',
1614 'from' => $rev->getUserText(),
1615 'token' => $wgUser->getEditToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1617 if ( $wgRequest->getBool( 'bot' ) ) {
1618 $query['bot'] = '1';
1619 $query['hidediff'] = '1'; // bug 15999
1623 wfMsgHtml( 'rollbacklink' ),
1624 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1626 array( 'known', 'noclasses' )
1631 * Returns HTML for the "templates used on this page" list.
1633 * @param $templates Array of templates from Article::getUsedTemplate
1635 * @param $preview Boolean: whether this is for a preview
1636 * @param $section Boolean: whether this is for a section edit
1637 * @return String: HTML output
1639 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1640 wfProfileIn( __METHOD__
);
1643 if ( count( $templates ) > 0 ) {
1644 # Do a batch existence check
1645 $batch = new LinkBatch
;
1646 foreach ( $templates as $title ) {
1647 $batch->addObj( $title );
1651 # Construct the HTML
1652 $outText = '<div class="mw-templatesUsedExplanation">';
1654 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1655 } elseif ( $section ) {
1656 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1658 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1660 $outText .= "</div><ul>\n";
1662 usort( $templates, array( 'Title', 'compare' ) );
1663 foreach ( $templates as $titleObj ) {
1664 $r = $titleObj->getRestrictions( 'edit' );
1665 if ( in_array( 'sysop', $r ) ) {
1666 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1667 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1668 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1672 if ( $titleObj->quickUserCan( 'edit' ) ) {
1673 $editLink = self
::link(
1675 wfMsg( 'editlink' ),
1677 array( 'action' => 'edit' )
1680 $editLink = self
::link(
1682 wfMsg( 'viewsourcelink' ),
1684 array( 'action' => 'edit' )
1687 $outText .= '<li>' . self
::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1689 $outText .= '</ul>';
1691 wfProfileOut( __METHOD__
);
1696 * Returns HTML for the "hidden categories on this page" list.
1698 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1700 * @return String: HTML output
1702 public static function formatHiddenCategories( $hiddencats ) {
1704 wfProfileIn( __METHOD__
);
1707 if ( count( $hiddencats ) > 0 ) {
1708 # Construct the HTML
1709 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1710 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1711 $outText .= "</div><ul>\n";
1713 foreach ( $hiddencats as $titleObj ) {
1714 $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
1716 $outText .= '</ul>';
1718 wfProfileOut( __METHOD__
);
1723 * Format a size in bytes for output, using an appropriate
1724 * unit (B, KB, MB or GB) according to the magnitude in question
1726 * @param $size int Size to format
1729 public static function formatSize( $size ) {
1731 return htmlspecialchars( $wgLang->formatSize( $size ) );
1735 * Given the id of an interface element, constructs the appropriate title
1736 * attribute from the system messages. (Note, this is usually the id but
1737 * isn't always, because sometimes the accesskey needs to go on a different
1738 * element than the id, for reverse-compatibility, etc.)
1740 * @param $name String: id of the element, minus prefixes.
1741 * @param $options Mixed: null or the string 'withaccess' to add an access-
1743 * @return String: contents of the title attribute (which you must HTML-
1744 * escape), or false for no title attribute
1746 public static function titleAttrib( $name, $options = null ) {
1747 wfProfileIn( __METHOD__
);
1749 $message = wfMessage( "tooltip-$name" );
1751 if ( !$message->exists() ) {
1754 $tooltip = $message->text();
1755 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1756 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1757 # Message equal to '-' means suppress it.
1758 if ( $tooltip == '-' ) {
1763 if ( $options == 'withaccess' ) {
1764 $accesskey = self
::accesskey( $name );
1765 if ( $accesskey !== false ) {
1766 if ( $tooltip === false ||
$tooltip === '' ) {
1767 $tooltip = "[$accesskey]";
1769 $tooltip .= " [$accesskey]";
1774 wfProfileOut( __METHOD__
);
1778 static $accesskeycache;
1781 * Given the id of an interface element, constructs the appropriate
1782 * accesskey attribute from the system messages. (Note, this is usually
1783 * the id but isn't always, because sometimes the accesskey needs to go on
1784 * a different element than the id, for reverse-compatibility, etc.)
1786 * @param $name String: id of the element, minus prefixes.
1787 * @return String: contents of the accesskey attribute (which you must HTML-
1788 * escape), or false for no accesskey attribute
1790 public static function accesskey( $name ) {
1791 if ( isset( self
::$accesskeycache[$name] ) ) {
1792 return self
::$accesskeycache[$name];
1794 wfProfileIn( __METHOD__
);
1796 $message = wfMessage( "accesskey-$name" );
1798 if ( !$message->exists() ) {
1801 $accesskey = $message->plain();
1802 if ( $accesskey === '' ||
$accesskey === '-' ) {
1803 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
1804 # attribute, but this is broken for accesskey: that might be a useful
1810 wfProfileOut( __METHOD__
);
1811 return self
::$accesskeycache[$name] = $accesskey;
1815 * Get a revision-deletion link, or disabled link, or nothing, depending
1816 * on user permissions & the settings on the revision.
1818 * Will use forward-compatible revision ID in the Special:RevDelete link
1819 * if possible, otherwise the timestamp-based ID which may break after
1823 * @param Revision $rev
1824 * @param Revision $title
1825 * @return string HTML fragment
1827 public static function getRevDeleteLink( User
$user, Revision
$rev, Title
$title ) {
1828 $canHide = $user->isAllowed( 'deleterevision' );
1829 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
1833 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
1834 return Linker
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
1836 if ( $rev->getId() ) {
1837 // RevDelete links using revision ID are stable across
1838 // page deletion and undeletion; use when possible.
1840 'type' => 'revision',
1841 'target' => $title->getPrefixedDBkey(),
1842 'ids' => $rev->getId()
1845 // Older deleted entries didn't save a revision ID.
1846 // We have to refer to these by timestamp, ick!
1848 'type' => 'archive',
1849 'target' => $title->getPrefixedDBkey(),
1850 'ids' => $rev->getTimestamp()
1853 return Linker
::revDeleteLink( $query,
1854 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
1859 * Creates a (show/hide) link for deleting revisions/log entries
1861 * @param $query Array: query parameters to be passed to link()
1862 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1863 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1865 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1866 * span to allow for customization of appearance with CSS
1868 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1869 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1870 $html = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1871 $tag = $restricted ?
'strong' : 'span';
1872 $link = self
::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
1873 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $link )->escaped() );
1877 * Creates a dead (show/hide) link for deleting revisions/log entries
1879 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1881 * @return string HTML text wrapped in a span to allow for customization
1882 * of appearance with CSS
1884 public static function revDeleteLinkDisabled( $delete = true ) {
1885 $html = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1886 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $html )->escaped() );
1889 /* Deprecated methods */
1892 * @deprecated since 1.16 Use link()
1894 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1895 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1897 * @param $title String: The text of the title
1898 * @param $text String: Link text
1899 * @param $query String: Optional query part
1900 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1901 * be included in the link text. Other characters will be appended after
1902 * the end of the link.
1905 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1906 wfDeprecated( __METHOD__
, '1.16' );
1908 $nt = Title
::newFromText( $title );
1909 if ( $nt instanceof Title
) {
1910 return self
::makeBrokenLinkObj( $nt, $text, $query, $trail );
1912 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
1913 return $text == '' ?
$title : $text;
1918 * @deprecated since 1.16 Use link()
1920 * Make a link for a title which may or may not be in the database. If you need to
1921 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1922 * call to this will result in a DB query.
1924 * @param $nt Title: the title object to make the link from, e.g. from
1925 * Title::newFromText.
1926 * @param $text String: link text
1927 * @param $query String: optional query part
1928 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1929 * be included in the link text. Other characters will be appended after
1930 * the end of the link.
1931 * @param $prefix String: optional prefix. As trail, only before instead of after.
1934 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1935 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
1937 wfProfileIn( __METHOD__
);
1938 $query = wfCgiToArray( $query );
1939 list( $inside, $trail ) = self
::splitTrail( $trail );
1940 if ( $text === '' ) {
1941 $text = self
::linkText( $nt );
1944 $ret = self
::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1946 wfProfileOut( __METHOD__
);
1951 * @deprecated since 1.16 Use link()
1953 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1954 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1957 * @param $title Title object of target page
1958 * @param $text String: text to replace the title
1959 * @param $query String: link target
1960 * @param $trail String: text after link
1961 * @param $prefix String: text before link text
1962 * @param $aprops String: extra attributes to the a-element
1963 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1964 * @return string the a-element
1966 static function makeKnownLinkObj(
1967 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
1969 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
1971 wfProfileIn( __METHOD__
);
1973 if ( $text == '' ) {
1974 $text = self
::linkText( $title );
1976 $attribs = Sanitizer
::mergeAttributes(
1977 Sanitizer
::decodeTagAttributes( $aprops ),
1978 Sanitizer
::decodeTagAttributes( $style )
1980 $query = wfCgiToArray( $query );
1981 list( $inside, $trail ) = self
::splitTrail( $trail );
1983 $ret = self
::link( $title, "$prefix$text$inside", $attribs, $query,
1984 array( 'known', 'noclasses' ) ) . $trail;
1986 wfProfileOut( __METHOD__
);
1991 * @deprecated since 1.16 Use link()
1993 * Make a red link to the edit page of a given title.
1995 * @param $title Title object of the target page
1996 * @param $text String: Link text
1997 * @param $query String: Optional query part
1998 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1999 * be included in the link text. Other characters will be appended after
2000 * the end of the link.
2001 * @param $prefix String: Optional prefix
2004 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
2005 wfDeprecated( __METHOD__
, '1.16' );
2007 wfProfileIn( __METHOD__
);
2009 list( $inside, $trail ) = self
::splitTrail( $trail );
2010 if ( $text === '' ) {
2011 $text = self
::linkText( $title );
2014 $ret = self
::link( $title, "$prefix$text$inside", array(),
2015 wfCgiToArray( $query ), 'broken' ) . $trail;
2017 wfProfileOut( __METHOD__
);
2022 * @deprecated since 1.16 Use link()
2024 * Make a coloured link.
2026 * @param $nt Title object of the target page
2027 * @param $colour Integer: colour of the link
2028 * @param $text String: link text
2029 * @param $query String: optional query part
2030 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2031 * be included in the link text. Other characters will be appended after
2032 * the end of the link.
2033 * @param $prefix String: Optional prefix
2036 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2037 wfDeprecated( __METHOD__
, '1.16' );
2039 if ( $colour != '' ) {
2040 $style = self
::getInternalLinkAttributesObj( $nt, $text, $colour );
2044 return self
::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2048 * Returns the attributes for the tooltip and access key.
2051 public static function tooltipAndAccesskeyAttribs( $name ) {
2052 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2053 # no attribute" instead of "output '' as value for attribute", this
2054 # would be three lines.
2056 'title' => self
::titleAttrib( $name, 'withaccess' ),
2057 'accesskey' => self
::accesskey( $name )
2059 if ( $attribs['title'] === false ) {
2060 unset( $attribs['title'] );
2062 if ( $attribs['accesskey'] === false ) {
2063 unset( $attribs['accesskey'] );
2069 * Returns raw bits of HTML, use titleAttrib()
2070 * @return null|string
2072 public static function tooltip( $name, $options = null ) {
2073 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2074 # no attribute" instead of "output '' as value for attribute", this
2075 # would be two lines.
2076 $tooltip = self
::titleAttrib( $name, $options );
2077 if ( $tooltip === false ) {
2080 return Xml
::expandAttributes( array(
2092 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2093 * into static calls to the new Linker for backwards compatibility.
2095 * @param $fname String Name of called method
2096 * @param $args Array Arguments to the method
2099 public function __call( $fname, $args ) {
2100 return call_user_func_array( array( 'Linker', $fname ), $args );