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 && $t->isContentPage() &&
143 $t->exists() && $t->getLength() < $threshold
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.
410 * @param $html String [optional]
411 * @param $query String [optional]
412 * @param $trail String [optional]
413 * @param $prefix String [optional]
418 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
420 $html = htmlspecialchars( $nt->getPrefixedText() );
422 list( $inside, $trail ) = self
::splitTrail( $trail );
423 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
427 * Get a message saying that an invalid title was encountered.
428 * This should be called after a method like Title::makeTitleSafe() returned
429 * a value indicating that the title object is invalid.
431 * @param $context IContextSource context to use to get the messages
432 * @param $namespace int Namespace number
433 * @param $title string Text of the title, without the namespace part
435 public static function getInvalidTitleDescription( IContextSource
$context, $namespace, $title ) {
438 // First we check whether the namespace exists or not.
439 if ( MWNamespace
::exists( $namespace ) ) {
440 if ( $namespace == NS_MAIN
) {
441 $name = $context->msg( 'blanknamespace' )->text();
443 $name = $wgContLang->getFormattedNsText( $namespace );
445 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
447 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
452 * @param $title Title
455 static function normaliseSpecialPage( Title
$title ) {
456 if ( $title->isSpecialPage() ) {
457 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
461 $ret = SpecialPage
::getTitleFor( $name, $subpage );
462 $ret->mFragment
= $title->getFragment();
470 * Returns the filename part of an url.
471 * Used as alternative text for external images.
477 private static function fnamePart( $url ) {
478 $basename = strrchr( $url, '/' );
479 if ( false === $basename ) {
482 $basename = substr( $basename, 1 );
488 * Return the code for images which were added via external links,
489 * via Parser::maybeMakeExternalImage().
496 public static function makeExternalImage( $url, $alt = '' ) {
498 $alt = self
::fnamePart( $url );
501 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
503 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
506 return Html
::element( 'img',
513 * Given parameters derived from [[Image:Foo|options...]], generate the
514 * HTML that that syntax inserts in the page.
516 * @param $parser Parser object
517 * @param $title Title object of the file (not the currently viewed page)
518 * @param $file File object, or false if it doesn't exist
519 * @param $frameParams Array: associative array of parameters external to the media handler.
520 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
521 * will often be false.
522 * thumbnail If present, downscale and frame
523 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
524 * framed Shows image in original size in a frame
525 * frameless Downscale but don't frame
526 * upright If present, tweak default sizes for portrait orientation
527 * upright_factor Fudge factor for "upright" tweak (default 0.75)
528 * border If present, show a border around the image
529 * align Horizontal alignment (left, right, center, none)
530 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
531 * bottom, text-bottom)
532 * alt Alternate text for image (i.e. alt attribute). Plain text.
533 * caption HTML for image caption.
534 * link-url URL to link to
535 * link-title Title object to link to
536 * link-target Value for the target attribue, only with link-url
537 * no-link Boolean, suppress description link
539 * @param $handlerParams Array: associative array of media handler parameters, to be passed
540 * to transform(). Typical keys are "width" and "page".
541 * @param $time String: timestamp of the file, set as false for current
542 * @param $query String: query params for desc url
543 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
545 * @return String: HTML for an image, with links, wrappers, etc.
547 public static function makeImageLink( /*Parser*/ $parser, Title
$title, $file, $frameParams = array(),
548 $handlerParams = array(), $time = false, $query = "", $widthOption = null )
551 $dummy = new DummyLinker
;
552 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
553 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
557 if ( $file && !$file->allowInlineDisplay() ) {
558 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
559 return self
::link( $title );
564 $hp =& $handlerParams;
566 // Clean up parameters
567 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
568 if ( !isset( $fp['align'] ) ) {
571 if ( !isset( $fp['alt'] ) ) {
574 if ( !isset( $fp['title'] ) ) {
578 $prefix = $postfix = '';
580 if ( 'center' == $fp['align'] ) {
581 $prefix = '<div class="center">';
583 $fp['align'] = 'none';
585 if ( $file && !isset( $hp['width'] ) ) {
586 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
587 // If its a vector image, and user only specifies height
588 // we don't want it to be limited by its "normal" width.
589 global $wgSVGMaxSize;
590 $hp['width'] = $wgSVGMaxSize;
592 $hp['width'] = $file->getWidth( $page );
595 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
596 global $wgThumbLimits, $wgThumbUpright;
597 if ( !isset( $widthOption ) ||
!isset( $wgThumbLimits[$widthOption] ) ) {
598 $widthOption = User
::getDefaultOption( 'thumbsize' );
601 // Reduce width for upright images when parameter 'upright' is used
602 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
603 $fp['upright'] = $wgThumbUpright;
605 // 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
606 $prefWidth = isset( $fp['upright'] ) ?
607 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
608 $wgThumbLimits[$widthOption];
610 // Use width which is smaller: real image width or user preference width
611 // Unless image is scalable vector.
612 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
613 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
614 $hp['width'] = $prefWidth;
619 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
620 # Create a thumbnail. Alignment depends on the writing direction of
621 # the page content language (right-aligned for LTR languages,
622 # left-aligned for RTL languages)
624 # If a thumbnail width has not been provided, it is set
625 # to the default user option as specified in Language*.php
626 if ( $fp['align'] == '' ) {
627 if( $parser instanceof Parser
) {
628 $fp['align'] = $parser->getTargetLanguage()->alignEnd();
630 # backwards compatibility, remove with makeImageLink2()
632 $fp['align'] = $wgContLang->alignEnd();
635 return $prefix . self
::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
638 if ( $file && isset( $fp['frameless'] ) ) {
639 $srcWidth = $file->getWidth( $page );
640 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
641 # This is the same behaviour as the "thumb" option does it already.
642 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
643 $hp['width'] = $srcWidth;
647 if ( $file && isset( $hp['width'] ) ) {
648 # Create a resized image, without the additional thumbnail features
649 $thumb = $file->transform( $hp );
655 $s = self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
659 'title' => $fp['title'],
660 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false ,
661 'img-class' => isset( $fp['border'] ) ?
'thumbborder' : false );
662 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
664 $s = $thumb->toHtml( $params );
666 if ( $fp['align'] != '' ) {
667 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
669 return str_replace( "\n", ' ', $prefix . $s . $postfix );
673 * See makeImageLink()
674 * When this function is removed, remove if( $parser instanceof Parser ) check there too
675 * @deprecated since 1.20
677 public static function makeImageLink2( Title
$title, $file, $frameParams = array(),
678 $handlerParams = array(), $time = false, $query = "", $widthOption = null ) {
679 return self
::makeImageLink( null, $title, $file, $frameParams,
680 $handlerParams, $time, $query, $widthOption );
684 * Get the link parameters for MediaTransformOutput::toHtml() from given
685 * frame parameters supplied by the Parser.
686 * @param $frameParams array The frame parameters
687 * @param $query string An optional query string to add to description page links
690 private static function getImageLinkMTOParams( $frameParams, $query = '' ) {
691 $mtoParams = array();
692 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
693 $mtoParams['custom-url-link'] = $frameParams['link-url'];
694 if ( isset( $frameParams['link-target'] ) ) {
695 $mtoParams['custom-target-link'] = $frameParams['link-target'];
697 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
698 $mtoParams['custom-title-link'] = self
::normaliseSpecialPage( $frameParams['link-title'] );
699 } elseif ( !empty( $frameParams['no-link'] ) ) {
702 $mtoParams['desc-link'] = true;
703 $mtoParams['desc-query'] = $query;
709 * Make HTML for a thumbnail including image, border and caption
710 * @param $title Title object
711 * @param $file File object or false if it doesn't exist
712 * @param $label String
714 * @param $align String
715 * @param $params Array
716 * @param $framed Boolean
717 * @param $manualthumb String
720 public static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt,
721 $align = 'right', $params = array(), $framed = false , $manualthumb = "" )
723 $frameParams = array(
729 $frameParams['framed'] = true;
731 if ( $manualthumb ) {
732 $frameParams['manualthumb'] = $manualthumb;
734 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
738 * @param $title Title
740 * @param array $frameParams
741 * @param array $handlerParams
743 * @param string $query
746 public static function makeThumbLink2( Title
$title, $file, $frameParams = array(),
747 $handlerParams = array(), $time = false, $query = "" )
749 global $wgStylePath, $wgContLang;
750 $exists = $file && $file->exists();
754 $hp =& $handlerParams;
756 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
757 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
758 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
759 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
760 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
762 if ( empty( $hp['width'] ) ) {
763 // Reduce width for upright images when parameter 'upright' is used
764 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
769 $outerWidth = $hp['width'] +
2;
771 if ( isset( $fp['manualthumb'] ) ) {
772 # Use manually specified thumbnail
773 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
774 if ( $manual_title ) {
775 $manual_img = wfFindFile( $manual_title );
777 $thumb = $manual_img->getUnscaledThumb( $hp );
782 } elseif ( isset( $fp['framed'] ) ) {
783 // Use image dimensions, don't scale
784 $thumb = $file->getUnscaledThumb( $hp );
786 # Do not present an image bigger than the source, for bitmap-style images
787 # This is a hack to maintain compatibility with arbitrary pre-1.10 behaviour
788 $srcWidth = $file->getWidth( $page );
789 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
790 $hp['width'] = $srcWidth;
792 $thumb = $file->transform( $hp );
796 $outerWidth = $thumb->getWidth() +
2;
798 $outerWidth = $hp['width'] +
2;
802 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
803 # So we don't need to pass it here in $query. However, the URL for the
804 # zoom icon still needs it, so we make a unique query for it. See bug 14771
805 $url = $title->getLocalURL( $query );
807 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
810 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
812 $s .= self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
814 } elseif ( !$thumb ) {
815 $s .= htmlspecialchars( wfMsg( 'thumbnail_error', '' ) );
820 'title' => $fp['title'],
821 'img-class' => 'thumbimage' );
822 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
823 $s .= $thumb->toHtml( $params );
824 if ( isset( $fp['framed'] ) ) {
827 $zoomIcon = Html
::rawElement( 'div', array( 'class' => 'magnify' ),
828 Html
::rawElement( 'a', array(
830 'class' => 'internal',
831 'title' => wfMsg( 'thumbnail-more' ) ),
832 Html
::element( 'img', array(
833 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ?
'-rtl' : '' ) . '.png',
839 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
840 return str_replace( "\n", ' ', $s );
844 * Make a "broken" link to an image
846 * @param $title Title object
847 * @param $html String: link label in htmlescaped text form
848 * @param $query String: query string
849 * @param $trail String: link trail (HTML fragment)
850 * @param $prefix String: link prefix (HTML fragment)
851 * @param $time Boolean: a file of a certain timestamp was requested
854 public static function makeBrokenImageLinkObj( $title, $html = '', $query = '', $trail = '', $prefix = '', $time = false ) {
855 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
856 if ( ! $title instanceof Title
) {
857 return "<!-- ERROR -->{$prefix}{$html}{$trail}";
859 wfProfileIn( __METHOD__
);
860 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
862 list( $inside, $trail ) = self
::splitTrail( $trail );
864 $html = htmlspecialchars( $title->getPrefixedText() );
866 if ( ( $wgUploadMissingFileUrl ||
$wgUploadNavigationUrl ||
$wgEnableUploads ) && !$currentExists ) {
867 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
870 wfProfileOut( __METHOD__
);
871 return self
::linkKnown( $title, "$prefix$html$inside", array(), $query ) . $trail;
874 $href = self
::getUploadUrl( $title, $query );
876 wfProfileOut( __METHOD__
);
877 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
878 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
879 "$prefix$html$inside</a>$trail";
881 wfProfileOut( __METHOD__
);
882 return self
::linkKnown( $title, "$prefix$html$inside", array(), $query ) . $trail;
887 * Get the URL to upload a certain file
889 * @param $destFile Title object of the file to upload
890 * @param $query String: urlencoded query string to prepend
891 * @return String: urlencoded URL
893 protected static function getUploadUrl( $destFile, $query = '' ) {
894 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
895 $q = 'wpDestFile=' . $destFile->getPartialUrl();
899 if ( $wgUploadMissingFileUrl ) {
900 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
901 } elseif( $wgUploadNavigationUrl ) {
902 return wfAppendQuery( $wgUploadNavigationUrl, $q );
904 $upload = SpecialPage
::getTitleFor( 'Upload' );
905 return $upload->getLocalUrl( $q );
910 * Create a direct link to a given uploaded file.
912 * @param $title Title object.
913 * @param $html String: pre-sanitized HTML
914 * @param $time string: MW timestamp of file creation time
915 * @return String: HTML
917 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
918 $img = wfFindFile( $title, array( 'time' => $time ) );
919 return self
::makeMediaLinkFile( $title, $img, $html );
923 * Create a direct link to a given uploaded file.
924 * This will make a broken link if $file is false.
926 * @param $title Title object.
927 * @param $file File|bool mixed File object or false
928 * @param $html String: pre-sanitized HTML
929 * @return String: HTML
931 * @todo Handle invalid or missing images better.
933 public static function makeMediaLinkFile( Title
$title, $file, $html = '' ) {
934 if ( $file && $file->exists() ) {
935 $url = $file->getURL();
938 $url = self
::getUploadUrl( $title );
941 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES
);
945 $u = htmlspecialchars( $url );
946 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$html}</a>";
950 * Make a link to a special page given its name and, optionally,
951 * a message key from the link text.
952 * Usage example: Linker::specialLink( 'Recentchanges' )
956 public static function specialLink( $name, $key = '' ) {
958 $key = strtolower( $name );
961 return self
::linkKnown( SpecialPage
::getTitleFor( $name ) , wfMsg( $key ) );
965 * Make an external link
966 * @param $url String: URL to link to
967 * @param $text String: text of link
968 * @param $escape Boolean: do we escape the link text?
969 * @param $linktype String: type of external link. Gets added to the classes
970 * @param $attribs Array of extra attributes to <a>
973 public static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
976 $class .= " $linktype";
978 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
979 $class .= " {$attribs['class']}";
981 $attribs['class'] = $class;
984 $text = htmlspecialchars( $text );
987 $success = wfRunHooks( 'LinkerMakeExternalLink',
988 array( &$url, &$text, &$link, &$attribs, $linktype ) );
990 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
993 $attribs['href'] = $url;
994 return Html
::rawElement( 'a', $attribs, $text );
998 * Make user link (or user contributions for unregistered users)
999 * @param $userId Integer: user id in database.
1000 * @param $userName String: user name in database.
1001 * @param $altUserName String: text to display instead of the user name (optional)
1002 * @return String: HTML fragment
1003 * @since 1.19 Method exists for a long time. $altUserName was added in 1.19.
1005 public static function userLink( $userId, $userName, $altUserName = false ) {
1006 if ( $userId == 0 ) {
1007 $page = SpecialPage
::getTitleFor( 'Contributions', $userName );
1009 $page = Title
::makeTitle( NS_USER
, $userName );
1014 htmlspecialchars( $altUserName !== false ?
$altUserName : $userName ),
1015 array( 'class' => 'mw-userlink' )
1020 * Generate standard user tool links (talk, contributions, block link, etc.)
1022 * @param $userId Integer: user identifier
1023 * @param $userText String: user name or IP address
1024 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
1025 * red if the user has no edits?
1026 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK and Linker::TOOL_LINKS_EMAIL)
1027 * @param $edits Integer: user edit count (optional, for performance)
1028 * @return String: HTML fragment
1030 public static function userToolLinks(
1031 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1033 global $wgUser, $wgDisableAnonTalk, $wgLang;
1034 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1035 $blockable = !( $flags & self
::TOOL_LINKS_NOBLOCK
);
1036 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
&& $userId;
1040 $items[] = self
::userTalkLink( $userId, $userText );
1043 // check if the user has an edit
1045 if ( $redContribsWhenNoEdits ) {
1046 $count = !is_null( $edits ) ?
$edits : User
::edits( $userId );
1047 if ( $count == 0 ) {
1048 $attribs['class'] = 'new';
1051 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
1053 $items[] = self
::link( $contribsPage, wfMsgHtml( 'contribslink' ), $attribs );
1055 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1056 $items[] = self
::blockLink( $userId, $userText );
1059 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1060 $items[] = self
::emailLink( $userId, $userText );
1063 wfRunHooks( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1066 return wfMessage( 'word-separator' )->plain()
1067 . '<span class="mw-usertoollinks">'
1068 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1076 * Alias for userToolLinks( $userId, $userText, true );
1077 * @param $userId Integer: user identifier
1078 * @param $userText String: user name or IP address
1079 * @param $edits Integer: user edit count (optional, for performance)
1082 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1083 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
1088 * @param $userId Integer: user id in database.
1089 * @param $userText String: user name in database.
1090 * @return String: HTML fragment with user talk link
1092 public static function userTalkLink( $userId, $userText ) {
1093 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
1094 $userTalkLink = self
::link( $userTalkPage, wfMsgHtml( 'talkpagelinktext' ) );
1095 return $userTalkLink;
1099 * @param $userId Integer: userid
1100 * @param $userText String: user name in database.
1101 * @return String: HTML fragment with block link
1103 public static function blockLink( $userId, $userText ) {
1104 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1105 $blockLink = self
::link( $blockPage, wfMsgHtml( 'blocklink' ) );
1110 * @param $userId Integer: userid
1111 * @param $userText String: user name in database.
1112 * @return String: HTML fragment with e-mail user link
1114 public static function emailLink( $userId, $userText ) {
1115 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1116 $emailLink = self
::link( $emailPage, wfMsgHtml( 'emaillink' ) );
1121 * Generate a user link if the current user is allowed to view it
1122 * @param $rev Revision object.
1123 * @param $isPublic Boolean: show only if all users can see it
1124 * @return String: HTML fragment
1126 public static function revUserLink( $rev, $isPublic = false ) {
1127 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1128 $link = wfMsgHtml( 'rev-deleted-user' );
1129 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1130 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1131 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1133 $link = wfMsgHtml( 'rev-deleted-user' );
1135 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1136 return '<span class="history-deleted">' . $link . '</span>';
1142 * Generate a user tool link cluster if the current user is allowed to view it
1143 * @param $rev Revision object.
1144 * @param $isPublic Boolean: show only if all users can see it
1145 * @return string HTML
1147 public static function revUserTools( $rev, $isPublic = false ) {
1148 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1149 $link = wfMsgHtml( 'rev-deleted-user' );
1150 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1151 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1152 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1153 $link = self
::userLink( $userId, $userText )
1154 . wfMessage( 'word-separator' )->plain()
1155 . self
::userToolLinks( $userId, $userText );
1157 $link = wfMsgHtml( 'rev-deleted-user' );
1159 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1160 return ' <span class="history-deleted">' . $link . '</span>';
1166 * This function is called by all recent changes variants, by the page history,
1167 * and by the user contributions list. It is responsible for formatting edit
1168 * comments. It escapes any HTML in the comment, but adds some CSS to format
1169 * auto-generated comments (from section editing) and formats [[wikilinks]].
1171 * @author Erik Moeller <moeller@scireview.de>
1173 * Note: there's not always a title to pass to this function.
1174 * Since you can't set a default parameter for a reference, I've turned it
1175 * temporarily to a value pass. Should be adjusted further. --brion
1177 * @param $comment String
1178 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1179 * @param $local Boolean: whether section links should refer to local page
1180 * @return mixed|String
1182 public static function formatComment( $comment, $title = null, $local = false ) {
1183 wfProfileIn( __METHOD__
);
1185 # Sanitize text a bit:
1186 $comment = str_replace( "\n", " ", $comment );
1187 # Allow HTML entities (for bug 13815)
1188 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1190 # Render autocomments and make links:
1191 $comment = self
::formatAutocomments( $comment, $title, $local );
1192 $comment = self
::formatLinksInComment( $comment, $title, $local );
1194 wfProfileOut( __METHOD__
);
1201 static $autocommentTitle;
1202 static $autocommentLocal;
1205 * The pattern for autogen comments is / * foo * /, which makes for
1207 * We look for all comments, match any text before and after the comment,
1208 * add a separator where needed and format the comment itself with CSS
1209 * Called by Linker::formatComment.
1211 * @param $comment String: comment text
1212 * @param $title Title|null An optional title object used to links to sections
1213 * @param $local Boolean: whether section links should refer to local page
1214 * @return String: formatted comment
1216 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1218 self
::$autocommentTitle = $title;
1219 self
::$autocommentLocal = $local;
1220 $comment = preg_replace_callback(
1221 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1222 array( 'Linker', 'formatAutocommentsCallback' ),
1224 self
::$autocommentTitle = null;
1225 self
::$autocommentLocal = null;
1233 private static function formatAutocommentsCallback( $match ) {
1235 $title = self
::$autocommentTitle;
1236 $local = self
::$autocommentLocal;
1242 wfRunHooks( 'FormatAutocomments', array( &$comment, $pre, $auto, $post, $title, $local ) );
1243 if ( $comment === null ) {
1248 # Remove links that a user may have manually put in the autosummary
1249 # This could be improved by copying as much of Parser::stripSectionName as desired.
1250 $section = str_replace( '[[:', '', $section );
1251 $section = str_replace( '[[', '', $section );
1252 $section = str_replace( ']]', '', $section );
1254 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1256 $sectionTitle = Title
::newFromText( '#' . $section );
1258 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1259 $title->getDBkey(), $section );
1261 if ( $sectionTitle ) {
1262 $link = self
::link( $sectionTitle,
1263 $wgLang->getArrow(), array(), array(),
1270 # written summary $presep autocomment (summary /* section */)
1271 $pre .= wfMsgExt( 'autocomment-prefix', array( 'escapenoentities', 'content' ) );
1274 # autocomment $postsep written summary (/* section */ summary)
1275 $auto .= wfMsgExt( 'colon-separator', array( 'escapenoentities', 'content' ) );
1277 $auto = '<span class="autocomment">' . $auto . '</span>';
1278 $comment = $pre . $link . $wgLang->getDirMark() . '<span dir="auto">' . $auto . $post . '</span>';
1286 static $commentContextTitle;
1287 static $commentLocal;
1290 * Formats wiki links and media links in text; all other wiki formatting
1293 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1294 * @param $comment String: text to format links in
1295 * @param $title Title|null An optional title object used to links to sections
1296 * @param $local Boolean: whether section links should refer to local page
1299 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1300 self
::$commentContextTitle = $title;
1301 self
::$commentLocal = $local;
1302 $html = preg_replace_callback(
1303 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1304 array( 'Linker', 'formatLinksInCommentCallback' ),
1306 self
::$commentContextTitle = null;
1307 self
::$commentLocal = null;
1315 protected static function formatLinksInCommentCallback( $match ) {
1318 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1319 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1321 $comment = $match[0];
1323 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1324 if ( strpos( $match[1], '%' ) !== false ) {
1325 $match[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $match[1] ) );
1328 # Handle link renaming [[foo|text]] will show link as "text"
1329 if ( $match[3] != "" ) {
1334 $submatch = array();
1336 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1337 # Media link; trail not supported.
1338 $linkRegexp = '/\[\[(.*?)\]\]/';
1339 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1341 $thelink = self
::makeMediaLinkObj( $title, $text );
1344 # Other kind of link
1345 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1346 $trail = $submatch[1];
1350 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1351 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1352 $match[1] = substr( $match[1], 1 );
1353 list( $inside, $trail ) = self
::splitTrail( $trail );
1356 $linkTarget = self
::normalizeSubpageLink( self
::$commentContextTitle,
1357 $match[1], $linkText );
1359 $target = Title
::newFromText( $linkTarget );
1361 if ( $target->getText() == '' && $target->getInterwiki() === ''
1362 && !self
::$commentLocal && self
::$commentContextTitle )
1364 $newTarget = clone ( self
::$commentContextTitle );
1365 $newTarget->setFragment( '#' . $target->getFragment() );
1366 $target = $newTarget;
1368 $thelink = self
::link(
1375 // If the link is still valid, go ahead and replace it in!
1376 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1383 * @param $contextTitle Title
1388 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1391 # :Foobar -- override special treatment of prefix (images, language links)
1392 # /Foobar -- convert to CurrentPage/Foobar
1393 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1394 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1395 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1397 wfProfileIn( __METHOD__
);
1398 $ret = $target; # default return value is no change
1400 # Some namespaces don't allow subpages,
1401 # so only perform processing if subpages are allowed
1402 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1403 $hash = strpos( $target, '#' );
1404 if ( $hash !== false ) {
1405 $suffix = substr( $target, $hash );
1406 $target = substr( $target, 0, $hash );
1411 $target = trim( $target );
1412 # Look at the first character
1413 if ( $target != '' && $target[0] === '/' ) {
1414 # / at end means we don't want the slash to be shown
1416 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1417 if ( $trailingSlashes ) {
1418 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1420 $noslash = substr( $target, 1 );
1423 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1424 if ( $text === '' ) {
1425 $text = $target . $suffix;
1426 } # this might be changed for ugliness reasons
1428 # check for .. subpage backlinks
1430 $nodotdot = $target;
1431 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1433 $nodotdot = substr( $nodotdot, 3 );
1435 if ( $dotdotcount > 0 ) {
1436 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1437 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1438 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1439 # / at the end means don't show full path
1440 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1441 $nodotdot = substr( $nodotdot, 0, -1 );
1442 if ( $text === '' ) {
1443 $text = $nodotdot . $suffix;
1446 $nodotdot = trim( $nodotdot );
1447 if ( $nodotdot != '' ) {
1448 $ret .= '/' . $nodotdot;
1456 wfProfileOut( __METHOD__
);
1461 * Wrap a comment in standard punctuation and formatting if
1462 * it's non-empty, otherwise return empty string.
1464 * @param $comment String
1465 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1466 * @param $local Boolean: whether section links should refer to local page
1470 public static function commentBlock( $comment, $title = null, $local = false ) {
1471 // '*' used to be the comment inserted by the software way back
1472 // in antiquity in case none was provided, here for backwards
1473 // compatability, acc. to brion -ævar
1474 if ( $comment == '' ||
$comment == '*' ) {
1477 $formatted = self
::formatComment( $comment, $title, $local );
1478 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1479 return " <span class=\"comment\">$formatted</span>";
1484 * Wrap and format the given revision's comment block, if the current
1485 * user is allowed to view it.
1487 * @param $rev Revision object
1488 * @param $local Boolean: whether section links should refer to local page
1489 * @param $isPublic Boolean: show only if all users can see it
1490 * @return String: HTML fragment
1492 public static function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1493 if ( $rev->getRawComment() == "" ) {
1496 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1497 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1498 } elseif ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1499 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1500 $rev->getTitle(), $local );
1502 $block = " <span class=\"comment\">" . wfMsgHtml( 'rev-deleted-comment' ) . "</span>";
1504 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1505 return " <span class=\"history-deleted\">$block</span>";
1514 public static function formatRevisionSize( $size ) {
1516 $stxt = wfMsgExt( 'historyempty', 'parsemag' );
1519 $stxt = wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $size ) );
1520 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1522 $stxt = htmlspecialchars( $stxt );
1523 return "<span class=\"history-size\">$stxt</span>";
1527 * Add another level to the Table of Contents
1531 public static function tocIndent() {
1536 * Finish one or more sublevels on the Table of Contents
1540 public static function tocUnindent( $level ) {
1541 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1545 * parameter level defines if we are on an indentation level
1549 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1550 $classes = "toclevel-$level";
1551 if ( $sectionIndex !== false ) {
1552 $classes .= " tocsection-$sectionIndex";
1554 return "\n<li class=\"$classes\"><a href=\"#" .
1555 $anchor . '"><span class="tocnumber">' .
1556 $tocnumber . '</span> <span class="toctext">' .
1557 $tocline . '</span></a>';
1561 * End a Table Of Contents line.
1562 * tocUnindent() will be used instead if we're ending a line below
1566 public static function tocLineEnd() {
1571 * Wraps the TOC in a table and provides the hide/collapse javascript.
1573 * @param $toc String: html of the Table Of Contents
1574 * @param $lang mixed: Language code for the toc title
1575 * @return String: full html of the TOC
1577 public static function tocList( $toc, $lang = false ) {
1578 $title = wfMsgExt( 'toc', array( 'language' => $lang, 'escape' ) );
1580 '<table id="toc" class="toc"><tr><td>'
1581 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1583 . "</ul>\n</td></tr></table>\n";
1587 * Generate a table of contents from a section tree
1590 * @param $tree array Return value of ParserOutput::getSections()
1591 * @return String: HTML fragment
1593 public static function generateTOC( $tree ) {
1596 foreach ( $tree as $section ) {
1597 if ( $section['toclevel'] > $lastLevel )
1598 $toc .= self
::tocIndent();
1599 elseif ( $section['toclevel'] < $lastLevel )
1600 $toc .= self
::tocUnindent(
1601 $lastLevel - $section['toclevel'] );
1603 $toc .= self
::tocLineEnd();
1605 $toc .= self
::tocLine( $section['anchor'],
1606 $section['line'], $section['number'],
1607 $section['toclevel'], $section['index'] );
1608 $lastLevel = $section['toclevel'];
1610 $toc .= self
::tocLineEnd();
1611 return self
::tocList( $toc );
1615 * Create a headline for content
1617 * @param $level Integer: the level of the headline (1-6)
1618 * @param $attribs String: any attributes for the headline, starting with
1619 * a space and ending with '>'
1620 * This *must* be at least '>' for no attribs
1621 * @param $anchor String: the anchor to give the headline (the bit after the #)
1622 * @param $html String: html for the text of the header
1623 * @param $link String: HTML to add for the section edit link
1624 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1625 * backward compatibility (false to omit)
1627 * @return String: HTML headline
1629 public static function makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor = false ) {
1630 $ret = "<h$level$attribs"
1632 . " <span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1634 if ( $legacyAnchor !== false ) {
1635 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1641 * Split a link trail, return the "inside" portion and the remainder of the trail
1642 * as a two-element array
1645 static function splitTrail( $trail ) {
1647 $regex = $wgContLang->linkTrail();
1649 if ( $trail !== '' ) {
1651 if ( preg_match( $regex, $trail, $m ) ) {
1656 return array( $inside, $trail );
1660 * Generate a rollback link for a given revision. Currently it's the
1661 * caller's responsibility to ensure that the revision is the top one. If
1662 * it's not, of course, the user will get an error message.
1664 * If the calling page is called with the parameter &bot=1, all rollback
1665 * links also get that parameter. It causes the edit itself and the rollback
1666 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1667 * changes, so this allows sysops to combat a busy vandal without bothering
1670 * @param $rev Revision object
1671 * @param $context IContextSource context to use or null for the main context.
1674 public static function generateRollback( $rev, IContextSource
$context = null ) {
1675 if ( $context === null ) {
1676 $context = RequestContext
::getMain();
1679 return '<span class="mw-rollback-link">'
1680 . $context->msg( 'brackets' )->rawParams(
1681 self
::buildRollbackLink( $rev, $context ) )->plain()
1686 * Build a raw rollback link, useful for collections of "tool" links
1688 * @param $rev Revision object
1689 * @param $context IContextSource context to use or null for the main context.
1690 * @return String: HTML fragment
1692 public static function buildRollbackLink( $rev, IContextSource
$context = null ) {
1693 global $wgShowRollbackEditCount, $wgMiserMode;
1695 // To config which pages are effected by miser mode
1696 $disableRollbackEditCountSpecialPage = array( 'Recentchanges', 'Watchlist' );
1698 if ( $context === null ) {
1699 $context = RequestContext
::getMain();
1702 $title = $rev->getTitle();
1704 'action' => 'rollback',
1705 'from' => $rev->getUserText(),
1706 'token' => $context->getUser()->getEditToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1708 if ( $context->getRequest()->getBool( 'bot' ) ) {
1709 $query['bot'] = '1';
1710 $query['hidediff'] = '1'; // bug 15999
1713 $disableRollbackEditCount = false;
1714 if( $wgMiserMode ) {
1715 foreach( $disableRollbackEditCountSpecialPage as $specialPage ) {
1716 if( $context->getTitle()->isSpecial( $specialPage ) ) {
1717 $disableRollbackEditCount = true;
1723 if( !$disableRollbackEditCount && is_int( $wgShowRollbackEditCount ) && $wgShowRollbackEditCount > 0 ) {
1724 $dbr = wfGetDB( DB_SLAVE
);
1726 // Up to the value of $wgShowRollbackEditCount revisions are counted
1727 $res = $dbr->select( 'revision',
1728 array( 'rev_id', 'rev_user_text' ),
1729 // $rev->getPage() returns null sometimes
1730 array( 'rev_page' => $rev->getTitle()->getArticleID() ),
1732 array( 'USE INDEX' => 'page_timestamp',
1733 'ORDER BY' => 'rev_timestamp DESC',
1734 'LIMIT' => $wgShowRollbackEditCount +
1 )
1738 while( $row = $dbr->fetchObject( $res ) ) {
1739 if( $rev->getUserText() != $row->rev_user_text
) {
1745 if( $editCount > $wgShowRollbackEditCount ) {
1746 $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )->numParams( $wgShowRollbackEditCount )->parse();
1748 $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1754 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1756 array( 'known', 'noclasses' )
1761 $context->msg( 'rollbacklink' )->escaped(),
1762 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1764 array( 'known', 'noclasses' )
1770 * Returns HTML for the "templates used on this page" list.
1772 * @param $templates Array of templates from Article::getUsedTemplate
1774 * @param $preview Boolean: whether this is for a preview
1775 * @param $section Boolean: whether this is for a section edit
1776 * @return String: HTML output
1778 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1779 wfProfileIn( __METHOD__
);
1782 if ( count( $templates ) > 0 ) {
1783 # Do a batch existence check
1784 $batch = new LinkBatch
;
1785 foreach ( $templates as $title ) {
1786 $batch->addObj( $title );
1790 # Construct the HTML
1791 $outText = '<div class="mw-templatesUsedExplanation">';
1793 $outText .= wfMsgExt( 'templatesusedpreview', array( 'parse' ), count( $templates ) );
1794 } elseif ( $section ) {
1795 $outText .= wfMsgExt( 'templatesusedsection', array( 'parse' ), count( $templates ) );
1797 $outText .= wfMsgExt( 'templatesused', array( 'parse' ), count( $templates ) );
1799 $outText .= "</div><ul>\n";
1801 usort( $templates, 'Title::compare' );
1802 foreach ( $templates as $titleObj ) {
1803 $r = $titleObj->getRestrictions( 'edit' );
1804 if ( in_array( 'sysop', $r ) ) {
1805 $protected = wfMsgExt( 'template-protected', array( 'parseinline' ) );
1806 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1807 $protected = wfMsgExt( 'template-semiprotected', array( 'parseinline' ) );
1811 if ( $titleObj->quickUserCan( 'edit' ) ) {
1812 $editLink = self
::link(
1814 wfMsg( 'editlink' ),
1816 array( 'action' => 'edit' )
1819 $editLink = self
::link(
1821 wfMsg( 'viewsourcelink' ),
1823 array( 'action' => 'edit' )
1826 $outText .= '<li>' . self
::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1828 $outText .= '</ul>';
1830 wfProfileOut( __METHOD__
);
1835 * Returns HTML for the "hidden categories on this page" list.
1837 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1839 * @return String: HTML output
1841 public static function formatHiddenCategories( $hiddencats ) {
1843 wfProfileIn( __METHOD__
);
1846 if ( count( $hiddencats ) > 0 ) {
1847 # Construct the HTML
1848 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1849 $outText .= wfMsgExt( 'hiddencategories', array( 'parse' ), $wgLang->formatnum( count( $hiddencats ) ) );
1850 $outText .= "</div><ul>\n";
1852 foreach ( $hiddencats as $titleObj ) {
1853 $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
1855 $outText .= '</ul>';
1857 wfProfileOut( __METHOD__
);
1862 * Format a size in bytes for output, using an appropriate
1863 * unit (B, KB, MB or GB) according to the magnitude in question
1865 * @param $size int Size to format
1868 public static function formatSize( $size ) {
1870 return htmlspecialchars( $wgLang->formatSize( $size ) );
1874 * Given the id of an interface element, constructs the appropriate title
1875 * attribute from the system messages. (Note, this is usually the id but
1876 * isn't always, because sometimes the accesskey needs to go on a different
1877 * element than the id, for reverse-compatibility, etc.)
1879 * @param $name String: id of the element, minus prefixes.
1880 * @param $options Mixed: null or the string 'withaccess' to add an access-
1882 * @return String: contents of the title attribute (which you must HTML-
1883 * escape), or false for no title attribute
1885 public static function titleAttrib( $name, $options = null ) {
1886 wfProfileIn( __METHOD__
);
1888 $message = wfMessage( "tooltip-$name" );
1890 if ( !$message->exists() ) {
1893 $tooltip = $message->text();
1894 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1895 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1896 # Message equal to '-' means suppress it.
1897 if ( $tooltip == '-' ) {
1902 if ( $options == 'withaccess' ) {
1903 $accesskey = self
::accesskey( $name );
1904 if ( $accesskey !== false ) {
1905 if ( $tooltip === false ||
$tooltip === '' ) {
1906 $tooltip = "[$accesskey]";
1908 $tooltip .= " [$accesskey]";
1913 wfProfileOut( __METHOD__
);
1917 static $accesskeycache;
1920 * Given the id of an interface element, constructs the appropriate
1921 * accesskey attribute from the system messages. (Note, this is usually
1922 * the id but isn't always, because sometimes the accesskey needs to go on
1923 * a different element than the id, for reverse-compatibility, etc.)
1925 * @param $name String: id of the element, minus prefixes.
1926 * @return String: contents of the accesskey attribute (which you must HTML-
1927 * escape), or false for no accesskey attribute
1929 public static function accesskey( $name ) {
1930 if ( isset( self
::$accesskeycache[$name] ) ) {
1931 return self
::$accesskeycache[$name];
1933 wfProfileIn( __METHOD__
);
1935 $message = wfMessage( "accesskey-$name" );
1937 if ( !$message->exists() ) {
1940 $accesskey = $message->plain();
1941 if ( $accesskey === '' ||
$accesskey === '-' ) {
1942 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
1943 # attribute, but this is broken for accesskey: that might be a useful
1949 wfProfileOut( __METHOD__
);
1950 return self
::$accesskeycache[$name] = $accesskey;
1954 * Get a revision-deletion link, or disabled link, or nothing, depending
1955 * on user permissions & the settings on the revision.
1957 * Will use forward-compatible revision ID in the Special:RevDelete link
1958 * if possible, otherwise the timestamp-based ID which may break after
1962 * @param Revision $rev
1963 * @param Revision $title
1964 * @return string HTML fragment
1966 public static function getRevDeleteLink( User
$user, Revision
$rev, Title
$title ) {
1967 $canHide = $user->isAllowed( 'deleterevision' );
1968 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
1972 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
1973 return Linker
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
1975 if ( $rev->getId() ) {
1976 // RevDelete links using revision ID are stable across
1977 // page deletion and undeletion; use when possible.
1979 'type' => 'revision',
1980 'target' => $title->getPrefixedDBkey(),
1981 'ids' => $rev->getId()
1984 // Older deleted entries didn't save a revision ID.
1985 // We have to refer to these by timestamp, ick!
1987 'type' => 'archive',
1988 'target' => $title->getPrefixedDBkey(),
1989 'ids' => $rev->getTimestamp()
1992 return Linker
::revDeleteLink( $query,
1993 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
1998 * Creates a (show/hide) link for deleting revisions/log entries
2000 * @param $query Array: query parameters to be passed to link()
2001 * @param $restricted Boolean: set to true to use a "<strong>" instead of a "<span>"
2002 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2004 * @return String: HTML "<a>" link to Special:Revisiondelete, wrapped in a
2005 * span to allow for customization of appearance with CSS
2007 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
2008 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
2009 $html = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
2010 $tag = $restricted ?
'strong' : 'span';
2011 $link = self
::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
2012 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $link )->escaped() );
2016 * Creates a dead (show/hide) link for deleting revisions/log entries
2018 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2020 * @return string HTML text wrapped in a span to allow for customization
2021 * of appearance with CSS
2023 public static function revDeleteLinkDisabled( $delete = true ) {
2024 $html = $delete ?
wfMsgHtml( 'rev-delundel' ) : wfMsgHtml( 'rev-showdeleted' );
2025 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $html )->escaped() );
2028 /* Deprecated methods */
2031 * @deprecated since 1.16 Use link()
2033 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
2034 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
2036 * @param $title String: The text of the title
2037 * @param $text String: Link text
2038 * @param $query String: Optional query part
2039 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
2040 * be included in the link text. Other characters will be appended after
2041 * the end of the link.
2044 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
2045 wfDeprecated( __METHOD__
, '1.16' );
2047 $nt = Title
::newFromText( $title );
2048 if ( $nt instanceof Title
) {
2049 return self
::makeBrokenLinkObj( $nt, $text, $query, $trail );
2051 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
2052 return $text == '' ?
$title : $text;
2057 * @deprecated since 1.16 Use link()
2059 * Make a link for a title which may or may not be in the database. If you need to
2060 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
2061 * call to this will result in a DB query.
2063 * @param $nt Title: the title object to make the link from, e.g. from
2064 * Title::newFromText.
2065 * @param $text String: link text
2066 * @param $query String: optional query part
2067 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2068 * be included in the link text. Other characters will be appended after
2069 * the end of the link.
2070 * @param $prefix String: optional prefix. As trail, only before instead of after.
2073 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
2074 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
2076 wfProfileIn( __METHOD__
);
2077 $query = wfCgiToArray( $query );
2078 list( $inside, $trail ) = self
::splitTrail( $trail );
2079 if ( $text === '' ) {
2080 $text = self
::linkText( $nt );
2083 $ret = self
::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
2085 wfProfileOut( __METHOD__
);
2090 * @deprecated since 1.16 Use link()
2092 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
2093 * it doesn't have to do a database query. It's also valid for interwiki titles and special
2096 * @param $title Title object of target page
2097 * @param $text String: text to replace the title
2098 * @param $query String: link target
2099 * @param $trail String: text after link
2100 * @param $prefix String: text before link text
2101 * @param $aprops String: extra attributes to the a-element
2102 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
2103 * @return string the a-element
2105 static function makeKnownLinkObj(
2106 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
2108 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
2110 wfProfileIn( __METHOD__
);
2112 if ( $text == '' ) {
2113 $text = self
::linkText( $title );
2115 $attribs = Sanitizer
::mergeAttributes(
2116 Sanitizer
::decodeTagAttributes( $aprops ),
2117 Sanitizer
::decodeTagAttributes( $style )
2119 $query = wfCgiToArray( $query );
2120 list( $inside, $trail ) = self
::splitTrail( $trail );
2122 $ret = self
::link( $title, "$prefix$text$inside", $attribs, $query,
2123 array( 'known', 'noclasses' ) ) . $trail;
2125 wfProfileOut( __METHOD__
);
2130 * @deprecated since 1.16 Use link()
2132 * Make a red link to the edit page of a given title.
2134 * @param $title Title object of the target page
2135 * @param $text String: Link text
2136 * @param $query String: Optional query part
2137 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
2138 * be included in the link text. Other characters will be appended after
2139 * the end of the link.
2140 * @param $prefix String: Optional prefix
2143 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
2144 wfDeprecated( __METHOD__
, '1.16' );
2146 wfProfileIn( __METHOD__
);
2148 list( $inside, $trail ) = self
::splitTrail( $trail );
2149 if ( $text === '' ) {
2150 $text = self
::linkText( $title );
2153 $ret = self
::link( $title, "$prefix$text$inside", array(),
2154 wfCgiToArray( $query ), 'broken' ) . $trail;
2156 wfProfileOut( __METHOD__
);
2161 * @deprecated since 1.16 Use link()
2163 * Make a coloured link.
2165 * @param $nt Title object of the target page
2166 * @param $colour Integer: colour of the link
2167 * @param $text String: link text
2168 * @param $query String: optional query part
2169 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2170 * be included in the link text. Other characters will be appended after
2171 * the end of the link.
2172 * @param $prefix String: Optional prefix
2175 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2176 wfDeprecated( __METHOD__
, '1.16' );
2178 if ( $colour != '' ) {
2179 $style = self
::getInternalLinkAttributesObj( $nt, $text, $colour );
2183 return self
::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2187 * Returns the attributes for the tooltip and access key.
2190 public static function tooltipAndAccesskeyAttribs( $name ) {
2191 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2192 # no attribute" instead of "output '' as value for attribute", this
2193 # would be three lines.
2195 'title' => self
::titleAttrib( $name, 'withaccess' ),
2196 'accesskey' => self
::accesskey( $name )
2198 if ( $attribs['title'] === false ) {
2199 unset( $attribs['title'] );
2201 if ( $attribs['accesskey'] === false ) {
2202 unset( $attribs['accesskey'] );
2208 * Returns raw bits of HTML, use titleAttrib()
2209 * @return null|string
2211 public static function tooltip( $name, $options = null ) {
2212 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2213 # no attribute" instead of "output '' as value for attribute", this
2214 # would be two lines.
2215 $tooltip = self
::titleAttrib( $name, $options );
2216 if ( $tooltip === false ) {
2219 return Xml
::expandAttributes( array(
2231 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2232 * into static calls to the new Linker for backwards compatibility.
2234 * @param $fname String Name of called method
2235 * @param $args Array Arguments to the method
2238 public function __call( $fname, $args ) {
2239 return call_user_func_array( array( 'Linker', $fname ), $args );