3 * Methods to make links and related items.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Some internal bits split of from Skin.php. These functions are used
25 * for primarily page content: links, embedded images, table of contents. Links
26 * are also used in the skin.
33 * Flags for userToolLinks()
35 const TOOL_LINKS_NOBLOCK
= 1;
36 const TOOL_LINKS_EMAIL
= 2;
39 * Get the appropriate HTML attributes to add to the "a" element of an ex-
40 * ternal link, as created by [wikisyntax].
42 * @param $class String: the contents of the class attribute; if an empty
43 * string is passed, which is the default value, defaults to 'external'.
45 * @deprecated since 1.18 Just pass the external class directly to something using Html::expandAttributes
47 static function getExternalLinkAttributes( $class = 'external' ) {
48 wfDeprecated( __METHOD__
, '1.18' );
49 return self
::getLinkAttributesInternal( '', $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; if an empty
60 * string is passed, which is the default value, defaults to 'external'.
63 static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
66 # @todo FIXME: We have a whole bunch of handling here that doesn't happen in
67 # getExternalLinkAttributes, why?
68 $title = urldecode( $title );
69 $title = $wgContLang->checkTitleEncoding( $title );
70 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
72 return self
::getLinkAttributesInternal( $title, $class );
76 * Get the appropriate HTML attributes to add to the "a" element of an in-
79 * @param $title String: the title text for the link, URL-encoded (???) but
81 * @param $unused String: unused
82 * @param $class String: the contents of the class attribute, default none
85 static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
86 $title = urldecode( $title );
87 $title = str_replace( '_', ' ', $title );
88 return self
::getLinkAttributesInternal( $title, $class );
92 * Get the appropriate HTML attributes to add to the "a" element of an in-
93 * ternal link, given the Title object for the page we want to link to.
96 * @param $unused String: unused
97 * @param $class String: the contents of the class attribute, default none
98 * @param $title Mixed: optional (unescaped) string to use in the title
99 * attribute; if false, default to the name of the page we're linking to
102 static function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
103 if ( $title === false ) {
104 $title = $nt->getPrefixedText();
106 return self
::getLinkAttributesInternal( $title, $class );
110 * Common code for getLinkAttributesX functions
112 * @param $title string
113 * @param $class string
117 private static function getLinkAttributesInternal( $title, $class ) {
118 $title = htmlspecialchars( $title );
119 $class = htmlspecialchars( $class );
121 if ( $class != '' ) {
122 $r .= " class=\"$class\"";
124 if ( $title != '' ) {
125 $r .= " title=\"$title\"";
131 * Return the CSS colour of a known link
133 * @param $t Title object
134 * @param $threshold Integer: user defined threshold
135 * @return String: CSS class
137 public static function getLinkColour( $t, $threshold ) {
139 if ( $t->isRedirect() ) {
141 $colour = 'mw-redirect';
142 } elseif ( $threshold > 0 &&
143 $t->exists() && $t->getLength() < $threshold &&
144 $t->isContentPage() ) {
152 * This function returns an HTML link to the given target. It serves a few
154 * 1) If $target is a Title, the correct URL to link to will be figured
156 * 2) It automatically adds the usual classes for various types of link
157 * targets: "new" for red links, "stub" for short articles, etc.
158 * 3) It escapes all attribute values safely so there's no risk of XSS.
159 * 4) It provides a default tooltip if the target is a Title (the page
160 * name of the target).
161 * link() replaces the old functions in the makeLink() family.
163 * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
164 * You can call it using this if you want to keep compat with these:
165 * $linker = class_exists( 'DummyLinker' ) ? new DummyLinker() : new Linker();
166 * $linker->link( ... );
168 * @param $target Title Can currently only be a Title, but this may
169 * change to support Images, literal URLs, etc.
170 * @param $html string The HTML contents of the <a> element, i.e.,
171 * the link text. This is raw HTML and will not be escaped. If null,
172 * defaults to the prefixed text of the Title; or if the Title is just a
173 * fragment, the contents of the fragment.
174 * @param $customAttribs array A key => value array of extra HTML attri-
175 * butes, such as title and class. (href is ignored.) Classes will be
176 * merged with the default classes, while other attributes will replace
177 * default attributes. All passed attribute values will be HTML-escaped.
178 * A false attribute value means to suppress that attribute.
179 * @param $query array The query string to append to the URL
180 * you're linking to, in key => value array form. Query keys and values
181 * will be URL-encoded.
182 * @param $options string|array String or array of strings:
183 * 'known': Page is known to exist, so don't check if it does.
184 * 'broken': Page is known not to exist, so don't check if it does.
185 * 'noclasses': Don't add any classes automatically (includes "new",
186 * "stub", "mw-redirect", "extiw"). Only use the class attribute
187 * provided, if any, so you get a simple blue link with no funny i-
189 * 'forcearticlepath': Use the article path always, even with a querystring.
190 * Has compatibility issues on some setups, so avoid wherever possible.
191 * @return string HTML <a> attribute
193 public static function link(
194 $target, $html = null, $customAttribs = array(), $query = array(), $options = array()
196 wfProfileIn( __METHOD__
);
197 if ( !$target instanceof Title
) {
198 wfProfileOut( __METHOD__
);
199 return "<!-- ERROR -->$html";
201 $options = (array)$options;
203 $dummy = new DummyLinker
; // dummy linker instance for bc on the hooks
206 if ( !wfRunHooks( 'LinkBegin', array( $dummy, $target, &$html,
207 &$customAttribs, &$query, &$options, &$ret ) ) ) {
208 wfProfileOut( __METHOD__
);
212 # Normalize the Title if it's a special page
213 $target = self
::normaliseSpecialPage( $target );
215 # If we don't know whether the page exists, let's find out.
216 wfProfileIn( __METHOD__
. '-checkPageExistence' );
217 if ( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
218 if ( $target->isKnown() ) {
219 $options[] = 'known';
221 $options[] = 'broken';
224 wfProfileOut( __METHOD__
. '-checkPageExistence' );
227 if ( in_array( "forcearticlepath", $options ) && $query ) {
232 # Note: we want the href attribute first, for prettiness.
233 $attribs = array( 'href' => self
::linkUrl( $target, $query, $options ) );
234 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
235 $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
238 $attribs = array_merge(
240 self
::linkAttribs( $target, $customAttribs, $options )
242 if ( is_null( $html ) ) {
243 $html = self
::linkText( $target );
247 if ( wfRunHooks( 'LinkEnd', array( $dummy, $target, $options, &$html, &$attribs, &$ret ) ) ) {
248 $ret = Html
::rawElement( 'a', $attribs, $html );
251 wfProfileOut( __METHOD__
);
256 * Identical to link(), except $options defaults to 'known'.
259 public static function linkKnown(
260 $target, $html = null, $customAttribs = array(),
261 $query = array(), $options = array( 'known', 'noclasses' ) )
263 return self
::link( $target, $html, $customAttribs, $query, $options );
267 * Returns the Url used to link to a Title
269 * @param $target Title
270 * @param $query Array: query parameters
271 * @param $options Array
274 private static function linkUrl( $target, $query, $options ) {
275 wfProfileIn( __METHOD__
);
276 # We don't want to include fragments for broken links, because they
277 # generally make no sense.
278 if ( in_array( 'broken', $options ) && $target->mFragment
!== '' ) {
279 $target = clone $target;
280 $target->mFragment
= '';
283 # If it's a broken link, add the appropriate query pieces, unless
284 # there's already an action specified, or unless 'edit' makes no sense
285 # (i.e., for a nonexistent special page).
286 if ( in_array( 'broken', $options ) && empty( $query['action'] )
287 && !$target->isSpecialPage() ) {
288 $query['action'] = 'edit';
289 $query['redlink'] = '1';
291 $ret = $target->getLinkURL( $query );
292 wfProfileOut( __METHOD__
);
297 * Returns the array of attributes used when linking to the Title $target
299 * @param $target Title
305 private static function linkAttribs( $target, $attribs, $options ) {
306 wfProfileIn( __METHOD__
);
310 if ( !in_array( 'noclasses', $options ) ) {
311 wfProfileIn( __METHOD__
. '-getClasses' );
312 # Now build the classes.
315 if ( in_array( 'broken', $options ) ) {
319 if ( $target->isExternal() ) {
320 $classes[] = 'extiw';
323 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
324 $colour = self
::getLinkColour( $target, $wgUser->getStubThreshold() );
325 if ( $colour !== '' ) {
326 $classes[] = $colour; # mw-redirect or stub
329 if ( $classes != array() ) {
330 $defaults['class'] = implode( ' ', $classes );
332 wfProfileOut( __METHOD__
. '-getClasses' );
335 # Get a default title attribute.
336 if ( $target->getPrefixedText() == '' ) {
337 # A link like [[#Foo]]. This used to mean an empty title
338 # attribute, but that's silly. Just don't output a title.
339 } elseif ( in_array( 'known', $options ) ) {
340 $defaults['title'] = $target->getPrefixedText();
342 $defaults['title'] = wfMsg( 'red-link-title', $target->getPrefixedText() );
345 # Finally, merge the custom attribs with the default ones, and iterate
346 # over that, deleting all "false" attributes.
348 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
349 foreach ( $merged as $key => $val ) {
350 # A false value suppresses the attribute, and we don't want the
351 # href attribute to be overridden.
352 if ( $key != 'href' and $val !== false ) {
356 wfProfileOut( __METHOD__
);
361 * Default text of the links to the Title $target
363 * @param $target Title
367 private static function linkText( $target ) {
368 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
369 if ( !$target instanceof Title
) {
373 # If the target is just a fragment, with no title, we return the frag-
374 # ment text. Otherwise, we return the title text itself.
375 if ( $target->getPrefixedText() === '' && $target->getFragment() !== '' ) {
376 return htmlspecialchars( $target->getFragment() );
378 return htmlspecialchars( $target->getPrefixedText() );
382 * Generate either a normal exists-style link or a stub link, depending
383 * on the given page size.
385 * @param $size Integer
386 * @param $nt Title object.
387 * @param $text String
388 * @param $query String
389 * @param $trail String
390 * @param $prefix String
391 * @return string HTML of link
392 * @deprecated since 1.17
394 static function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
396 wfDeprecated( __METHOD__
, '1.17' );
398 $threshold = $wgUser->getStubThreshold();
399 $colour = ( $size < $threshold ) ?
'stub' : '';
400 // @todo FIXME: Replace deprecated makeColouredLinkObj by link()
401 return self
::makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
405 * Make appropriate markup for a link to the current article. This is currently rendered
406 * as the bold link text. The calling sequence is the same as the other make*LinkObj static functions,
407 * despite $query not being used.
413 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
415 $html = htmlspecialchars( $nt->getPrefixedText() );
417 list( $inside, $trail ) = self
::splitTrail( $trail );
418 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
422 * Get a message saying that an invalid title was encountered.
423 * This should be called after a method like Title::makeTitleSafe() returned
424 * a value indicating that the title object is invalid.
426 * @param $context IContextSource context to use to get the messages
427 * @param $namespace int Namespace number
428 * @param $title string Text of the title, without the namespace part
430 public static function getInvalidTitleDescription( IContextSource
$context, $namespace, $title ) {
433 // First we check whether the namespace exists or not.
434 if ( MWNamespace
::exists( $namespace ) ) {
435 if ( $namespace == NS_MAIN
) {
436 $name = $context->msg( 'blanknamespace' )->text();
438 $name = $wgContLang->getFormattedNsText( $namespace );
440 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
442 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
447 * @param $title Title
450 static function normaliseSpecialPage( Title
$title ) {
451 if ( $title->isSpecialPage() ) {
452 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
456 $ret = SpecialPage
::getTitleFor( $name, $subpage );
457 $ret->mFragment
= $title->getFragment();
465 * Returns the filename part of an url.
466 * Used as alternative text for external images.
472 private static function fnamePart( $url ) {
473 $basename = strrchr( $url, '/' );
474 if ( false === $basename ) {
477 $basename = substr( $basename, 1 );
483 * Return the code for images which were added via external links,
484 * via Parser::maybeMakeExternalImage().
491 public static function makeExternalImage( $url, $alt = '' ) {
493 $alt = self
::fnamePart( $url );
496 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
498 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
501 return Html
::element( 'img',
508 * Given parameters derived from [[Image:Foo|options...]], generate the
509 * HTML that that syntax inserts in the page.
511 * @param $title Title object
512 * @param $file File object, or false if it doesn't exist
513 * @param $frameParams Array: associative array of parameters external to the media handler.
514 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
515 * will often be false.
516 * thumbnail If present, downscale and frame
517 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
518 * framed Shows image in original size in a frame
519 * frameless Downscale but don't frame
520 * upright If present, tweak default sizes for portrait orientation
521 * upright_factor Fudge factor for "upright" tweak (default 0.75)
522 * border If present, show a border around the image
523 * align Horizontal alignment (left, right, center, none)
524 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
525 * bottom, text-bottom)
526 * alt Alternate text for image (i.e. alt attribute). Plain text.
527 * caption HTML for image caption.
528 * link-url URL to link to
529 * link-title Title object to link to
530 * link-target Value for the target attribue, only with link-url
531 * no-link Boolean, suppress description link
533 * @param $handlerParams Array: associative array of media handler parameters, to be passed
534 * to transform(). Typical keys are "width" and "page".
535 * @param $time String: timestamp of the file, set as false for current
536 * @param $query String: query params for desc url
537 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
538 * @return String: HTML for an image, with links, wrappers, etc.
540 public static function makeImageLink2( Title
$title, $file, $frameParams = array(),
541 $handlerParams = array(), $time = false, $query = "", $widthOption = null )
544 $dummy = new DummyLinker
;
545 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
546 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
550 if ( $file && !$file->allowInlineDisplay() ) {
551 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
552 return self
::link( $title );
557 $hp =& $handlerParams;
559 // Clean up parameters
560 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
561 if ( !isset( $fp['align'] ) ) {
564 if ( !isset( $fp['alt'] ) ) {
567 if ( !isset( $fp['title'] ) ) {
571 $prefix = $postfix = '';
573 if ( 'center' == $fp['align'] ) {
574 $prefix = '<div class="center">';
576 $fp['align'] = 'none';
578 if ( $file && !isset( $hp['width'] ) ) {
579 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
580 // If its a vector image, and user only specifies height
581 // we don't want it to be limited by its "normal" width.
582 global $wgSVGMaxSize;
583 $hp['width'] = $wgSVGMaxSize;
585 $hp['width'] = $file->getWidth( $page );
588 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
589 global $wgThumbLimits, $wgThumbUpright;
590 if ( !isset( $widthOption ) ||
!isset( $wgThumbLimits[$widthOption] ) ) {
591 $widthOption = User
::getDefaultOption( 'thumbsize' );
594 // Reduce width for upright images when parameter 'upright' is used
595 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
596 $fp['upright'] = $wgThumbUpright;
598 // 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
599 $prefWidth = isset( $fp['upright'] ) ?
600 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
601 $wgThumbLimits[$widthOption];
603 // Use width which is smaller: real image width or user preference width
604 // Unless image is scalable vector.
605 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
606 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
607 $hp['width'] = $prefWidth;
612 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
614 # Create a thumbnail. Alignment depends on language
615 # writing direction, # right aligned for left-to-right-
616 # languages ("Western languages"), left-aligned
617 # for right-to-left-languages ("Semitic languages")
619 # If thumbnail width has not been provided, it is set
620 # to the default user option as specified in Language*.php
621 if ( $fp['align'] == '' ) {
622 $fp['align'] = $wgContLang->alignEnd();
624 return $prefix . self
::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
627 if ( $file && isset( $fp['frameless'] ) ) {
628 $srcWidth = $file->getWidth( $page );
629 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
630 # This is the same behaviour as the "thumb" option does it already.
631 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
632 $hp['width'] = $srcWidth;
636 if ( $file && isset( $hp['width'] ) ) {
637 # Create a resized image, without the additional thumbnail features
638 $thumb = $file->transform( $hp );
644 $s = self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
648 'title' => $fp['title'],
649 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
650 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
651 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
653 $s = $thumb->toHtml( $params );
655 if ( $fp['align'] != '' ) {
656 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
658 return str_replace( "\n", ' ', $prefix . $s . $postfix );
662 * Get the link parameters for MediaTransformOutput::toHtml() from given
663 * frame parameters supplied by the Parser.
664 * @param $frameParams array The frame parameters
665 * @param $query string An optional query string to add to description page links
668 private static function getImageLinkMTOParams( $frameParams, $query = '' ) {
669 $mtoParams = array();
670 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
671 $mtoParams['custom-url-link'] = $frameParams['link-url'];
672 if ( isset( $frameParams['link-target'] ) ) {
673 $mtoParams['custom-target-link'] = $frameParams['link-target'];
675 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
676 $mtoParams['custom-title-link'] = self
::normaliseSpecialPage( $frameParams['link-title'] );
677 } elseif ( !empty( $frameParams['no-link'] ) ) {
680 $mtoParams['desc-link'] = true;
681 $mtoParams['desc-query'] = $query;
687 * Make HTML for a thumbnail including image, border and caption
688 * @param $title Title object
689 * @param $file File object or false if it doesn't exist
690 * @param $label String
692 * @param $align String
693 * @param $params Array
694 * @param $framed Boolean
695 * @param $manualthumb String
698 public static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt,
699 $align = 'right', $params = array(), $framed = false , $manualthumb = "" )
701 $frameParams = array(
707 $frameParams['framed'] = true;
709 if ( $manualthumb ) {
710 $frameParams['manualthumb'] = $manualthumb;
712 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
716 * @param $title Title
718 * @param array $frameParams
719 * @param array $handlerParams
721 * @param string $query
724 public static function makeThumbLink2( Title
$title, $file, $frameParams = array(),
725 $handlerParams = array(), $time = false, $query = "" )
727 global $wgStylePath, $wgContLang;
728 $exists = $file && $file->exists();
732 $hp =& $handlerParams;
734 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
735 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
736 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
737 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
738 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
740 if ( empty( $hp['width'] ) ) {
741 // Reduce width for upright images when parameter 'upright' is used
742 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
747 $outerWidth = $hp['width'] +
2;
749 if ( isset( $fp['manualthumb'] ) ) {
750 # Use manually specified thumbnail
751 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
752 if ( $manual_title ) {
753 $manual_img = wfFindFile( $manual_title );
755 $thumb = $manual_img->getUnscaledThumb( $hp );
760 } elseif ( isset( $fp['framed'] ) ) {
761 // Use image dimensions, don't scale
762 $thumb = $file->getUnscaledThumb( $hp );
764 # Do not present an image bigger than the source, for bitmap-style images
765 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
766 $srcWidth = $file->getWidth( $page );
767 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
768 $hp['width'] = $srcWidth;
770 $thumb = $file->transform( $hp );
774 $outerWidth = $thumb->getWidth() +
2;
776 $outerWidth = $hp['width'] +
2;
780 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
781 # So we don't need to pass it here in $query. However, the URL for the
782 # zoom icon still needs it, so we make a unique query for it. See bug 14771
783 $url = $title->getLocalURL( $query );
785 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
788 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
790 $s .= self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
792 } elseif ( !$thumb ) {
793 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
798 'title' => $fp['title'],
799 'img-class' => 'thumbimage' );
800 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
801 $s .= $thumb->toHtml( $params );
802 if ( isset( $fp['framed'] ) ) {
805 $zoomIcon = Html
::rawElement( 'div', array( 'class' => 'magnify' ),
806 Html
::rawElement( 'a', array(
808 'class' => 'internal',
809 'title' => wfMsg( 'thumbnail-more' ) ),
810 Html
::element( 'img', array(
811 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ?
'-rtl' : '' ) . '.png',
817 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
818 return str_replace( "\n", ' ', $s );
822 * Make a "broken" link to an image
824 * @param $title Title object
825 * @param $html String: link label in htmlescaped text form
826 * @param $query String: query string
827 * @param $trail String: link trail (HTML fragment)
828 * @param $prefix String: link prefix (HTML fragment)
829 * @param $time Boolean: a file of a certain timestamp was requested
832 public static function makeBrokenImageLinkObj( $title, $html = '', $query = '', $trail = '', $prefix = '', $time = false ) {
833 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
834 if ( ! $title instanceof Title
) {
835 return "<!-- ERROR -->{$prefix}{$html}{$trail}";
837 wfProfileIn( __METHOD__
);
838 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
840 list( $inside, $trail ) = self
::splitTrail( $trail );
842 $html = htmlspecialchars( $title->getPrefixedText() );
844 if ( ( $wgUploadMissingFileUrl ||
$wgUploadNavigationUrl ||
$wgEnableUploads ) && !$currentExists ) {
845 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
848 wfProfileOut( __METHOD__
);
849 return self
::linkKnown( $title, "$prefix$html$inside", array(), $query ) . $trail;
852 $href = self
::getUploadUrl( $title, $query );
854 wfProfileOut( __METHOD__
);
855 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
856 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
857 "$prefix$html$inside</a>$trail";
859 wfProfileOut( __METHOD__
);
860 return self
::linkKnown( $title, "$prefix$html$inside", array(), $query ) . $trail;
865 * Get the URL to upload a certain file
867 * @param $destFile Title object of the file to upload
868 * @param $query String: urlencoded query string to prepend
869 * @return String: urlencoded URL
871 protected static function getUploadUrl( $destFile, $query = '' ) {
872 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
873 $q = 'wpDestFile=' . $destFile->getPartialUrl();
877 if ( $wgUploadMissingFileUrl ) {
878 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
879 } elseif( $wgUploadNavigationUrl ) {
880 return wfAppendQuery( $wgUploadNavigationUrl, $q );
882 $upload = SpecialPage
::getTitleFor( 'Upload' );
883 return $upload->getLocalUrl( $q );
888 * Create a direct link to a given uploaded file.
890 * @param $title Title object.
891 * @param $html String: pre-sanitized HTML
892 * @param $time string: MW timestamp of file creation time
893 * @return String: HTML
895 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
896 $img = wfFindFile( $title, array( 'time' => $time ) );
897 return self
::makeMediaLinkFile( $title, $img, $html );
901 * Create a direct link to a given uploaded file.
902 * This will make a broken link if $file is false.
904 * @param $title Title object.
905 * @param $file File|bool mixed File object or false
906 * @param $html String: pre-sanitized HTML
907 * @return String: HTML
909 * @todo Handle invalid or missing images better.
911 public static function makeMediaLinkFile( Title
$title, $file, $html = '' ) {
912 if ( $file && $file->exists() ) {
913 $url = $file->getURL();
916 $url = self
::getUploadUrl( $title );
919 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES
);
923 $u = htmlspecialchars( $url );
924 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$html}</a>";
928 * Make a link to a special page given its name and, optionally,
929 * a message key from the link text.
930 * Usage example: Linker::specialLink( 'Recentchanges' )
934 public static function specialLink( $name, $key = '' ) {
936 $key = strtolower( $name );
939 return self
::linkKnown( SpecialPage
::getTitleFor( $name ) , wfMsg( $key ) );
943 * Make an external link
944 * @param $url String: URL to link to
945 * @param $text String: text of link
946 * @param $escape Boolean: do we escape the link text?
947 * @param $linktype String: type of external link. Gets added to the classes
948 * @param $attribs Array of extra attributes to <a>
951 public static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
954 $class .= " $linktype";
956 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
957 $class .= " {$attribs['class']}";
959 $attribs['class'] = $class;
962 $text = htmlspecialchars( $text );
965 $success = wfRunHooks( 'LinkerMakeExternalLink',
966 array( &$url, &$text, &$link, &$attribs, $linktype ) );
968 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
971 $attribs['href'] = $url;
972 return Html
::rawElement( 'a', $attribs, $text );
976 * Make user link (or user contributions for unregistered users)
977 * @param $userId Integer: user id in database.
978 * @param $userName String: user name in database.
979 * @param $altUserName String: text to display instead of the user name (optional)
980 * @return String: HTML fragment
981 * @since 1.19 Method exists for a long time. $displayText was added in 1.19.
983 public static function userLink( $userId, $userName, $altUserName = false ) {
984 if ( $userId == 0 ) {
985 $page = SpecialPage
::getTitleFor( 'Contributions', $userName );
987 $page = Title
::makeTitle( NS_USER
, $userName );
992 htmlspecialchars( $altUserName !== false ?
$altUserName : $userName ),
993 array( 'class' => 'mw-userlink' )
998 * Generate standard user tool links (talk, contributions, block link, etc.)
1000 * @param $userId Integer: user identifier
1001 * @param $userText String: user name or IP address
1002 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
1003 * red if the user has no edits?
1004 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK and Linker::TOOL_LINKS_EMAIL)
1005 * @param $edits Integer: user edit count (optional, for performance)
1006 * @return String: HTML fragment
1008 public static function userToolLinks(
1009 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1011 global $wgUser, $wgDisableAnonTalk, $wgLang;
1012 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1013 $blockable = !( $flags & self
::TOOL_LINKS_NOBLOCK
);
1014 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
&& $userId;
1018 $items[] = self
::userTalkLink( $userId, $userText );
1021 // check if the user has an edit
1023 if ( $redContribsWhenNoEdits ) {
1024 $count = !is_null( $edits ) ?
$edits : User
::edits( $userId );
1025 if ( $count == 0 ) {
1026 $attribs['class'] = 'new';
1029 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
1031 $items[] = self
::link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
1033 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1034 $items[] = self
::blockLink( $userId, $userText );
1037 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1038 $items[] = self
::emailLink( $userId, $userText );
1041 wfRunHooks( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1044 return ' <span class="mw-usertoollinks">' . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped() . '</span>';
1051 * Alias for userToolLinks( $userId, $userText, true );
1052 * @param $userId Integer: user identifier
1053 * @param $userText String: user name or IP address
1054 * @param $edits Integer: user edit count (optional, for performance)
1057 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1058 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
1063 * @param $userId Integer: user id in database.
1064 * @param $userText String: user name in database.
1065 * @return String: HTML fragment with user talk link
1067 public static function userTalkLink( $userId, $userText ) {
1068 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
1069 $userTalkLink = self
::link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
1070 return $userTalkLink;
1074 * @param $userId Integer: userid
1075 * @param $userText String: user name in database.
1076 * @return String: HTML fragment with block link
1078 public static function blockLink( $userId, $userText ) {
1079 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1080 $blockLink = self
::link( $blockPage, wfMsgHtml( 'blocklink' ) );
1085 * @param $userId Integer: userid
1086 * @param $userText String: user name in database.
1087 * @return String: HTML fragment with e-mail user link
1089 public static function emailLink( $userId, $userText ) {
1090 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1091 $emailLink = self
::link( $emailPage, wfMsgHtml( 'emaillink' ) );
1096 * Generate a user link if the current user is allowed to view it
1097 * @param $rev Revision object.
1098 * @param $isPublic Boolean: show only if all users can see it
1099 * @return String: HTML fragment
1101 public static function revUserLink( $rev, $isPublic = false ) {
1102 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1103 $link = wfMsgHtml( 'rev-deleted-user' );
1104 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1105 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1106 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1108 $link = wfMsgHtml( 'rev-deleted-user' );
1110 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1111 return '<span class="history-deleted">' . $link . '</span>';
1117 * Generate a user tool link cluster if the current user is allowed to view it
1118 * @param $rev Revision object.
1119 * @param $isPublic Boolean: show only if all users can see it
1120 * @return string HTML
1122 public static function revUserTools( $rev, $isPublic = false ) {
1123 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1124 $link = wfMsgHtml( 'rev-deleted-user' );
1125 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1126 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1127 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1128 $link = self
::userLink( $userId, $userText ) .
1129 ' ' . self
::userToolLinks( $userId, $userText );
1131 $link = wfMsgHtml( 'rev-deleted-user' );
1133 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1134 return ' <span class="history-deleted">' . $link . '</span>';
1140 * This function is called by all recent changes variants, by the page history,
1141 * and by the user contributions list. It is responsible for formatting edit
1142 * comments. It escapes any HTML in the comment, but adds some CSS to format
1143 * auto-generated comments (from section editing) and formats [[wikilinks]].
1145 * @author Erik Moeller <moeller@scireview.de>
1147 * Note: there's not always a title to pass to this function.
1148 * Since you can't set a default parameter for a reference, I've turned it
1149 * temporarily to a value pass. Should be adjusted further. --brion
1151 * @param $comment String
1152 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1153 * @param $local Boolean: whether section links should refer to local page
1154 * @return mixed|String
1156 public static function formatComment( $comment, $title = null, $local = false ) {
1157 wfProfileIn( __METHOD__
);
1159 # Sanitize text a bit:
1160 $comment = str_replace( "\n", " ", $comment );
1161 # Allow HTML entities (for bug 13815)
1162 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1164 # Render autocomments and make links:
1165 $comment = self
::formatAutocomments( $comment, $title, $local );
1166 $comment = self
::formatLinksInComment( $comment, $title, $local );
1168 wfProfileOut( __METHOD__
);
1175 static $autocommentTitle;
1176 static $autocommentLocal;
1179 * The pattern for autogen comments is / * foo * /, which makes for
1181 * We look for all comments, match any text before and after the comment,
1182 * add a separator where needed and format the comment itself with CSS
1183 * Called by Linker::formatComment.
1185 * @param $comment String: comment text
1186 * @param $title Title|null An optional title object used to links to sections
1187 * @param $local Boolean: whether section links should refer to local page
1188 * @return String: formatted comment
1190 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1192 self
::$autocommentTitle = $title;
1193 self
::$autocommentLocal = $local;
1194 $comment = preg_replace_callback(
1195 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1196 array( 'Linker', 'formatAutocommentsCallback' ),
1198 self
::$autocommentTitle = null;
1199 self
::$autocommentLocal = null;
1207 private static function formatAutocommentsCallback( $match ) {
1209 $title = self
::$autocommentTitle;
1210 $local = self
::$autocommentLocal;
1219 # Remove links that a user may have manually put in the autosummary
1220 # This could be improved by copying as much of Parser::stripSectionName as desired.
1221 $section = str_replace( '[[:', '', $section );
1222 $section = str_replace( '[[', '', $section );
1223 $section = str_replace( ']]', '', $section );
1225 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1227 $sectionTitle = Title
::newFromText( '#' . $section );
1229 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1230 $title->getDBkey(), $section );
1232 if ( $sectionTitle ) {
1233 $link = self
::link( $sectionTitle,
1234 $wgLang->getArrow(), array(), array(),
1241 # written summary $presep autocomment (summary /* section */)
1242 $pre .= wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) );
1245 # autocomment $postsep written summary (/* section */ summary)
1246 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1248 $auto = '<span class="autocomment">' . $auto . '</span>';
1249 $comment = $pre . $link . $wgLang->getDirMark() . '<span dir="auto">' . $auto . $post . '</span>';
1256 static $commentContextTitle;
1257 static $commentLocal;
1260 * Formats wiki links and media links in text; all other wiki formatting
1263 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1264 * @param $comment String: text to format links in
1265 * @param $title Title|null An optional title object used to links to sections
1266 * @param $local Boolean: whether section links should refer to local page
1269 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1270 self
::$commentContextTitle = $title;
1271 self
::$commentLocal = $local;
1272 $html = preg_replace_callback(
1273 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1274 array( 'Linker', 'formatLinksInCommentCallback' ),
1276 self
::$commentContextTitle = null;
1277 self
::$commentLocal = null;
1285 protected static function formatLinksInCommentCallback( $match ) {
1288 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1289 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1291 $comment = $match[0];
1293 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1294 if ( strpos( $match[1], '%' ) !== false ) {
1295 $match[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $match[1] ) );
1298 # Handle link renaming [[foo|text]] will show link as "text"
1299 if ( $match[3] != "" ) {
1304 $submatch = array();
1306 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1307 # Media link; trail not supported.
1308 $linkRegexp = '/\[\[(.*?)\]\]/';
1309 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1311 $thelink = self
::makeMediaLinkObj( $title, $text );
1314 # Other kind of link
1315 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1316 $trail = $submatch[1];
1320 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1321 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1322 $match[1] = substr( $match[1], 1 );
1323 list( $inside, $trail ) = self
::splitTrail( $trail );
1326 $linkTarget = self
::normalizeSubpageLink( self
::$commentContextTitle,
1327 $match[1], $linkText );
1329 $target = Title
::newFromText( $linkTarget );
1331 if ( $target->getText() == '' && $target->getInterwiki() === ''
1332 && !self
::$commentLocal && self
::$commentContextTitle )
1334 $newTarget = clone ( self
::$commentContextTitle );
1335 $newTarget->setFragment( '#' . $target->getFragment() );
1336 $target = $newTarget;
1338 $thelink = self
::link(
1345 // If the link is still valid, go ahead and replace it in!
1346 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1353 * @param $contextTitle Title
1358 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1361 # :Foobar -- override special treatment of prefix (images, language links)
1362 # /Foobar -- convert to CurrentPage/Foobar
1363 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1364 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1365 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1367 wfProfileIn( __METHOD__
);
1368 $ret = $target; # default return value is no change
1370 # Some namespaces don't allow subpages,
1371 # so only perform processing if subpages are allowed
1372 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1373 $hash = strpos( $target, '#' );
1374 if ( $hash !== false ) {
1375 $suffix = substr( $target, $hash );
1376 $target = substr( $target, 0, $hash );
1381 $target = trim( $target );
1382 # Look at the first character
1383 if ( $target != '' && $target[0] === '/' ) {
1384 # / at end means we don't want the slash to be shown
1386 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1387 if ( $trailingSlashes ) {
1388 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1390 $noslash = substr( $target, 1 );
1393 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1394 if ( $text === '' ) {
1395 $text = $target . $suffix;
1396 } # this might be changed for ugliness reasons
1398 # check for .. subpage backlinks
1400 $nodotdot = $target;
1401 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1403 $nodotdot = substr( $nodotdot, 3 );
1405 if ( $dotdotcount > 0 ) {
1406 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1407 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1408 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1409 # / at the end means don't show full path
1410 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1411 $nodotdot = substr( $nodotdot, 0, -1 );
1412 if ( $text === '' ) {
1413 $text = $nodotdot . $suffix;
1416 $nodotdot = trim( $nodotdot );
1417 if ( $nodotdot != '' ) {
1418 $ret .= '/' . $nodotdot;
1426 wfProfileOut( __METHOD__
);
1431 * Wrap a comment in standard punctuation and formatting if
1432 * it's non-empty, otherwise return empty string.
1434 * @param $comment String
1435 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1436 * @param $local Boolean: whether section links should refer to local page
1440 public static function commentBlock( $comment, $title = null, $local = false ) {
1441 // '*' used to be the comment inserted by the software way back
1442 // in antiquity in case none was provided, here for backwards
1443 // compatability, acc. to brion -ævar
1444 if ( $comment == '' ||
$comment == '*' ) {
1447 $formatted = self
::formatComment( $comment, $title, $local );
1448 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1449 return " <span class=\"comment\">$formatted</span>";
1454 * Wrap and format the given revision's comment block, if the current
1455 * user is allowed to view it.
1457 * @param $rev Revision object
1458 * @param $local Boolean: whether section links should refer to local page
1459 * @param $isPublic Boolean: show only if all users can see it
1460 * @return String: HTML fragment
1462 public static function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1463 if ( $rev->getRawComment() == "" ) {
1466 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1467 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1468 } elseif ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1469 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1470 $rev->getTitle(), $local );
1472 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1474 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1475 return " <span class=\"history-deleted\">$block</span>";
1484 public static function formatRevisionSize( $size ) {
1486 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1489 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1490 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1492 $stxt = htmlspecialchars( $stxt );
1493 return "<span class=\"history-size\">$stxt</span>";
1497 * Add another level to the Table of Contents
1501 public static function tocIndent() {
1506 * Finish one or more sublevels on the Table of Contents
1510 public static function tocUnindent( $level ) {
1511 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1515 * parameter level defines if we are on an indentation level
1519 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1520 $classes = "toclevel-$level";
1521 if ( $sectionIndex !== false ) {
1522 $classes .= " tocsection-$sectionIndex";
1524 return "\n<li class=\"$classes\"><a href=\"#" .
1525 $anchor . '"><span class="tocnumber">' .
1526 $tocnumber . '</span> <span class="toctext">' .
1527 $tocline . '</span></a>';
1531 * End a Table Of Contents line.
1532 * tocUnindent() will be used instead if we're ending a line below
1536 public static function tocLineEnd() {
1541 * Wraps the TOC in a table and provides the hide/collapse javascript.
1543 * @param $toc String: html of the Table Of Contents
1544 * @param $lang mixed: Language code for the toc title
1545 * @return String: full html of the TOC
1547 public static function tocList( $toc, $lang = false ) {
1548 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1550 '<table id="toc" class="toc"><tr><td>'
1551 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1553 . "</ul>\n</td></tr></table>\n";
1557 * Generate a table of contents from a section tree
1560 * @param $tree array Return value of ParserOutput::getSections()
1561 * @return String: HTML fragment
1563 public static function generateTOC( $tree ) {
1566 foreach ( $tree as $section ) {
1567 if ( $section['toclevel'] > $lastLevel )
1568 $toc .= self
::tocIndent();
1569 elseif ( $section['toclevel'] < $lastLevel )
1570 $toc .= self
::tocUnindent(
1571 $lastLevel - $section['toclevel'] );
1573 $toc .= self
::tocLineEnd();
1575 $toc .= self
::tocLine( $section['anchor'],
1576 $section['line'], $section['number'],
1577 $section['toclevel'], $section['index'] );
1578 $lastLevel = $section['toclevel'];
1580 $toc .= self
::tocLineEnd();
1581 return self
::tocList( $toc );
1585 * Create a headline for content
1587 * @param $level Integer: the level of the headline (1-6)
1588 * @param $attribs String: any attributes for the headline, starting with
1589 * a space and ending with '>'
1590 * This *must* be at least '>' for no attribs
1591 * @param $anchor String: the anchor to give the headline (the bit after the #)
1592 * @param $html String: html for the text of the header
1593 * @param $link String: HTML to add for the section edit link
1594 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1595 * backward compatibility (false to omit)
1597 * @return String: HTML headline
1599 public static function makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor = false ) {
1600 $ret = "<h$level$attribs"
1602 . " <span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1604 if ( $legacyAnchor !== false ) {
1605 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1611 * Split a link trail, return the "inside" portion and the remainder of the trail
1612 * as a two-element array
1615 static function splitTrail( $trail ) {
1617 $regex = $wgContLang->linkTrail();
1619 if ( $trail !== '' ) {
1621 if ( preg_match( $regex, $trail, $m ) ) {
1626 return array( $inside, $trail );
1630 * Generate a rollback link for a given revision. Currently it's the
1631 * caller's responsibility to ensure that the revision is the top one. If
1632 * it's not, of course, the user will get an error message.
1634 * If the calling page is called with the parameter &bot=1, all rollback
1635 * links also get that parameter. It causes the edit itself and the rollback
1636 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1637 * changes, so this allows sysops to combat a busy vandal without bothering
1640 * @param $rev Revision object
1643 public static function generateRollback( $rev ) {
1644 return '<span class="mw-rollback-link">'
1645 . wfMessage( 'brackets' )->rawParams( self
::buildRollbackLink( $rev ) )->plain()
1650 * Build a raw rollback link, useful for collections of "tool" links
1652 * @param $rev Revision object
1653 * @return String: HTML fragment
1655 public static function buildRollbackLink( $rev ) {
1656 global $wgRequest, $wgUser;
1657 $title = $rev->getTitle();
1659 'action' => 'rollback',
1660 'from' => $rev->getUserText(),
1661 'token' => $wgUser->getEditToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1663 if ( $wgRequest->getBool( 'bot' ) ) {
1664 $query['bot'] = '1';
1665 $query['hidediff'] = '1'; // bug 15999
1669 wfMsgHtml( 'rollbacklink' ),
1670 array( 'title' => wfMsg( 'tooltip-rollback' ) ),
1672 array( 'known', 'noclasses' )
1677 * Returns HTML for the "templates used on this page" list.
1679 * @param $templates Array of templates from Article::getUsedTemplate
1681 * @param $preview Boolean: whether this is for a preview
1682 * @param $section Boolean: whether this is for a section edit
1683 * @return String: HTML output
1685 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1686 wfProfileIn( __METHOD__
);
1689 if ( count( $templates ) > 0 ) {
1690 # Do a batch existence check
1691 $batch = new LinkBatch
;
1692 foreach ( $templates as $title ) {
1693 $batch->addObj( $title );
1697 # Construct the HTML
1698 $outText = '<div class="mw-templatesUsedExplanation">';
1700 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1701 } elseif ( $section ) {
1702 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1704 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1706 $outText .= "</div><ul>\n";
1708 usort( $templates, array( 'Title', 'compare' ) );
1709 foreach ( $templates as $titleObj ) {
1710 $r = $titleObj->getRestrictions( 'edit' );
1711 if ( in_array( 'sysop', $r ) ) {
1712 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1713 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1714 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1718 if ( $titleObj->quickUserCan( 'edit' ) ) {
1719 $editLink = self
::link(
1721 wfMsg( 'editlink' ),
1723 array( 'action' => 'edit' )
1726 $editLink = self
::link(
1728 wfMsg( 'viewsourcelink' ),
1730 array( 'action' => 'edit' )
1733 $outText .= '<li>' . self
::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1735 $outText .= '</ul>';
1737 wfProfileOut( __METHOD__
);
1742 * Returns HTML for the "hidden categories on this page" list.
1744 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1746 * @return String: HTML output
1748 public static function formatHiddenCategories( $hiddencats ) {
1750 wfProfileIn( __METHOD__
);
1753 if ( count( $hiddencats ) > 0 ) {
1754 # Construct the HTML
1755 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1756 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1757 $outText .= "</div><ul>\n";
1759 foreach ( $hiddencats as $titleObj ) {
1760 $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
1762 $outText .= '</ul>';
1764 wfProfileOut( __METHOD__
);
1769 * Format a size in bytes for output, using an appropriate
1770 * unit (B, KB, MB or GB) according to the magnitude in question
1772 * @param $size int Size to format
1775 public static function formatSize( $size ) {
1777 return htmlspecialchars( $wgLang->formatSize( $size ) );
1781 * Given the id of an interface element, constructs the appropriate title
1782 * attribute from the system messages. (Note, this is usually the id but
1783 * isn't always, because sometimes the accesskey needs to go on a different
1784 * element than the id, for reverse-compatibility, etc.)
1786 * @param $name String: id of the element, minus prefixes.
1787 * @param $options Mixed: null or the string 'withaccess' to add an access-
1789 * @return String: contents of the title attribute (which you must HTML-
1790 * escape), or false for no title attribute
1792 public static function titleAttrib( $name, $options = null ) {
1793 wfProfileIn( __METHOD__
);
1795 $message = wfMessage( "tooltip-$name" );
1797 if ( !$message->exists() ) {
1800 $tooltip = $message->text();
1801 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1802 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1803 # Message equal to '-' means suppress it.
1804 if ( $tooltip == '-' ) {
1809 if ( $options == 'withaccess' ) {
1810 $accesskey = self
::accesskey( $name );
1811 if ( $accesskey !== false ) {
1812 if ( $tooltip === false ||
$tooltip === '' ) {
1813 $tooltip = "[$accesskey]";
1815 $tooltip .= " [$accesskey]";
1820 wfProfileOut( __METHOD__
);
1824 static $accesskeycache;
1827 * Given the id of an interface element, constructs the appropriate
1828 * accesskey attribute from the system messages. (Note, this is usually
1829 * the id but isn't always, because sometimes the accesskey needs to go on
1830 * a different element than the id, for reverse-compatibility, etc.)
1832 * @param $name String: id of the element, minus prefixes.
1833 * @return String: contents of the accesskey attribute (which you must HTML-
1834 * escape), or false for no accesskey attribute
1836 public static function accesskey( $name ) {
1837 if ( isset( self
::$accesskeycache[$name] ) ) {
1838 return self
::$accesskeycache[$name];
1840 wfProfileIn( __METHOD__
);
1842 $message = wfMessage( "accesskey-$name" );
1844 if ( !$message->exists() ) {
1847 $accesskey = $message->plain();
1848 if ( $accesskey === '' ||
$accesskey === '-' ) {
1849 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
1850 # attribute, but this is broken for accesskey: that might be a useful
1856 wfProfileOut( __METHOD__
);
1857 return self
::$accesskeycache[$name] = $accesskey;
1861 * Get a revision-deletion link, or disabled link, or nothing, depending
1862 * on user permissions & the settings on the revision.
1864 * Will use forward-compatible revision ID in the Special:RevDelete link
1865 * if possible, otherwise the timestamp-based ID which may break after
1869 * @param Revision $rev
1870 * @param Revision $title
1871 * @return string HTML fragment
1873 public static function getRevDeleteLink( User
$user, Revision
$rev, Title
$title ) {
1874 $canHide = $user->isAllowed( 'deleterevision' );
1875 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
1879 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
1880 return Linker
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
1882 if ( $rev->getId() ) {
1883 // RevDelete links using revision ID are stable across
1884 // page deletion and undeletion; use when possible.
1886 'type' => 'revision',
1887 'target' => $title->getPrefixedDBkey(),
1888 'ids' => $rev->getId()
1891 // Older deleted entries didn't save a revision ID.
1892 // We have to refer to these by timestamp, ick!
1894 'type' => 'archive',
1895 'target' => $title->getPrefixedDBkey(),
1896 'ids' => $rev->getTimestamp()
1899 return Linker
::revDeleteLink( $query,
1900 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
1905 * Creates a (show/hide) link for deleting revisions/log entries
1907 * @param $query Array: query parameters to be passed to link()
1908 * @param $restricted Boolean: set to true to use a <strong> instead of a <span>
1909 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1911 * @return String: HTML <a> link to Special:Revisiondelete, wrapped in a
1912 * span to allow for customization of appearance with CSS
1914 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
1915 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
1916 $html = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1917 $tag = $restricted ?
'strong' : 'span';
1918 $link = self
::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
1919 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $link )->escaped() );
1923 * Creates a dead (show/hide) link for deleting revisions/log entries
1925 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
1927 * @return string HTML text wrapped in a span to allow for customization
1928 * of appearance with CSS
1930 public static function revDeleteLinkDisabled( $delete = true ) {
1931 $html = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
1932 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $html )->escaped() );
1935 /* Deprecated methods */
1938 * @deprecated since 1.16 Use link()
1940 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
1941 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
1943 * @param $title String: The text of the title
1944 * @param $text String: Link text
1945 * @param $query String: Optional query part
1946 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
1947 * be included in the link text. Other characters will be appended after
1948 * the end of the link.
1951 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
1952 wfDeprecated( __METHOD__
, '1.16' );
1954 $nt = Title
::newFromText( $title );
1955 if ( $nt instanceof Title
) {
1956 return self
::makeBrokenLinkObj( $nt, $text, $query, $trail );
1958 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
1959 return $text == '' ?
$title : $text;
1964 * @deprecated since 1.16 Use link()
1966 * Make a link for a title which may or may not be in the database. If you need to
1967 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
1968 * call to this will result in a DB query.
1970 * @param $nt Title: the title object to make the link from, e.g. from
1971 * Title::newFromText.
1972 * @param $text String: link text
1973 * @param $query String: optional query part
1974 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
1975 * be included in the link text. Other characters will be appended after
1976 * the end of the link.
1977 * @param $prefix String: optional prefix. As trail, only before instead of after.
1980 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1981 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
1983 wfProfileIn( __METHOD__
);
1984 $query = wfCgiToArray( $query );
1985 list( $inside, $trail ) = self
::splitTrail( $trail );
1986 if ( $text === '' ) {
1987 $text = self
::linkText( $nt );
1990 $ret = self
::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
1992 wfProfileOut( __METHOD__
);
1997 * @deprecated since 1.16 Use link()
1999 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
2000 * it doesn't have to do a database query. It's also valid for interwiki titles and special
2003 * @param $title Title object of target page
2004 * @param $text String: text to replace the title
2005 * @param $query String: link target
2006 * @param $trail String: text after link
2007 * @param $prefix String: text before link text
2008 * @param $aprops String: extra attributes to the a-element
2009 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
2010 * @return string the a-element
2012 static function makeKnownLinkObj(
2013 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
2015 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
2017 wfProfileIn( __METHOD__
);
2019 if ( $text == '' ) {
2020 $text = self
::linkText( $title );
2022 $attribs = Sanitizer
::mergeAttributes(
2023 Sanitizer
::decodeTagAttributes( $aprops ),
2024 Sanitizer
::decodeTagAttributes( $style )
2026 $query = wfCgiToArray( $query );
2027 list( $inside, $trail ) = self
::splitTrail( $trail );
2029 $ret = self
::link( $title, "$prefix$text$inside", $attribs, $query,
2030 array( 'known', 'noclasses' ) ) . $trail;
2032 wfProfileOut( __METHOD__
);
2037 * @deprecated since 1.16 Use link()
2039 * Make a red link to the edit page of a given title.
2041 * @param $title Title object of the target page
2042 * @param $text String: Link text
2043 * @param $query String: Optional query part
2044 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
2045 * be included in the link text. Other characters will be appended after
2046 * the end of the link.
2047 * @param $prefix String: Optional prefix
2050 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
2051 wfDeprecated( __METHOD__
, '1.16' );
2053 wfProfileIn( __METHOD__
);
2055 list( $inside, $trail ) = self
::splitTrail( $trail );
2056 if ( $text === '' ) {
2057 $text = self
::linkText( $title );
2060 $ret = self
::link( $title, "$prefix$text$inside", array(),
2061 wfCgiToArray( $query ), 'broken' ) . $trail;
2063 wfProfileOut( __METHOD__
);
2068 * @deprecated since 1.16 Use link()
2070 * Make a coloured link.
2072 * @param $nt Title object of the target page
2073 * @param $colour Integer: colour of the link
2074 * @param $text String: link text
2075 * @param $query String: optional query part
2076 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2077 * be included in the link text. Other characters will be appended after
2078 * the end of the link.
2079 * @param $prefix String: Optional prefix
2082 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2083 wfDeprecated( __METHOD__
, '1.16' );
2085 if ( $colour != '' ) {
2086 $style = self
::getInternalLinkAttributesObj( $nt, $text, $colour );
2090 return self
::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2094 * Returns the attributes for the tooltip and access key.
2097 public static function tooltipAndAccesskeyAttribs( $name ) {
2098 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2099 # no attribute" instead of "output '' as value for attribute", this
2100 # would be three lines.
2102 'title' => self
::titleAttrib( $name, 'withaccess' ),
2103 'accesskey' => self
::accesskey( $name )
2105 if ( $attribs['title'] === false ) {
2106 unset( $attribs['title'] );
2108 if ( $attribs['accesskey'] === false ) {
2109 unset( $attribs['accesskey'] );
2115 * Returns raw bits of HTML, use titleAttrib()
2116 * @return null|string
2118 public static function tooltip( $name, $options = null ) {
2119 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2120 # no attribute" instead of "output '' as value for attribute", this
2121 # would be two lines.
2122 $tooltip = self
::titleAttrib( $name, $options );
2123 if ( $tooltip === false ) {
2126 return Xml
::expandAttributes( array(
2138 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2139 * into static calls to the new Linker for backwards compatibility.
2141 * @param $fname String Name of called method
2142 * @param $args Array Arguments to the method
2145 public function __call( $fname, $args ) {
2146 return call_user_func_array( array( 'Linker', $fname ), $args );