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'.
23 * @deprecated since 1.18 Just pass the external class directly to something using Html::expandAttributes
25 static function getExternalLinkAttributes( $class = 'external' ) {
26 wfDeprecated( __METHOD__
);
27 return self
::getLinkAttributesInternal( '', $class );
31 * Get the appropriate HTML attributes to add to the "a" element of an in-
34 * @param $title String: the title text for the link, URL-encoded (???) but
36 * @param $unused String: unused
37 * @param $class String: the contents of the class attribute; if an empty
38 * string is passed, which is the default value, defaults to 'external'.
40 static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
43 # @todo FIXME: We have a whole bunch of handling here that doesn't happen in
44 # getExternalLinkAttributes, why?
45 $title = urldecode( $title );
46 $title = $wgContLang->checkTitleEncoding( $title );
47 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
49 return self
::getLinkAttributesInternal( $title, $class );
53 * Get the appropriate HTML attributes to add to the "a" element of an in-
56 * @param $title String: the title text for the link, URL-encoded (???) but
58 * @param $unused String: unused
59 * @param $class String: the contents of the class attribute, default none
61 static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
62 $title = urldecode( $title );
63 $title = str_replace( '_', ' ', $title );
64 return self
::getLinkAttributesInternal( $title, $class );
68 * Get the appropriate HTML attributes to add to the "a" element of an in-
69 * ternal link, given the Title object for the page we want to link to.
72 * @param $unused String: unused
73 * @param $class String: the contents of the class attribute, default none
74 * @param $title Mixed: optional (unescaped) string to use in the title
75 * attribute; if false, default to the name of the page we're linking to
77 static function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
78 if ( $title === false ) {
79 $title = $nt->getPrefixedText();
81 return self
::getLinkAttributesInternal( $title, $class );
85 * Common code for getLinkAttributesX functions
87 * @param $title string
88 * @param $class string
92 private static function getLinkAttributesInternal( $title, $class ) {
93 $title = htmlspecialchars( $title );
94 $class = htmlspecialchars( $class );
97 $r .= " class=\"$class\"";
100 $r .= " title=\"$title\"";
106 * Return the CSS colour of a known link
108 * @param $t Title object
109 * @param $threshold Integer: user defined threshold
110 * @return String: CSS class
112 static function getLinkColour( $t, $threshold ) {
114 if ( $t->isRedirect() ) {
116 $colour = 'mw-redirect';
117 } elseif ( $threshold > 0 &&
118 $t->exists() && $t->getLength() < $threshold &&
119 $t->isContentPage() ) {
127 * This function returns an HTML link to the given target. It serves a few
129 * 1) If $target is a Title, the correct URL to link to will be figured
131 * 2) It automatically adds the usual classes for various types of link
132 * targets: "new" for red links, "stub" for short articles, etc.
133 * 3) It escapes all attribute values safely so there's no risk of XSS.
134 * 4) It provides a default tooltip if the target is a Title (the page
135 * name of the target).
136 * link() replaces the old functions in the makeLink() family.
138 * @param $target Title Can currently only be a Title, but this may
139 * change to support Images, literal URLs, etc.
140 * @param $html string The HTML contents of the <a> element, i.e.,
141 * the link text. This is raw HTML and will not be escaped. If null,
142 * defaults to the prefixed text of the Title; or if the Title is just a
143 * fragment, the contents of the fragment.
144 * @param $customAttribs array A key => value array of extra HTML attri-
145 * butes, such as title and class. (href is ignored.) Classes will be
146 * merged with the default classes, while other attributes will replace
147 * default attributes. All passed attribute values will be HTML-escaped.
148 * A false attribute value means to suppress that attribute.
149 * @param $query array The query string to append to the URL
150 * you're linking to, in key => value array form. Query keys and values
151 * will be URL-encoded.
152 * @param $options string|array String or array of strings:
153 * 'known': Page is known to exist, so don't check if it does.
154 * 'broken': Page is known not to exist, so don't check if it does.
155 * 'noclasses': Don't add any classes automatically (includes "new",
156 * "stub", "mw-redirect", "extiw"). Only use the class attribute
157 * provided, if any, so you get a simple blue link with no funny i-
159 * 'forcearticlepath': Use the article path always, even with a querystring.
160 * Has compatibility issues on some setups, so avoid wherever possible.
161 * @return string HTML <a> attribute
163 public static function link(
164 $target, $html = null, $customAttribs = array(), $query = array(), $options = array()
166 wfProfileIn( __METHOD__
);
167 if ( !$target instanceof Title
) {
168 wfProfileOut( __METHOD__
);
169 return "<!-- ERROR -->$html";
171 $options = (array)$options;
173 $dummy = new DummyLinker
; // dummy linker instance for bc on the hooks
176 if ( !wfRunHooks( 'LinkBegin', array( $dummy, $target, &$html,
177 &$customAttribs, &$query, &$options, &$ret ) ) ) {
178 wfProfileOut( __METHOD__
);
182 # Normalize the Title if it's a special page
183 $target = self
::normaliseSpecialPage( $target );
185 # If we don't know whether the page exists, let's find out.
186 wfProfileIn( __METHOD__
. '-checkPageExistence' );
187 if ( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
188 if ( $target->isKnown() ) {
189 $options[] = 'known';
191 $options[] = 'broken';
194 wfProfileOut( __METHOD__
. '-checkPageExistence' );
197 if ( in_array( "forcearticlepath", $options ) && $query ) {
202 # Note: we want the href attribute first, for prettiness.
203 $attribs = array( 'href' => self
::linkUrl( $target, $query, $options ) );
204 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
205 $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
208 $attribs = array_merge(
210 self
::linkAttribs( $target, $customAttribs, $options )
212 if ( is_null( $html ) ) {
213 $html = self
::linkText( $target );
217 if ( wfRunHooks( 'LinkEnd', array( $dummy, $target, $options, &$html, &$attribs, &$ret ) ) ) {
218 $ret = Html
::rawElement( 'a', $attribs, $html );
221 wfProfileOut( __METHOD__
);
226 * Identical to link(), except $options defaults to 'known'.
228 public static function linkKnown(
229 $target, $html = null, $customAttribs = array(),
230 $query = array(), $options = array( 'known', 'noclasses' ) )
232 return self
::link( $target, $html, $customAttribs, $query, $options );
236 * Returns the Url used to link to a Title
238 * @param $target Title
240 private static function linkUrl( $target, $query, $options ) {
241 wfProfileIn( __METHOD__
);
242 # We don't want to include fragments for broken links, because they
243 # generally make no sense.
244 if ( in_array( 'broken', $options ) && $target->mFragment
!== '' ) {
245 $target = clone $target;
246 $target->mFragment
= '';
249 # If it's a broken link, add the appropriate query pieces, unless
250 # there's already an action specified, or unless 'edit' makes no sense
251 # (i.e., for a nonexistent special page).
252 if ( in_array( 'broken', $options ) && empty( $query['action'] )
253 && $target->getNamespace() != NS_SPECIAL
) {
254 $query['action'] = 'edit';
255 $query['redlink'] = '1';
257 $ret = $target->getLinkUrl( $query );
258 wfProfileOut( __METHOD__
);
263 * Returns the array of attributes used when linking to the Title $target
265 * @param $target Title
271 private static function linkAttribs( $target, $attribs, $options ) {
272 wfProfileIn( __METHOD__
);
276 if ( !in_array( 'noclasses', $options ) ) {
277 wfProfileIn( __METHOD__
. '-getClasses' );
278 # Now build the classes.
281 if ( in_array( 'broken', $options ) ) {
285 if ( $target->isExternal() ) {
286 $classes[] = 'extiw';
289 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
290 $colour = self
::getLinkColour( $target, $wgUser->getStubThreshold() );
291 if ( $colour !== '' ) {
292 $classes[] = $colour; # mw-redirect or stub
295 if ( $classes != array() ) {
296 $defaults['class'] = implode( ' ', $classes );
298 wfProfileOut( __METHOD__
. '-getClasses' );
301 # Get a default title attribute.
302 if ( $target->getPrefixedText() == '' ) {
303 # A link like [[#Foo]]. This used to mean an empty title
304 # attribute, but that's silly. Just don't output a title.
305 } elseif ( in_array( 'known', $options ) ) {
306 $defaults['title'] = $target->getPrefixedText();
308 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
311 # Finally, merge the custom attribs with the default ones, and iterate
312 # over that, deleting all "false" attributes.
314 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
315 foreach ( $merged as $key => $val ) {
316 # A false value suppresses the attribute, and we don't want the
317 # href attribute to be overridden.
318 if ( $key != 'href' and $val !== false ) {
322 wfProfileOut( __METHOD__
);
327 * Default text of the links to the Title $target
329 * @param $target Title
333 private static function linkText( $target ) {
334 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
335 if ( !$target instanceof Title
) {
339 # If the target is just a fragment, with no title, we return the frag-
340 # ment text. Otherwise, we return the title text itself.
341 if ( $target->getPrefixedText() === '' && $target->getFragment() !== '' ) {
342 return htmlspecialchars( $target->getFragment() );
344 return htmlspecialchars( $target->getPrefixedText() );
348 * Generate either a normal exists-style link or a stub link, depending
349 * on the given page size.
351 * @param $size Integer
352 * @param $nt Title object.
353 * @param $text String
354 * @param $query String
355 * @param $trail String
356 * @param $prefix String
357 * @return string HTML of link
358 * @deprecated since 1.17
360 static function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
362 wfDeprecated( __METHOD__
);
364 $threshold = $wgUser->getStubThreshold();
365 $colour = ( $size < $threshold ) ?
'stub' : '';
366 // @todo FIXME: Replace deprecated makeColouredLinkObj by link()
367 return self
::makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
371 * Make appropriate markup for a link to the current article. This is currently rendered
372 * as the bold link text. The calling sequence is the same as the other make*LinkObj static functions,
373 * despite $query not being used.
379 static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
381 $html = htmlspecialchars( $nt->getPrefixedText() );
383 list( $inside, $trail ) = self
::splitTrail( $trail );
384 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
388 * @param $title Title
391 static function normaliseSpecialPage( Title
$title ) {
392 if ( $title->getNamespace() == NS_SPECIAL
) {
393 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
397 $ret = SpecialPage
::getTitleFor( $name, $subpage );
398 $ret->mFragment
= $title->getFragment();
406 * Returns the filename part of an url.
407 * Used as alternative text for external images.
413 static function fnamePart( $url ) {
414 $basename = strrchr( $url, '/' );
415 if ( false === $basename ) {
418 $basename = substr( $basename, 1 );
424 * Return the code for images which were added via external links,
425 * via Parser::maybeMakeExternalImage().
432 static function makeExternalImage( $url, $alt = '' ) {
434 $alt = self
::fnamePart( $url );
437 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
439 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
442 return Html
::element( 'img',
449 * Given parameters derived from [[Image:Foo|options...]], generate the
450 * HTML that that syntax inserts in the page.
452 * @param $title Title object
453 * @param $file File object, or false if it doesn't exist
454 * @param $frameParams Array: associative array of parameters external to the media handler.
455 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
456 * will often be false.
457 * thumbnail If present, downscale and frame
458 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
459 * framed Shows image in original size in a frame
460 * frameless Downscale but don't frame
461 * upright If present, tweak default sizes for portrait orientation
462 * upright_factor Fudge factor for "upright" tweak (default 0.75)
463 * border If present, show a border around the image
464 * align Horizontal alignment (left, right, center, none)
465 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
466 * bottom, text-bottom)
467 * alt Alternate text for image (i.e. alt attribute). Plain text.
468 * caption HTML for image caption.
469 * link-url URL to link to
470 * link-title Title object to link to
471 * link-target Value for the target attribue, only with link-url
472 * no-link Boolean, suppress description link
474 * @param $handlerParams Array: associative array of media handler parameters, to be passed
475 * to transform(). Typical keys are "width" and "page".
476 * @param $time String: timestamp of the file, set as false for current
477 * @param $query String: query params for desc url
478 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
479 * @return String: HTML for an image, with links, wrappers, etc.
481 static function makeImageLink2( Title
$title, $file, $frameParams = array(),
482 $handlerParams = array(), $time = false, $query = "", $widthOption = null )
485 $dummy = new DummyLinker
;
486 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
487 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
491 if ( $file && !$file->allowInlineDisplay() ) {
492 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
493 return self
::link( $title );
498 $hp =& $handlerParams;
500 // Clean up parameters
501 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
502 if ( !isset( $fp['align'] ) ) {
505 if ( !isset( $fp['alt'] ) ) {
508 if ( !isset( $fp['title'] ) ) {
512 $prefix = $postfix = '';
514 if ( 'center' == $fp['align'] ) {
515 $prefix = '<div class="center">';
517 $fp['align'] = 'none';
519 if ( $file && !isset( $hp['width'] ) ) {
520 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
521 // If its a vector image, and user only specifies height
522 // we don't want it to be limited by its "normal" width.
523 global $wgSVGMaxSize;
524 $hp['width'] = $wgSVGMaxSize;
526 $hp['width'] = $file->getWidth( $page );
529 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
530 global $wgThumbLimits, $wgThumbUpright;
531 if ( !isset( $widthOption ) ||
!isset( $wgThumbLimits[$widthOption] ) ) {
532 $widthOption = User
::getDefaultOption( 'thumbsize' );
535 // Reduce width for upright images when parameter 'upright' is used
536 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
537 $fp['upright'] = $wgThumbUpright;
539 // 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
540 $prefWidth = isset( $fp['upright'] ) ?
541 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
542 $wgThumbLimits[$widthOption];
544 // Use width which is smaller: real image width or user preference width
545 // Unless image is scalable vector.
546 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
547 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
548 $hp['width'] = $prefWidth;
553 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
555 # Create a thumbnail. Alignment depends on language
556 # writing direction, # right aligned for left-to-right-
557 # languages ("Western languages"), left-aligned
558 # for right-to-left-languages ("Semitic languages")
560 # If thumbnail width has not been provided, it is set
561 # to the default user option as specified in Language*.php
562 if ( $fp['align'] == '' ) {
563 $fp['align'] = $wgContLang->alignEnd();
565 return $prefix . self
::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
568 if ( $file && isset( $fp['frameless'] ) ) {
569 $srcWidth = $file->getWidth( $page );
570 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
571 # This is the same behaviour as the "thumb" option does it already.
572 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
573 $hp['width'] = $srcWidth;
577 if ( $file && isset( $hp['width'] ) ) {
578 # Create a resized image, without the additional thumbnail features
579 $thumb = $file->transform( $hp );
585 $s = self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
589 'title' => $fp['title'],
590 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
591 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
592 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
594 $s = $thumb->toHtml( $params );
596 if ( $fp['align'] != '' ) {
597 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
599 return str_replace( "\n", ' ', $prefix . $s . $postfix );
603 * Get the link parameters for MediaTransformOutput::toHtml() from given
604 * frame parameters supplied by the Parser.
605 * @param $frameParams The frame parameters
606 * @param $query An optional query string to add to description page links
608 static function getImageLinkMTOParams( $frameParams, $query = '' ) {
609 $mtoParams = array();
610 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
611 $mtoParams['custom-url-link'] = $frameParams['link-url'];
612 if ( isset( $frameParams['link-target'] ) ) {
613 $mtoParams['custom-target-link'] = $frameParams['link-target'];
615 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
616 $mtoParams['custom-title-link'] = self
::normaliseSpecialPage( $frameParams['link-title'] );
617 } elseif ( !empty( $frameParams['no-link'] ) ) {
620 $mtoParams['desc-link'] = true;
621 $mtoParams['desc-query'] = $query;
627 * Make HTML for a thumbnail including image, border and caption
628 * @param $title Title object
629 * @param $file File object or false if it doesn't exist
630 * @param $label String
632 * @param $align String
633 * @param $params Array
634 * @param $framed Boolean
635 * @param $manualthumb String
637 static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt,
638 $align = 'right', $params = array(), $framed = false , $manualthumb = "" )
640 $frameParams = array(
646 $frameParams['framed'] = true;
648 if ( $manualthumb ) {
649 $frameParams['manualthumb'] = $manualthumb;
651 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
655 * @param $title Title
657 * @param array $frameParams
658 * @param array $handlerParams
660 * @param string $query
663 static function makeThumbLink2( Title
$title, $file, $frameParams = array(),
664 $handlerParams = array(), $time = false, $query = "" )
666 global $wgStylePath, $wgContLang;
667 $exists = $file && $file->exists();
671 $hp =& $handlerParams;
673 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
674 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
675 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
676 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
677 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
679 if ( empty( $hp['width'] ) ) {
680 // Reduce width for upright images when parameter 'upright' is used
681 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
686 $outerWidth = $hp['width'] +
2;
688 if ( isset( $fp['manualthumb'] ) ) {
689 # Use manually specified thumbnail
690 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
691 if ( $manual_title ) {
692 $manual_img = wfFindFile( $manual_title );
694 $thumb = $manual_img->getUnscaledThumb( $hp );
699 } elseif ( isset( $fp['framed'] ) ) {
700 // Use image dimensions, don't scale
701 $thumb = $file->getUnscaledThumb( $hp );
703 # Do not present an image bigger than the source, for bitmap-style images
704 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
705 $srcWidth = $file->getWidth( $page );
706 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
707 $hp['width'] = $srcWidth;
709 $thumb = $file->transform( $hp );
713 $outerWidth = $thumb->getWidth() +
2;
715 $outerWidth = $hp['width'] +
2;
719 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
720 # So we don't need to pass it here in $query. However, the URL for the
721 # zoom icon still needs it, so we make a unique query for it. See bug 14771
722 $url = $title->getLocalURL( $query );
724 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
727 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
729 $s .= self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
731 } elseif ( !$thumb ) {
732 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
737 'title' => $fp['title'],
738 'img-class' => 'thumbimage' );
739 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
740 $s .= $thumb->toHtml( $params );
741 if ( isset( $fp['framed'] ) ) {
744 $zoomIcon = Html
::rawElement( 'div', array( 'class' => 'magnify' ),
745 Html
::rawElement( 'a', array(
747 'class' => 'internal',
748 'title' => wfMsg( 'thumbnail-more' ) ),
749 Html
::element( 'img', array(
750 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ?
'-rtl' : '' ) . '.png',
756 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
757 return str_replace( "\n", ' ', $s );
761 * Make a "broken" link to an image
763 * @param $title Title object
764 * @param $html String: link label in htmlescaped text form
765 * @param $query String: query string
766 * @param $trail String: link trail (HTML fragment)
767 * @param $prefix String: link prefix (HTML fragment)
768 * @param $time Boolean: a file of a certain timestamp was requested
771 public static function makeBrokenImageLinkObj( $title, $html = '', $query = '', $trail = '', $prefix = '', $time = false ) {
772 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
773 if ( ! $title instanceof Title
) {
774 return "<!-- ERROR -->{$prefix}{$html}{$trail}";
776 wfProfileIn( __METHOD__
);
777 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
779 list( $inside, $trail ) = self
::splitTrail( $trail );
781 $html = htmlspecialchars( $title->getPrefixedText() );
783 if ( ( $wgUploadMissingFileUrl ||
$wgUploadNavigationUrl ||
$wgEnableUploads ) && !$currentExists ) {
784 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
787 wfProfileOut( __METHOD__
);
788 return self
::linkKnown( $title, "$prefix$html$inside", array(), $query ) . $trail;
791 $href = self
::getUploadUrl( $title, $query );
793 wfProfileOut( __METHOD__
);
794 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
795 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
796 "$prefix$html$inside</a>$trail";
798 wfProfileOut( __METHOD__
);
799 return self
::linkKnown( $title, "$prefix$html$inside", array(), $query ) . $trail;
804 * Get the URL to upload a certain file
806 * @param $destFile Title object of the file to upload
807 * @param $query String: urlencoded query string to prepend
808 * @return String: urlencoded URL
810 protected static function getUploadUrl( $destFile, $query = '' ) {
811 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
812 $q = 'wpDestFile=' . $destFile->getPartialUrl();
816 if ( $wgUploadMissingFileUrl ) {
817 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
818 } elseif( $wgUploadNavigationUrl ) {
819 return wfAppendQuery( $wgUploadNavigationUrl, $q );
821 $upload = SpecialPage
::getTitleFor( 'Upload' );
822 return $upload->getLocalUrl( $q );
827 * Create a direct link to a given uploaded file.
829 * @param $title Title object.
830 * @param $html String: pre-sanitized HTML
831 * @param $time string: MW timestamp of file creation time
832 * @return String: HTML
834 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
835 $img = wfFindFile( $title, array( 'time' => $time ) );
836 return self
::makeMediaLinkFile( $title, $img, $html );
840 * Create a direct link to a given uploaded file.
841 * This will make a broken link if $file is false.
843 * @param $title Title object.
844 * @param $file File|false mixed File object or false
845 * @param $html String: pre-sanitized HTML
846 * @return String: HTML
848 * @todo Handle invalid or missing images better.
850 public static function makeMediaLinkFile( Title
$title, $file, $html = '' ) {
851 if ( $file && $file->exists() ) {
852 $url = $file->getURL();
855 $url = self
::getUploadUrl( $title );
858 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES
);
862 $u = htmlspecialchars( $url );
863 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$html}</a>";
867 * Make a link to a special page given its name and, optionally,
868 * a message key from the link text.
869 * Usage example: $skin->specialLink( 'recentchanges' )
873 static function specialLink( $name, $key = '' ) {
875 $key = strtolower( $name );
878 return self
::linkKnown( SpecialPage
::getTitleFor( $name ) , wfMsg( $key ) );
882 * Make an external link
883 * @param $url String: URL to link to
884 * @param $text String: text of link
885 * @param $escape Boolean: do we escape the link text?
886 * @param $linktype String: type of external link. Gets added to the classes
887 * @param $attribs Array of extra attributes to <a>
889 static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
891 if ( isset($linktype) && $linktype ) {
892 $class .= " $linktype";
894 if ( isset($attribs['class']) && $attribs['class'] ) {
895 $class .= " {$attribs['class']}";
897 $attribs['class'] = $class;
900 $text = htmlspecialchars( $text );
903 $success = wfRunHooks( 'LinkerMakeExternalLink',
904 array( &$url, &$text, &$link, &$attribs, $linktype ) );
906 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
909 $attribs['href'] = $url;
910 return Html
::rawElement( 'a', $attribs, $text );
914 * Make user link (or user contributions for unregistered users)
915 * @param $userId Integer: user id in database.
916 * @param $userText String: user name in database
917 * @return String: HTML fragment
920 static function userLink( $userId, $userText ) {
921 if ( $userId == 0 ) {
922 $page = SpecialPage
::getTitleFor( 'Contributions', $userText );
924 $page = Title
::makeTitle( NS_USER
, $userText );
926 return self
::link( $page, htmlspecialchars( $userText ), array( 'class' => 'mw-userlink' ) );
930 * Generate standard user tool links (talk, contributions, block link, etc.)
932 * @param $userId Integer: user identifier
933 * @param $userText String: user name or IP address
934 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
935 * red if the user has no edits?
936 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK and Linker::TOOL_LINKS_EMAIL)
937 * @param $edits Integer: user edit count (optional, for performance)
938 * @return String: HTML fragment
940 public static function userToolLinks(
941 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
943 global $wgUser, $wgDisableAnonTalk, $wgLang;
944 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
945 $blockable = !$flags & self
::TOOL_LINKS_NOBLOCK
;
946 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
;
950 $items[] = self
::userTalkLink( $userId, $userText );
953 // check if the user has an edit
955 if ( $redContribsWhenNoEdits ) {
956 $count = !is_null( $edits ) ?
$edits : User
::edits( $userId );
958 $attribs['class'] = 'new';
961 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
963 $items[] = self
::link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
965 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
966 $items[] = self
::blockLink( $userId, $userText );
969 if ( $addEmailLink && $wgUser->canSendEmail() ) {
970 $items[] = self
::emailLink( $userId, $userText );
974 return ' <span class="mw-usertoollinks">(' . $wgLang->pipeList( $items ) . ')</span>';
981 * Alias for userToolLinks( $userId, $userText, true );
982 * @param $userId Integer: user identifier
983 * @param $userText String: user name or IP address
984 * @param $edits Integer: user edit count (optional, for performance)
986 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
987 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
992 * @param $userId Integer: user id in database.
993 * @param $userText String: user name in database.
994 * @return String: HTML fragment with user talk link
997 static function userTalkLink( $userId, $userText ) {
998 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
999 $userTalkLink = self
::link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
1000 return $userTalkLink;
1004 * @param $userId Integer: userid
1005 * @param $userText String: user name in database.
1006 * @return String: HTML fragment with block link
1009 static function blockLink( $userId, $userText ) {
1010 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1011 $blockLink = self
::link( $blockPage, wfMsgHtml( 'blocklink' ) );
1016 * @param $userId Integer: userid
1017 * @param $userText String: user name in database.
1018 * @return String: HTML fragment with e-mail user link
1021 static function emailLink( $userId, $userText ) {
1022 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1023 $emailLink = self
::link( $emailPage, wfMsgHtml( 'emaillink' ) );
1028 * Generate a user link if the current user is allowed to view it
1029 * @param $rev Revision object.
1030 * @param $isPublic Boolean: show only if all users can see it
1031 * @return String: HTML fragment
1033 static function revUserLink( $rev, $isPublic = false ) {
1034 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1035 $link = wfMsgHtml( 'rev-deleted-user' );
1036 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1037 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1038 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1040 $link = wfMsgHtml( 'rev-deleted-user' );
1042 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1043 return '<span class="history-deleted">' . $link . '</span>';
1049 * Generate a user tool link cluster if the current user is allowed to view it
1050 * @param $rev Revision object.
1051 * @param $isPublic Boolean: show only if all users can see it
1052 * @return string HTML
1054 static function revUserTools( $rev, $isPublic = false ) {
1055 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1056 $link = wfMsgHtml( 'rev-deleted-user' );
1057 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1058 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1059 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1060 $link = self
::userLink( $userId, $userText ) .
1061 ' ' . self
::userToolLinks( $userId, $userText );
1063 $link = wfMsgHtml( 'rev-deleted-user' );
1065 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1066 return ' <span class="history-deleted">' . $link . '</span>';
1072 * This function is called by all recent changes variants, by the page history,
1073 * and by the user contributions list. It is responsible for formatting edit
1074 * comments. It escapes any HTML in the comment, but adds some CSS to format
1075 * auto-generated comments (from section editing) and formats [[wikilinks]].
1077 * @author Erik Moeller <moeller@scireview.de>
1079 * Note: there's not always a title to pass to this function.
1080 * Since you can't set a default parameter for a reference, I've turned it
1081 * temporarily to a value pass. Should be adjusted further. --brion
1083 * @param $comment String
1084 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1085 * @param $local Boolean: whether section links should refer to local page
1087 static function formatComment( $comment, $title = null, $local = false ) {
1088 wfProfileIn( __METHOD__
);
1090 # Sanitize text a bit:
1091 $comment = str_replace( "\n", " ", $comment );
1092 # Allow HTML entities (for bug 13815)
1093 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1095 # Render autocomments and make links:
1096 $comment = self
::formatAutocomments( $comment, $title, $local );
1097 $comment = self
::formatLinksInComment( $comment, $title, $local );
1099 wfProfileOut( __METHOD__
);
1106 static $autocommentTitle;
1107 static $autocommentLocal;
1110 * The pattern for autogen comments is / * foo * /, which makes for
1112 * We look for all comments, match any text before and after the comment,
1113 * add a separator where needed and format the comment itself with CSS
1114 * Called by Linker::formatComment.
1116 * @param $comment String: comment text
1117 * @param $title An optional title object used to links to sections
1118 * @param $local Boolean: whether section links should refer to local page
1119 * @return String: formatted comment
1121 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1123 self
::$autocommentTitle = $title;
1124 self
::$autocommentLocal = $local;
1125 $comment = preg_replace_callback(
1126 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1127 array( 'Linker', 'formatAutocommentsCallback' ),
1129 self
::$autocommentTitle = null;
1130 self
::$autocommentLocal = null;
1138 private static function formatAutocommentsCallback( $match ) {
1139 $title = self
::$autocommentTitle;
1140 $local = self
::$autocommentLocal;
1149 # Remove links that a user may have manually put in the autosummary
1150 # This could be improved by copying as much of Parser::stripSectionName as desired.
1151 $section = str_replace( '[[:', '', $section );
1152 $section = str_replace( '[[', '', $section );
1153 $section = str_replace( ']]', '', $section );
1155 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1157 $sectionTitle = Title
::newFromText( '#' . $section );
1159 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1160 $title->getDBkey(), $section );
1162 if ( $sectionTitle ) {
1163 $link = self
::link( $sectionTitle,
1164 htmlspecialchars( wfMsgForContent( 'sectionlink' ) ), array(), array(),
1170 $auto = "$link$auto";
1172 # written summary $presep autocomment (summary /* section */)
1173 $auto = wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) ) . $auto;
1176 # autocomment $postsep written summary (/* section */ summary)
1177 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1179 $auto = '<span class="autocomment">' . $auto . '</span>';
1180 $comment = $pre . $auto . $post;
1187 static $commentContextTitle;
1188 static $commentLocal;
1191 * Formats wiki links and media links in text; all other wiki formatting
1194 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1195 * @param $comment String: text to format links in
1196 * @param $title An optional title object used to links to sections
1197 * @param $local Boolean: whether section links should refer to local page
1200 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1201 self
::$commentContextTitle = $title;
1202 self
::$commentLocal = $local;
1203 $html = preg_replace_callback(
1204 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1205 array( 'Linker', 'formatLinksInCommentCallback' ),
1207 self
::$commentContextTitle = null;
1208 self
::$commentLocal = null;
1216 protected static function formatLinksInCommentCallback( $match ) {
1219 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1220 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1222 $comment = $match[0];
1224 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1225 if ( strpos( $match[1], '%' ) !== false ) {
1226 $match[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $match[1] ) );
1229 # Handle link renaming [[foo|text]] will show link as "text"
1230 if ( $match[3] != "" ) {
1235 $submatch = array();
1237 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1238 # Media link; trail not supported.
1239 $linkRegexp = '/\[\[(.*?)\]\]/';
1240 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1241 $thelink = self
::makeMediaLinkObj( $title, $text );
1243 # Other kind of link
1244 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1245 $trail = $submatch[1];
1249 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1250 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1251 $match[1] = substr( $match[1], 1 );
1252 list( $inside, $trail ) = self
::splitTrail( $trail );
1255 $linkTarget = self
::normalizeSubpageLink( self
::$commentContextTitle,
1256 $match[1], $linkText );
1258 $target = Title
::newFromText( $linkTarget );
1260 if ( $target->getText() == '' && $target->getInterwiki() === ''
1261 && !self
::$commentLocal && self
::$commentContextTitle )
1263 $newTarget = clone ( self
::$commentContextTitle );
1264 $newTarget->setFragment( '#' . $target->getFragment() );
1265 $target = $newTarget;
1267 $thelink = self
::link(
1274 // If the link is still valid, go ahead and replace it in!
1275 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1282 * @param $contextTitle Title
1287 static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1290 # :Foobar -- override special treatment of prefix (images, language links)
1291 # /Foobar -- convert to CurrentPage/Foobar
1292 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1293 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1294 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1296 wfProfileIn( __METHOD__
);
1297 $ret = $target; # default return value is no change
1299 # Some namespaces don't allow subpages,
1300 # so only perform processing if subpages are allowed
1301 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1302 $hash = strpos( $target, '#' );
1303 if ( $hash !== false ) {
1304 $suffix = substr( $target, $hash );
1305 $target = substr( $target, 0, $hash );
1310 $target = trim( $target );
1311 # Look at the first character
1312 if ( $target != '' && $target { 0 } === '/' ) {
1313 # / at end means we don't want the slash to be shown
1315 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1316 if ( $trailingSlashes ) {
1317 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1319 $noslash = substr( $target, 1 );
1322 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1323 if ( $text === '' ) {
1324 $text = $target . $suffix;
1325 } # this might be changed for ugliness reasons
1327 # check for .. subpage backlinks
1329 $nodotdot = $target;
1330 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1332 $nodotdot = substr( $nodotdot, 3 );
1334 if ( $dotdotcount > 0 ) {
1335 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1336 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1337 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1338 # / at the end means don't show full path
1339 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1340 $nodotdot = substr( $nodotdot, 0, -1 );
1341 if ( $text === '' ) {
1342 $text = $nodotdot . $suffix;
1345 $nodotdot = trim( $nodotdot );
1346 if ( $nodotdot != '' ) {
1347 $ret .= '/' . $nodotdot;
1355 wfProfileOut( __METHOD__
);
1360 * Wrap a comment in standard punctuation and formatting if
1361 * it's non-empty, otherwise return empty string.
1363 * @param $comment String
1364 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1365 * @param $local Boolean: whether section links should refer to local page
1369 static function commentBlock( $comment, $title = null, $local = false ) {
1370 // '*' used to be the comment inserted by the software way back
1371 // in antiquity in case none was provided, here for backwards
1372 // compatability, acc. to brion -ævar
1373 if ( $comment == '' ||
$comment == '*' ) {
1376 $formatted = self
::formatComment( $comment, $title, $local );
1377 return " <span class=\"comment\">($formatted)</span>";
1382 * Wrap and format the given revision's comment block, if the current
1383 * user is allowed to view it.
1385 * @param $rev Revision object
1386 * @param $local Boolean: whether section links should refer to local page
1387 * @param $isPublic Boolean: show only if all users can see it
1388 * @return String: HTML fragment
1390 static function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1391 if ( $rev->getRawComment() == "" ) {
1394 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1395 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1396 } elseif ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1397 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1398 $rev->getTitle(), $local );
1400 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1402 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1403 return " <span class=\"history-deleted\">$block</span>";
1412 public static function formatRevisionSize( $size ) {
1414 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1417 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1420 $stxt = htmlspecialchars( $stxt );
1421 return "<span class=\"history-size\">$stxt</span>";
1425 * Add another level to the Table of Contents
1429 static function tocIndent() {
1434 * Finish one or more sublevels on the Table of Contents
1438 static function tocUnindent( $level ) {
1439 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1443 * parameter level defines if we are on an indentation level
1447 static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1448 $classes = "toclevel-$level";
1449 if ( $sectionIndex !== false ) {
1450 $classes .= " tocsection-$sectionIndex";
1452 return "\n<li class=\"$classes\"><a href=\"#" .
1453 $anchor . '"><span class="tocnumber">' .
1454 $tocnumber . '</span> <span class="toctext">' .
1455 $tocline . '</span></a>';
1459 * End a Table Of Contents line.
1460 * tocUnindent() will be used instead if we're ending a line below
1463 static function tocLineEnd() {
1468 * Wraps the TOC in a table and provides the hide/collapse javascript.
1470 * @param $toc String: html of the Table Of Contents
1471 * @param $lang mixed: Language code for the toc title
1472 * @return String: full html of the TOC
1474 static function tocList( $toc, $lang = false ) {
1475 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1477 '<table id="toc" class="toc"><tr><td>'
1478 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1480 . "</ul>\n</td></tr></table>\n";
1484 * Generate a table of contents from a section tree
1487 * @param $tree Return value of ParserOutput::getSections()
1488 * @return String: HTML fragment
1490 public static function generateTOC( $tree ) {
1493 foreach ( $tree as $section ) {
1494 if ( $section['toclevel'] > $lastLevel )
1495 $toc .= self
::tocIndent();
1496 elseif ( $section['toclevel'] < $lastLevel )
1497 $toc .= self
::tocUnindent(
1498 $lastLevel - $section['toclevel'] );
1500 $toc .= self
::tocLineEnd();
1502 $toc .= self
::tocLine( $section['anchor'],
1503 $section['line'], $section['number'],
1504 $section['toclevel'], $section['index'] );
1505 $lastLevel = $section['toclevel'];
1507 $toc .= self
::tocLineEnd();
1508 return self
::tocList( $toc );
1512 * Create a headline for content
1514 * @param $level Integer: the level of the headline (1-6)
1515 * @param $attribs String: any attributes for the headline, starting with
1516 * a space and ending with '>'
1517 * This *must* be at least '>' for no attribs
1518 * @param $anchor String: the anchor to give the headline (the bit after the #)
1519 * @param $html String: html for the text of the header
1520 * @param $link String: HTML to add for the section edit link
1521 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1522 * backward compatibility (false to omit)
1524 * @return String: HTML headline
1526 public static function makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor = false ) {
1527 $ret = "<h$level$attribs"
1529 . " <span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1531 if ( $legacyAnchor !== false ) {
1532 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1538 * Split a link trail, return the "inside" portion and the remainder of the trail
1539 * as a two-element array
1541 static function splitTrail( $trail ) {
1543 $regex = $wgContLang->linkTrail();
1545 if ( $trail !== '' ) {
1547 if ( preg_match( $regex, $trail, $m ) ) {
1552 return array( $inside, $trail );
1556 * Generate a rollback link for a given revision. Currently it's the
1557 * caller's responsibility to ensure that the revision is the top one. If
1558 * it's not, of course, the user will get an error message.
1560 * If the calling page is called with the parameter &bot=1, all rollback
1561 * links also get that parameter. It causes the edit itself and the rollback
1562 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1563 * changes, so this allows sysops to combat a busy vandal without bothering
1566 * @param $rev Revision object
1568 static function generateRollback( $rev ) {
1569 return '<span class="mw-rollback-link">['
1570 . self
::buildRollbackLink( $rev )
1575 * Build a raw rollback link, useful for collections of "tool" links
1577 * @param $rev Revision object
1578 * @return String: HTML fragment
1580 public static function buildRollbackLink( $rev ) {
1581 global $wgRequest, $wgUser;
1582 $title = $rev->getTitle();
1584 'action' => 'rollback',
1585 'from' => $rev->getUserText(),
1586 'token' => $wgUser->editToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1588 if ( $wgRequest->getBool( 'bot' ) ) {
1589 $query['bot'] = '1';
1590 $query['hidediff'] = '1'; // bug 15999
1594 wfMsgHtml( 'rollbacklink' ),
1595 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1597 array( 'known', 'noclasses' )
1602 * Returns HTML for the "templates used on this page" list.
1604 * @param $templates Array of templates from Article::getUsedTemplate
1606 * @param $preview Boolean: whether this is for a preview
1607 * @param $section Boolean: whether this is for a section edit
1608 * @return String: HTML output
1610 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1611 wfProfileIn( __METHOD__
);
1614 if ( count( $templates ) > 0 ) {
1615 # Do a batch existence check
1616 $batch = new LinkBatch
;
1617 foreach ( $templates as $title ) {
1618 $batch->addObj( $title );
1622 # Construct the HTML
1623 $outText = '<div class="mw-templatesUsedExplanation">';
1625 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1626 } elseif ( $section ) {
1627 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1629 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1631 $outText .= "</div><ul>\n";
1633 usort( $templates, array( 'Title', 'compare' ) );
1634 foreach ( $templates as $titleObj ) {
1635 $r = $titleObj->getRestrictions( 'edit' );
1636 if ( in_array( 'sysop', $r ) ) {
1637 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1638 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1639 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1643 if ( $titleObj->quickUserCan( 'edit' ) ) {
1644 $editLink = self
::link(
1646 wfMsg( 'editlink' ),
1648 array( 'action' => 'edit' )
1651 $editLink = self
::link(
1653 wfMsg( 'viewsourcelink' ),
1655 array( 'action' => 'edit' )
1658 $outText .= '<li>' . self
::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1660 $outText .= '</ul>';
1662 wfProfileOut( __METHOD__
);
1667 * Returns HTML for the "templates used on this page" list.
1669 * @param $templates Array of templates from Article::getUsedTemplate
1671 * @param $preview Boolean: whether this is for a preview
1672 * @param $section Boolean: whether this is for a section edit
1673 * @return String: HTML output
1675 public static function formatDistantTemplates( $templates, $preview = false, $section = false ) {
1676 wfProfileIn( __METHOD__
);
1679 if ( count( $templates ) > 0 ) {
1681 # Construct the HTML
1682 $outText = '<div class="mw-templatesUsedExplanation">';
1684 $outText .= wfMsgExt( 'distanttemplatesusedpreview', array( 'parse' ), count( $templates ) );
1685 } elseif ( $section ) {
1686 $outText .= wfMsgExt( 'distanttemplatesusedsection', array( 'parse' ), count( $templates ) );
1688 $outText .= wfMsgExt( 'distanttemplatesused', array( 'parse' ), count( $templates ) );
1690 $outText .= "</div><ul>\n";
1692 usort( $templates, array( 'Title', 'compare' ) );
1693 foreach ( $templates as $titleObj ) {
1694 $outText .= '<li>' . self
::link( $titleObj ) . '</li>';
1696 $outText .= '</ul>';
1698 wfProfileOut( __METHOD__
);
1703 * Returns HTML for the "hidden categories on this page" list.
1705 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1707 * @return String: HTML output
1709 public static function formatHiddenCategories( $hiddencats ) {
1711 wfProfileIn( __METHOD__
);
1714 if ( count( $hiddencats ) > 0 ) {
1715 # Construct the HTML
1716 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1717 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1718 $outText .= "</div><ul>\n";
1720 foreach ( $hiddencats as $titleObj ) {
1721 $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
1723 $outText .= '</ul>';
1725 wfProfileOut( __METHOD__
);
1730 * Format a size in bytes for output, using an appropriate
1731 * unit (B, KB, MB or GB) according to the magnitude in question
1733 * @param $size Size to format
1736 public static function formatSize( $size ) {
1738 return htmlspecialchars( $wgLang->formatSize( $size ) );
1742 * Given the id of an interface element, constructs the appropriate title
1743 * attribute from the system messages. (Note, this is usually the id but
1744 * isn't always, because sometimes the accesskey needs to go on a different
1745 * element than the id, for reverse-compatibility, etc.)
1747 * @param $name String: id of the element, minus prefixes.
1748 * @param $options Mixed: null or the string 'withaccess' to add an access-
1750 * @return String: contents of the title attribute (which you must HTML-
1751 * escape), or false for no title attribute
1753 public static function titleAttrib( $name, $options = null ) {
1754 global $wgEnableTooltipsAndAccesskeys;
1755 if ( !$wgEnableTooltipsAndAccesskeys )
1758 wfProfileIn( __METHOD__
);
1760 $message = wfMessage( "tooltip-$name" );
1762 if ( !$message->exists() ) {
1765 $tooltip = $message->text();
1766 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1767 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1768 # Message equal to '-' means suppress it.
1769 if ( $tooltip == '-' ) {
1774 if ( $options == 'withaccess' ) {
1775 $accesskey = self
::accesskey( $name );
1776 if ( $accesskey !== false ) {
1777 if ( $tooltip === false ||
$tooltip === '' ) {
1778 $tooltip = "[$accesskey]";
1780 $tooltip .= " [$accesskey]";
1785 wfProfileOut( __METHOD__
);
1789 static $accesskeycache;
1792 * Given the id of an interface element, constructs the appropriate
1793 * accesskey attribute from the system messages. (Note, this is usually
1794 * the id but isn't always, because sometimes the accesskey needs to go on
1795 * a different element than the id, for reverse-compatibility, etc.)
1797 * @param $name String: id of the element, minus prefixes.
1798 * @return String: contents of the accesskey attribute (which you must HTML-
1799 * escape), or false for no accesskey attribute
1801 public static function accesskey( $name ) {
1802 if ( isset( self
::$accesskeycache[$name] ) ) {
1803 return self
::$accesskeycache[$name];
1805 wfProfileIn( __METHOD__
);
1807 $message = wfMessage( "accesskey-$name" );
1809 if ( !$message->exists() ) {
1812 $accesskey = $message->plain();
1813 if ( $accesskey === '' ||
$accesskey === '-' ) {
1814 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
1815 # attribute, but this is broken for accesskey: that might be a useful
1821 wfProfileOut( __METHOD__
);
1822 return self
::$accesskeycache[$name] = $accesskey;
1826 * Get a revision-deletion link, or disabled link, or nothing, depending
1827 * on user permissions & the settings on the revision.
1829 * Will use forward-compatible revision ID in the Special:RevDelete link
1830 * if possible, otherwise the timestamp-based ID which may break after
1834 * @param Revision $rev
1835 * @param Revision $title
1836 * @return string HTML fragment
1838 public static function getRevDeleteLink( User
$user, Revision
$rev, Title
$title ) {
1839 $canHide = $user->isAllowed( 'deleterevision' );
1840 if ( $canHide ||
( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
1841 if( !$rev->userCan( Revision
::DELETED_RESTRICTED
) ) {
1842 $revdlink = Linker
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
1844 if ( $rev->getId() ) {
1845 // RevDelete links using revision ID are stable across
1846 // page deletion and undeletion; use when possible.
1848 'type' => 'revision',
1849 'target' => $title->getPrefixedDBkey(),
1850 'ids' => $rev->getId()
1853 // Older deleted entries didn't save a revision ID.
1854 // We have to refer to these by timestamp, ick!
1856 'type' => 'archive',
1857 'target' => $title->getPrefixedDBkey(),
1858 'ids' => $rev->getTimestamp()
1861 return Linker
::revDeleteLink( $query,
1862 $rev->isDeleted( File
::DELETED_RESTRICTED
), $canHide );
1870 * Creates a (show/hide) link for deleting revisions/log entries
1872 * @param $query Array: query parameters to be passed to link()
1873 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1874 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1876 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1877 * span to allow for customization of appearance with CSS
1879 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1880 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1881 $html = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1882 $tag = $restricted ?
'strong' : 'span';
1883 $link = self
::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
1884 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), "($link)" );
1888 * Creates a dead (show/hide) link for deleting revisions/log entries
1890 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1892 * @return string HTML text wrapped in a span to allow for customization
1893 * of appearance with CSS
1895 public static function revDeleteLinkDisabled( $delete = true ) {
1896 $html = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1897 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), "($html)" );
1900 /* Deprecated methods */
1903 * @deprecated since 1.16 Use link()
1905 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1906 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1908 * @param $title String: The text of the title
1909 * @param $text String: Link text
1910 * @param $query String: Optional query part
1911 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1912 * be included in the link text. Other characters will be appended after
1913 * the end of the link.
1915 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1916 $nt = Title
::newFromText( $title );
1917 if ( $nt instanceof Title
) {
1918 return self
::makeBrokenLinkObj( $nt, $text, $query, $trail );
1920 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
1921 return $text == '' ?
$title : $text;
1926 * @deprecated since 1.16 Use link()
1928 * Make a link for a title which may or may not be in the database. If you need to
1929 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1930 * call to this will result in a DB query.
1932 * @param $nt Title: the title object to make the link from, e.g. from
1933 * Title::newFromText.
1934 * @param $text String: link text
1935 * @param $query String: optional query part
1936 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1937 * be included in the link text. Other characters will be appended after
1938 * the end of the link.
1939 * @param $prefix String: optional prefix. As trail, only before instead of after.
1941 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1942 wfProfileIn( __METHOD__
);
1943 $query = wfCgiToArray( $query );
1944 list( $inside, $trail ) = self
::splitTrail( $trail );
1945 if ( $text === '' ) {
1946 $text = self
::linkText( $nt );
1949 $ret = self
::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1951 wfProfileOut( __METHOD__
);
1956 * @deprecated since 1.16 Use link()
1958 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
1959 * it doesn't have to do a database query. It's also valid for interwiki titles and special
1962 * @param $title Title object of target page
1963 * @param $text String: text to replace the title
1964 * @param $query String: link target
1965 * @param $trail String: text after link
1966 * @param $prefix String: text before link text
1967 * @param $aprops String: extra attributes to the a-element
1968 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
1969 * @return the a-element
1971 static function makeKnownLinkObj(
1972 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
1974 wfProfileIn( __METHOD__
);
1976 if ( $text == '' ) {
1977 $text = self
::linkText( $title );
1979 $attribs = Sanitizer
::mergeAttributes(
1980 Sanitizer
::decodeTagAttributes( $aprops ),
1981 Sanitizer
::decodeTagAttributes( $style )
1983 $query = wfCgiToArray( $query );
1984 list( $inside, $trail ) = self
::splitTrail( $trail );
1986 $ret = self
::link( $title, "$prefix$text$inside", $attribs, $query,
1987 array( 'known', 'noclasses' ) ) . $trail;
1989 wfProfileOut( __METHOD__
);
1994 * @deprecated since 1.16 Use link()
1996 * Make a red link to the edit page of a given title.
1998 * @param $title Title object of the target page
1999 * @param $text String: Link text
2000 * @param $query String: Optional query part
2001 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
2002 * be included in the link text. Other characters will be appended after
2003 * the end of the link.
2004 * @param $prefix String: Optional prefix
2006 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
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
2035 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2036 if ( $colour != '' ) {
2037 $style = self
::getInternalLinkAttributesObj( $nt, $text, $colour );
2041 return self
::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2045 * Returns the attributes for the tooltip and access key.
2047 public static function tooltipAndAccesskeyAttribs( $name ) {
2048 global $wgEnableTooltipsAndAccesskeys;
2049 if ( !$wgEnableTooltipsAndAccesskeys )
2051 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2052 # no attribute" instead of "output '' as value for attribute", this
2053 # would be three lines.
2055 'title' => self
::titleAttrib( $name, 'withaccess' ),
2056 'accesskey' => self
::accesskey( $name )
2058 if ( $attribs['title'] === false ) {
2059 unset( $attribs['title'] );
2061 if ( $attribs['accesskey'] === false ) {
2062 unset( $attribs['accesskey'] );
2068 * @deprecated since 1.14
2069 * Returns raw bits of HTML, use titleAttrib()
2071 public static function tooltip( $name, $options = null ) {
2072 global $wgEnableTooltipsAndAccesskeys;
2073 if ( !$wgEnableTooltipsAndAccesskeys )
2075 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2076 # no attribute" instead of "output '' as value for attribute", this
2077 # would be two lines.
2078 $tooltip = self
::titleAttrib( $name, $options );
2079 if ( $tooltip === false ) {
2082 return Xml
::expandAttributes( array(
2094 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2095 * into static calls to the new Linker for backwards compatibility.
2097 * @param $fname String Name of called method
2098 * @param $args Array Arguments to the method
2100 public function __call( $fname, $args ) {
2101 return call_user_func_array( array( 'Linker', $fname ), $args );