When serializing Message, don't try to unstub StubUserLang
[mediawiki.git] / includes / Linker.php
blob0dd4c478fe343ef892ece554c2cf70bd62a07174
1 <?php
2 /**
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
20 * @file
23 /**
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.
28 * @todo turn this into a legacy interface for HtmlPageLinkRenderer and similar services.
30 * @ingroup Skins
32 class Linker {
33 /**
34 * Flags for userToolLinks()
36 const TOOL_LINKS_NOBLOCK = 1;
37 const TOOL_LINKS_EMAIL = 2;
39 /**
40 * Get the appropriate HTML attributes to add to the "a" element of an interwiki link.
42 * @deprecated since 1.25
44 * @param string $title The title text for the link, URL-encoded (???) but
45 * not HTML-escaped
46 * @param string $unused Unused
47 * @param string $class The contents of the class attribute; if an empty
48 * string is passed, which is the default value, defaults to 'external'.
49 * @return string
51 static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
52 global $wgContLang;
54 wfDeprecated( __METHOD__, '1.25' );
56 # @todo FIXME: We have a whole bunch of handling here that doesn't happen in
57 # getExternalLinkAttributes, why?
58 $title = urldecode( $title );
59 $title = $wgContLang->checkTitleEncoding( $title );
60 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
62 return self::getLinkAttributesInternal( $title, $class );
65 /**
66 * Get the appropriate HTML attributes to add to the "a" element of an internal link.
68 * @deprecated since 1.25
70 * @param string $title The title text for the link, URL-encoded (???) but
71 * not HTML-escaped
72 * @param string $unused Unused
73 * @param string $class The contents of the class attribute, default none
74 * @return string
76 static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
77 wfDeprecated( __METHOD__, '1.25' );
79 $title = urldecode( $title );
80 $title = strtr( $title, '_', ' ' );
81 return self::getLinkAttributesInternal( $title, $class );
84 /**
85 * Get the appropriate HTML attributes to add to the "a" element of an internal
86 * link, given the Title object for the page we want to link to.
88 * @deprecated since 1.25
90 * @param Title $nt
91 * @param string $unused Unused
92 * @param string $class The contents of the class attribute, default none
93 * @param string|bool $title Optional (unescaped) string to use in the title
94 * attribute; if false, default to the name of the page we're linking to
95 * @return string
97 static function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
98 wfDeprecated( __METHOD__, '1.25' );
100 if ( $title === false ) {
101 $title = $nt->getPrefixedText();
103 return self::getLinkAttributesInternal( $title, $class );
107 * Common code for getLinkAttributesX functions
109 * @deprecated since 1.25
111 * @param string $title
112 * @param string $class
114 * @return string
116 private static function getLinkAttributesInternal( $title, $class ) {
117 wfDeprecated( __METHOD__, '1.25' );
119 $title = htmlspecialchars( $title );
120 $class = htmlspecialchars( $class );
121 $r = '';
122 if ( $class != '' ) {
123 $r .= " class=\"$class\"";
125 if ( $title != '' ) {
126 $r .= " title=\"$title\"";
128 return $r;
132 * Return the CSS colour of a known link
134 * @param Title $t
135 * @param int $threshold User defined threshold
136 * @return string CSS class
138 public static function getLinkColour( $t, $threshold ) {
139 $colour = '';
140 if ( $t->isRedirect() ) {
141 # Page is a redirect
142 $colour = 'mw-redirect';
143 } elseif ( $threshold > 0 && $t->isContentPage() &&
144 $t->exists() && $t->getLength() < $threshold
146 # Page is a stub
147 $colour = 'stub';
149 return $colour;
153 * This function returns an HTML link to the given target. It serves a few
154 * purposes:
155 * 1) If $target is a Title, the correct URL to link to will be figured
156 * out automatically.
157 * 2) It automatically adds the usual classes for various types of link
158 * targets: "new" for red links, "stub" for short articles, etc.
159 * 3) It escapes all attribute values safely so there's no risk of XSS.
160 * 4) It provides a default tooltip if the target is a Title (the page
161 * name of the target).
162 * link() replaces the old functions in the makeLink() family.
164 * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
166 * @param Title $target Can currently only be a Title, but this may
167 * change to support Images, literal URLs, etc.
168 * @param string $html The HTML contents of the <a> element, i.e.,
169 * the link text. This is raw HTML and will not be escaped. If null,
170 * defaults to the prefixed text of the Title; or if the Title is just a
171 * fragment, the contents of the fragment.
172 * @param array $customAttribs A key => value array of extra HTML attributes,
173 * such as title and class. (href is ignored.) Classes will be
174 * merged with the default classes, while other attributes will replace
175 * default attributes. All passed attribute values will be HTML-escaped.
176 * A false attribute value means to suppress that attribute.
177 * @param array $query The query string to append to the URL
178 * you're linking to, in key => value array form. Query keys and values
179 * will be URL-encoded.
180 * @param string|array $options String or array of strings:
181 * 'known': Page is known to exist, so don't check if it does.
182 * 'broken': Page is known not to exist, so don't check if it does.
183 * 'noclasses': Don't add any classes automatically (includes "new",
184 * "stub", "mw-redirect", "extiw"). Only use the class attribute
185 * provided, if any, so you get a simple blue link with no funny i-
186 * cons.
187 * 'forcearticlepath': Use the article path always, even with a querystring.
188 * Has compatibility issues on some setups, so avoid wherever possible.
189 * 'http': Force a full URL with http:// as the scheme.
190 * 'https': Force a full URL with https:// as the scheme.
191 * @return string HTML <a> attribute
193 public static function link(
194 $target, $html = null, $customAttribs = array(), $query = array(), $options = array()
196 if ( !$target instanceof Title ) {
197 wfWarn( __METHOD__ . ': Requires $target to be a Title object.', 2 );
198 return "<!-- ERROR -->$html";
201 if ( is_string( $query ) ) {
202 // some functions withing core using this still hand over query strings
203 wfDeprecated( __METHOD__ . ' with parameter $query as string (should be array)', '1.20' );
204 $query = wfCgiToArray( $query );
206 $options = (array)$options;
208 $dummy = new DummyLinker; // dummy linker instance for bc on the hooks
210 $ret = null;
211 if ( !Hooks::run( 'LinkBegin',
212 array( $dummy, $target, &$html, &$customAttribs, &$query, &$options, &$ret ) )
214 return $ret;
217 # Normalize the Title if it's a special page
218 $target = self::normaliseSpecialPage( $target );
220 # If we don't know whether the page exists, let's find out.
221 if ( !in_array( 'known', $options ) && !in_array( 'broken', $options ) ) {
222 if ( $target->isKnown() ) {
223 $options[] = 'known';
224 } else {
225 $options[] = 'broken';
229 $oldquery = array();
230 if ( in_array( "forcearticlepath", $options ) && $query ) {
231 $oldquery = $query;
232 $query = array();
235 # Note: we want the href attribute first, for prettiness.
236 $attribs = array( 'href' => self::linkUrl( $target, $query, $options ) );
237 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
238 $attribs['href'] = wfAppendQuery( $attribs['href'], $oldquery );
241 $attribs = array_merge(
242 $attribs,
243 self::linkAttribs( $target, $customAttribs, $options )
245 if ( is_null( $html ) ) {
246 $html = self::linkText( $target );
249 $ret = null;
250 if ( Hooks::run( 'LinkEnd', array( $dummy, $target, $options, &$html, &$attribs, &$ret ) ) ) {
251 $ret = Html::rawElement( 'a', $attribs, $html );
254 return $ret;
258 * Identical to link(), except $options defaults to 'known'.
259 * @see Linker::link
260 * @return string
262 public static function linkKnown(
263 $target, $html = null, $customAttribs = array(),
264 $query = array(), $options = array( 'known', 'noclasses' )
266 return self::link( $target, $html, $customAttribs, $query, $options );
270 * Returns the Url used to link to a Title
272 * @param Title $target
273 * @param array $query Query parameters
274 * @param array $options
275 * @return string
277 private static function linkUrl( $target, $query, $options ) {
278 # We don't want to include fragments for broken links, because they
279 # generally make no sense.
280 if ( in_array( 'broken', $options ) && $target->hasFragment() ) {
281 $target = clone $target;
282 $target->setFragment( '' );
285 # If it's a broken link, add the appropriate query pieces, unless
286 # there's already an action specified, or unless 'edit' makes no sense
287 # (i.e., for a nonexistent special page).
288 if ( in_array( 'broken', $options ) && empty( $query['action'] )
289 && !$target->isSpecialPage() ) {
290 $query['action'] = 'edit';
291 $query['redlink'] = '1';
294 if ( in_array( 'http', $options ) ) {
295 $proto = PROTO_HTTP;
296 } elseif ( in_array( 'https', $options ) ) {
297 $proto = PROTO_HTTPS;
298 } else {
299 $proto = PROTO_RELATIVE;
302 $ret = $target->getLinkURL( $query, false, $proto );
303 return $ret;
307 * Returns the array of attributes used when linking to the Title $target
309 * @param Title $target
310 * @param array $attribs
311 * @param array $options
313 * @return array
315 private static function linkAttribs( $target, $attribs, $options ) {
316 global $wgUser;
317 $defaults = array();
319 if ( !in_array( 'noclasses', $options ) ) {
320 # Now build the classes.
321 $classes = array();
323 if ( in_array( 'broken', $options ) ) {
324 $classes[] = 'new';
327 if ( $target->isExternal() ) {
328 $classes[] = 'extiw';
331 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
332 $colour = self::getLinkColour( $target, $wgUser->getStubThreshold() );
333 if ( $colour !== '' ) {
334 $classes[] = $colour; # mw-redirect or stub
337 if ( $classes != array() ) {
338 $defaults['class'] = implode( ' ', $classes );
342 # Get a default title attribute.
343 if ( $target->getPrefixedText() == '' ) {
344 # A link like [[#Foo]]. This used to mean an empty title
345 # attribute, but that's silly. Just don't output a title.
346 } elseif ( in_array( 'known', $options ) ) {
347 $defaults['title'] = $target->getPrefixedText();
348 } else {
349 $defaults['title'] = wfMessage( 'red-link-title', $target->getPrefixedText() )->text();
352 # Finally, merge the custom attribs with the default ones, and iterate
353 # over that, deleting all "false" attributes.
354 $ret = array();
355 $merged = Sanitizer::mergeAttributes( $defaults, $attribs );
356 foreach ( $merged as $key => $val ) {
357 # A false value suppresses the attribute, and we don't want the
358 # href attribute to be overridden.
359 if ( $key != 'href' && $val !== false ) {
360 $ret[$key] = $val;
363 return $ret;
367 * Default text of the links to the Title $target
369 * @param Title $target
371 * @return string
373 private static function linkText( $target ) {
374 if ( !$target instanceof Title ) {
375 wfWarn( __METHOD__ . ': Requires $target to be a Title object.' );
376 return '';
378 // If the target is just a fragment, with no title, we return the fragment
379 // text. Otherwise, we return the title text itself.
380 if ( $target->getPrefixedText() === '' && $target->hasFragment() ) {
381 return htmlspecialchars( $target->getFragment() );
384 return htmlspecialchars( $target->getPrefixedText() );
388 * Make appropriate markup for a link to the current article. This is
389 * currently rendered as the bold link text. The calling sequence is the
390 * same as the other make*LinkObj static functions, despite $query not
391 * being used.
393 * @param Title $nt
394 * @param string $html [optional]
395 * @param string $query [optional]
396 * @param string $trail [optional]
397 * @param string $prefix [optional]
399 * @return string
401 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
402 $ret = "<strong class=\"selflink\">{$prefix}{$html}</strong>{$trail}";
403 if ( !Hooks::run( 'SelfLinkBegin', array( $nt, &$html, &$trail, &$prefix, &$ret ) ) ) {
404 return $ret;
407 if ( $html == '' ) {
408 $html = htmlspecialchars( $nt->getPrefixedText() );
410 list( $inside, $trail ) = self::splitTrail( $trail );
411 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
415 * Get a message saying that an invalid title was encountered.
416 * This should be called after a method like Title::makeTitleSafe() returned
417 * a value indicating that the title object is invalid.
419 * @param IContextSource $context Context to use to get the messages
420 * @param int $namespace Namespace number
421 * @param string $title Text of the title, without the namespace part
422 * @return string
424 public static function getInvalidTitleDescription( IContextSource $context, $namespace, $title ) {
425 global $wgContLang;
427 // First we check whether the namespace exists or not.
428 if ( MWNamespace::exists( $namespace ) ) {
429 if ( $namespace == NS_MAIN ) {
430 $name = $context->msg( 'blanknamespace' )->text();
431 } else {
432 $name = $wgContLang->getFormattedNsText( $namespace );
434 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
435 } else {
436 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
441 * @param Title $title
442 * @return Title
444 static function normaliseSpecialPage( Title $title ) {
445 if ( $title->isSpecialPage() ) {
446 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
447 if ( !$name ) {
448 return $title;
450 $ret = SpecialPage::getTitleFor( $name, $subpage, $title->getFragment() );
451 return $ret;
452 } else {
453 return $title;
458 * Returns the filename part of an url.
459 * Used as alternative text for external images.
461 * @param string $url
463 * @return string
465 private static function fnamePart( $url ) {
466 $basename = strrchr( $url, '/' );
467 if ( false === $basename ) {
468 $basename = $url;
469 } else {
470 $basename = substr( $basename, 1 );
472 return $basename;
476 * Return the code for images which were added via external links,
477 * via Parser::maybeMakeExternalImage().
479 * @param string $url
480 * @param string $alt
482 * @return string
484 public static function makeExternalImage( $url, $alt = '' ) {
485 if ( $alt == '' ) {
486 $alt = self::fnamePart( $url );
488 $img = '';
489 $success = Hooks::run( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
490 if ( !$success ) {
491 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
492 . "with url {$url} and alt text {$alt} to {$img}\n", true );
493 return $img;
495 return Html::element( 'img',
496 array(
497 'src' => $url,
498 'alt' => $alt ) );
502 * Given parameters derived from [[Image:Foo|options...]], generate the
503 * HTML that that syntax inserts in the page.
505 * @param Parser $parser
506 * @param Title $title Title object of the file (not the currently viewed page)
507 * @param File $file File object, or false if it doesn't exist
508 * @param array $frameParams Associative array of parameters external to the media handler.
509 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
510 * will often be false.
511 * thumbnail If present, downscale and frame
512 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
513 * framed Shows image in original size in a frame
514 * frameless Downscale but don't frame
515 * upright If present, tweak default sizes for portrait orientation
516 * upright_factor Fudge factor for "upright" tweak (default 0.75)
517 * border If present, show a border around the image
518 * align Horizontal alignment (left, right, center, none)
519 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
520 * bottom, text-bottom)
521 * alt Alternate text for image (i.e. alt attribute). Plain text.
522 * class HTML for image classes. Plain text.
523 * caption HTML for image caption.
524 * link-url URL to link to
525 * link-title Title object to link to
526 * link-target Value for the target attribute, only with link-url
527 * no-link Boolean, suppress description link
529 * @param array $handlerParams Associative array of media handler parameters, to be passed
530 * to transform(). Typical keys are "width" and "page".
531 * @param string|bool $time Timestamp of the file, set as false for current
532 * @param string $query Query params for desc url
533 * @param int|null $widthOption Used by the parser to remember the user preference thumbnailsize
534 * @since 1.20
535 * @return string HTML for an image, with links, wrappers, etc.
537 public static function makeImageLink( Parser $parser, Title $title,
538 $file, $frameParams = array(), $handlerParams = array(), $time = false,
539 $query = "", $widthOption = null
541 $res = null;
542 $dummy = new DummyLinker;
543 if ( !Hooks::run( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
544 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
545 return $res;
548 if ( $file && !$file->allowInlineDisplay() ) {
549 wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
550 return self::link( $title );
553 // Shortcuts
554 $fp =& $frameParams;
555 $hp =& $handlerParams;
557 // Clean up parameters
558 $page = isset( $hp['page'] ) ? $hp['page'] : false;
559 if ( !isset( $fp['align'] ) ) {
560 $fp['align'] = '';
562 if ( !isset( $fp['alt'] ) ) {
563 $fp['alt'] = '';
565 if ( !isset( $fp['title'] ) ) {
566 $fp['title'] = '';
568 if ( !isset( $fp['class'] ) ) {
569 $fp['class'] = '';
572 $prefix = $postfix = '';
574 if ( 'center' == $fp['align'] ) {
575 $prefix = '<div class="center">';
576 $postfix = '</div>';
577 $fp['align'] = 'none';
579 if ( $file && !isset( $hp['width'] ) ) {
580 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
581 // If its a vector image, and user only specifies height
582 // we don't want it to be limited by its "normal" width.
583 global $wgSVGMaxSize;
584 $hp['width'] = $wgSVGMaxSize;
585 } else {
586 $hp['width'] = $file->getWidth( $page );
589 if ( isset( $fp['thumbnail'] )
590 || isset( $fp['manualthumb'] )
591 || isset( $fp['framed'] )
592 || isset( $fp['frameless'] )
593 || !$hp['width']
595 global $wgThumbLimits, $wgThumbUpright;
597 if ( $widthOption === null || !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;
606 // For caching health: If width scaled down due to upright
607 // parameter, round to full __0 pixel to avoid the creation of a
608 // lot of odd thumbs.
609 $prefWidth = isset( $fp['upright'] ) ?
610 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
611 $wgThumbLimits[$widthOption];
613 // Use width which is smaller: real image width or user preference width
614 // Unless image is scalable vector.
615 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
616 $prefWidth < $hp['width'] || $file->isVectorized() ) ) {
617 $hp['width'] = $prefWidth;
622 if ( isset( $fp['thumbnail'] ) || isset( $fp['manualthumb'] ) || isset( $fp['framed'] ) ) {
623 # Create a thumbnail. Alignment depends on the writing direction of
624 # the page content language (right-aligned for LTR languages,
625 # left-aligned for RTL languages)
626 # If a thumbnail width has not been provided, it is set
627 # to the default user option as specified in Language*.php
628 if ( $fp['align'] == '' ) {
629 $fp['align'] = $parser->getTargetLanguage()->alignEnd();
631 return $prefix . self::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
634 if ( $file && isset( $fp['frameless'] ) ) {
635 $srcWidth = $file->getWidth( $page );
636 # For "frameless" option: do not present an image bigger than the
637 # source (for bitmap-style images). This is the same behavior as the
638 # "thumb" option does it already.
639 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
640 $hp['width'] = $srcWidth;
644 if ( $file && isset( $hp['width'] ) ) {
645 # Create a resized image, without the additional thumbnail features
646 $thumb = $file->transform( $hp );
647 } else {
648 $thumb = false;
651 if ( !$thumb ) {
652 $s = self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
653 } else {
654 self::processResponsiveImages( $file, $thumb, $hp );
655 $params = array(
656 'alt' => $fp['alt'],
657 'title' => $fp['title'],
658 'valign' => isset( $fp['valign'] ) ? $fp['valign'] : false,
659 'img-class' => $fp['class'] );
660 if ( isset( $fp['border'] ) ) {
661 $params['img-class'] .= ( $params['img-class'] !== '' ? ' ' : '' ) . 'thumbborder';
663 $params = self::getImageLinkMTOParams( $fp, $query, $parser ) + $params;
665 $s = $thumb->toHtml( $params );
667 if ( $fp['align'] != '' ) {
668 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
670 return str_replace( "\n", ' ', $prefix . $s . $postfix );
674 * Get the link parameters for MediaTransformOutput::toHtml() from given
675 * frame parameters supplied by the Parser.
676 * @param array $frameParams The frame parameters
677 * @param string $query An optional query string to add to description page links
678 * @param Parser|null $parser
679 * @return array
681 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
682 $mtoParams = array();
683 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
684 $mtoParams['custom-url-link'] = $frameParams['link-url'];
685 if ( isset( $frameParams['link-target'] ) ) {
686 $mtoParams['custom-target-link'] = $frameParams['link-target'];
688 if ( $parser ) {
689 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
690 foreach ( $extLinkAttrs as $name => $val ) {
691 // Currently could include 'rel' and 'target'
692 $mtoParams['parser-extlink-' . $name] = $val;
695 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
696 $mtoParams['custom-title-link'] = self::normaliseSpecialPage( $frameParams['link-title'] );
697 } elseif ( !empty( $frameParams['no-link'] ) ) {
698 // No link
699 } else {
700 $mtoParams['desc-link'] = true;
701 $mtoParams['desc-query'] = $query;
703 return $mtoParams;
707 * Make HTML for a thumbnail including image, border and caption
708 * @param Title $title
709 * @param File|bool $file File object or false if it doesn't exist
710 * @param string $label
711 * @param string $alt
712 * @param string $align
713 * @param array $params
714 * @param bool $framed
715 * @param string $manualthumb
716 * @return string
718 public static function makeThumbLinkObj( Title $title, $file, $label = '', $alt,
719 $align = 'right', $params = array(), $framed = false, $manualthumb = ""
721 $frameParams = array(
722 'alt' => $alt,
723 'caption' => $label,
724 'align' => $align
726 if ( $framed ) {
727 $frameParams['framed'] = true;
729 if ( $manualthumb ) {
730 $frameParams['manualthumb'] = $manualthumb;
732 return self::makeThumbLink2( $title, $file, $frameParams, $params );
736 * @param Title $title
737 * @param File $file
738 * @param array $frameParams
739 * @param array $handlerParams
740 * @param bool $time
741 * @param string $query
742 * @return string
744 public static function makeThumbLink2( Title $title, $file, $frameParams = array(),
745 $handlerParams = array(), $time = false, $query = ""
747 $exists = $file && $file->exists();
749 # Shortcuts
750 $fp =& $frameParams;
751 $hp =& $handlerParams;
753 $page = isset( $hp['page'] ) ? $hp['page'] : false;
754 if ( !isset( $fp['align'] ) ) {
755 $fp['align'] = 'right';
757 if ( !isset( $fp['alt'] ) ) {
758 $fp['alt'] = '';
760 if ( !isset( $fp['title'] ) ) {
761 $fp['title'] = '';
763 if ( !isset( $fp['caption'] ) ) {
764 $fp['caption'] = '';
767 if ( empty( $hp['width'] ) ) {
768 // Reduce width for upright images when parameter 'upright' is used
769 $hp['width'] = isset( $fp['upright'] ) ? 130 : 180;
771 $thumb = false;
772 $noscale = false;
773 $manualthumb = false;
775 if ( !$exists ) {
776 $outerWidth = $hp['width'] + 2;
777 } else {
778 if ( isset( $fp['manualthumb'] ) ) {
779 # Use manually specified thumbnail
780 $manual_title = Title::makeTitleSafe( NS_FILE, $fp['manualthumb'] );
781 if ( $manual_title ) {
782 $manual_img = wfFindFile( $manual_title );
783 if ( $manual_img ) {
784 $thumb = $manual_img->getUnscaledThumb( $hp );
785 $manualthumb = true;
786 } else {
787 $exists = false;
790 } elseif ( isset( $fp['framed'] ) ) {
791 // Use image dimensions, don't scale
792 $thumb = $file->getUnscaledThumb( $hp );
793 $noscale = true;
794 } else {
795 # Do not present an image bigger than the source, for bitmap-style images
796 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
797 $srcWidth = $file->getWidth( $page );
798 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
799 $hp['width'] = $srcWidth;
801 $thumb = $file->transform( $hp );
804 if ( $thumb ) {
805 $outerWidth = $thumb->getWidth() + 2;
806 } else {
807 $outerWidth = $hp['width'] + 2;
811 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
812 # So we don't need to pass it here in $query. However, the URL for the
813 # zoom icon still needs it, so we make a unique query for it. See bug 14771
814 $url = $title->getLocalURL( $query );
815 if ( $page ) {
816 $url = wfAppendQuery( $url, array( 'page' => $page ) );
818 if ( $manualthumb
819 && !isset( $fp['link-title'] )
820 && !isset( $fp['link-url'] )
821 && !isset( $fp['no-link'] ) ) {
822 $fp['link-url'] = $url;
825 $s = "<div class=\"thumb t{$fp['align']}\">"
826 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
828 if ( !$exists ) {
829 $s .= self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
830 $zoomIcon = '';
831 } elseif ( !$thumb ) {
832 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
833 $zoomIcon = '';
834 } else {
835 if ( !$noscale && !$manualthumb ) {
836 self::processResponsiveImages( $file, $thumb, $hp );
838 $params = array(
839 'alt' => $fp['alt'],
840 'title' => $fp['title'],
841 'img-class' => ( isset( $fp['class'] ) && $fp['class'] !== ''
842 ? $fp['class'] . ' '
843 : '' ) . 'thumbimage'
845 $params = self::getImageLinkMTOParams( $fp, $query ) + $params;
846 $s .= $thumb->toHtml( $params );
847 if ( isset( $fp['framed'] ) ) {
848 $zoomIcon = "";
849 } else {
850 $zoomIcon = Html::rawElement( 'div', array( 'class' => 'magnify' ),
851 Html::rawElement( 'a', array(
852 'href' => $url,
853 'class' => 'internal',
854 'title' => wfMessage( 'thumbnail-more' )->text() ),
855 "" ) );
858 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
859 return str_replace( "\n", ' ', $s );
863 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
864 * applicable.
866 * @param File $file
867 * @param MediaTransformOutput $thumb
868 * @param array $hp Image parameters
870 public static function processResponsiveImages( $file, $thumb, $hp ) {
871 global $wgResponsiveImages;
872 if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
873 $hp15 = $hp;
874 $hp15['width'] = round( $hp['width'] * 1.5 );
875 $hp20 = $hp;
876 $hp20['width'] = $hp['width'] * 2;
877 if ( isset( $hp['height'] ) ) {
878 $hp15['height'] = round( $hp['height'] * 1.5 );
879 $hp20['height'] = $hp['height'] * 2;
882 $thumb15 = $file->transform( $hp15 );
883 $thumb20 = $file->transform( $hp20 );
884 if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
885 $thumb->responsiveUrls['1.5'] = $thumb15->getUrl();
887 if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
888 $thumb->responsiveUrls['2'] = $thumb20->getUrl();
894 * Make a "broken" link to an image
896 * @param Title $title
897 * @param string $label Link label (plain text)
898 * @param string $query Query string
899 * @param string $unused1 Unused parameter kept for b/c
900 * @param string $unused2 Unused parameter kept for b/c
901 * @param bool $time A file of a certain timestamp was requested
902 * @return string
904 public static function makeBrokenImageLinkObj( $title, $label = '',
905 $query = '', $unused1 = '', $unused2 = '', $time = false
907 if ( !$title instanceof Title ) {
908 wfWarn( __METHOD__ . ': Requires $title to be a Title object.' );
909 return "<!-- ERROR -->" . htmlspecialchars( $label );
912 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
913 if ( $label == '' ) {
914 $label = $title->getPrefixedText();
916 $encLabel = htmlspecialchars( $label );
917 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
919 if ( ( $wgUploadMissingFileUrl || $wgUploadNavigationUrl || $wgEnableUploads )
920 && !$currentExists
922 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
924 if ( $redir ) {
925 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
928 $href = self::getUploadUrl( $title, $query );
930 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
931 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES ) . '">' .
932 $encLabel . '</a>';
935 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
939 * Get the URL to upload a certain file
941 * @param Title $destFile Title object of the file to upload
942 * @param string $query Urlencoded query string to prepend
943 * @return string Urlencoded URL
945 protected static function getUploadUrl( $destFile, $query = '' ) {
946 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
947 $q = 'wpDestFile=' . $destFile->getPartialURL();
948 if ( $query != '' ) {
949 $q .= '&' . $query;
952 if ( $wgUploadMissingFileUrl ) {
953 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
954 } elseif ( $wgUploadNavigationUrl ) {
955 return wfAppendQuery( $wgUploadNavigationUrl, $q );
956 } else {
957 $upload = SpecialPage::getTitleFor( 'Upload' );
958 return $upload->getLocalURL( $q );
963 * Create a direct link to a given uploaded file.
965 * @param Title $title
966 * @param string $html Pre-sanitized HTML
967 * @param string $time MW timestamp of file creation time
968 * @return string HTML
970 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
971 $img = wfFindFile( $title, array( 'time' => $time ) );
972 return self::makeMediaLinkFile( $title, $img, $html );
976 * Create a direct link to a given uploaded file.
977 * This will make a broken link if $file is false.
979 * @param Title $title
980 * @param File|bool $file File object or false
981 * @param string $html Pre-sanitized HTML
982 * @return string HTML
984 * @todo Handle invalid or missing images better.
986 public static function makeMediaLinkFile( Title $title, $file, $html = '' ) {
987 if ( $file && $file->exists() ) {
988 $url = $file->getURL();
989 $class = 'internal';
990 } else {
991 $url = self::getUploadUrl( $title );
992 $class = 'new';
995 $alt = $title->getText();
996 if ( $html == '' ) {
997 $html = $alt;
1000 $ret = '';
1001 $attribs = array(
1002 'href' => $url,
1003 'class' => $class,
1004 'title' => $alt
1007 if ( !Hooks::run( 'LinkerMakeMediaLinkFile',
1008 array( $title, $file, &$html, &$attribs, &$ret ) ) ) {
1009 wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
1010 . "with url {$url} and text {$html} to {$ret}\n", true );
1011 return $ret;
1014 return Html::rawElement( 'a', $attribs, $html );
1018 * Make a link to a special page given its name and, optionally,
1019 * a message key from the link text.
1020 * Usage example: Linker::specialLink( 'Recentchanges' )
1022 * @param string $name
1023 * @param string $key
1024 * @return string
1026 public static function specialLink( $name, $key = '' ) {
1027 if ( $key == '' ) {
1028 $key = strtolower( $name );
1031 return self::linkKnown( SpecialPage::getTitleFor( $name ), wfMessage( $key )->text() );
1035 * Make an external link
1036 * @param string $url URL to link to
1037 * @param string $text Text of link
1038 * @param bool $escape Do we escape the link text?
1039 * @param string $linktype Type of external link. Gets added to the classes
1040 * @param array $attribs Array of extra attributes to <a>
1041 * @param Title|null $title Title object used for title specific link attributes
1042 * @return string
1044 public static function makeExternalLink( $url, $text, $escape = true,
1045 $linktype = '', $attribs = array(), $title = null
1047 global $wgTitle;
1048 $class = "external";
1049 if ( $linktype ) {
1050 $class .= " $linktype";
1052 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1053 $class .= " {$attribs['class']}";
1055 $attribs['class'] = $class;
1057 if ( $escape ) {
1058 $text = htmlspecialchars( $text );
1061 if ( !$title ) {
1062 $title = $wgTitle;
1064 $attribs['rel'] = Parser::getExternalLinkRel( $url, $title );
1065 $link = '';
1066 $success = Hooks::run( 'LinkerMakeExternalLink',
1067 array( &$url, &$text, &$link, &$attribs, $linktype ) );
1068 if ( !$success ) {
1069 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
1070 . "with url {$url} and text {$text} to {$link}\n", true );
1071 return $link;
1073 $attribs['href'] = $url;
1074 return Html::rawElement( 'a', $attribs, $text );
1078 * Make user link (or user contributions for unregistered users)
1079 * @param int $userId User id in database.
1080 * @param string $userName User name in database.
1081 * @param string $altUserName Text to display instead of the user name (optional)
1082 * @return string HTML fragment
1083 * @since 1.19 Method exists for a long time. $altUserName was added in 1.19.
1085 public static function userLink( $userId, $userName, $altUserName = false ) {
1086 $classes = 'mw-userlink';
1087 if ( $userId == 0 ) {
1088 $page = SpecialPage::getTitleFor( 'Contributions', $userName );
1089 if ( $altUserName === false ) {
1090 $altUserName = IP::prettifyIP( $userName );
1092 $classes .= ' mw-anonuserlink'; // Separate link class for anons (bug 43179)
1093 } else {
1094 $page = Title::makeTitle( NS_USER, $userName );
1097 return self::link(
1098 $page,
1099 htmlspecialchars( $altUserName !== false ? $altUserName : $userName ),
1100 array( 'class' => $classes )
1105 * Generate standard user tool links (talk, contributions, block link, etc.)
1107 * @param int $userId User identifier
1108 * @param string $userText User name or IP address
1109 * @param bool $redContribsWhenNoEdits Should the contributions link be
1110 * red if the user has no edits?
1111 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
1112 * and Linker::TOOL_LINKS_EMAIL).
1113 * @param int $edits User edit count (optional, for performance)
1114 * @return string HTML fragment
1116 public static function userToolLinks(
1117 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1119 global $wgUser, $wgDisableAnonTalk, $wgLang;
1120 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1121 $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1122 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1124 $items = array();
1125 if ( $talkable ) {
1126 $items[] = self::userTalkLink( $userId, $userText );
1128 if ( $userId ) {
1129 // check if the user has an edit
1130 $attribs = array();
1131 if ( $redContribsWhenNoEdits ) {
1132 if ( intval( $edits ) === 0 && $edits !== 0 ) {
1133 $user = User::newFromId( $userId );
1134 $edits = $user->getEditCount();
1136 if ( $edits === 0 ) {
1137 $attribs['class'] = 'new';
1140 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1142 $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1144 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1145 $items[] = self::blockLink( $userId, $userText );
1148 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1149 $items[] = self::emailLink( $userId, $userText );
1152 Hooks::run( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1154 if ( $items ) {
1155 return wfMessage( 'word-separator' )->escaped()
1156 . '<span class="mw-usertoollinks">'
1157 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1158 . '</span>';
1159 } else {
1160 return '';
1165 * Alias for userToolLinks( $userId, $userText, true );
1166 * @param int $userId User identifier
1167 * @param string $userText User name or IP address
1168 * @param int $edits User edit count (optional, for performance)
1169 * @return string
1171 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1172 return self::userToolLinks( $userId, $userText, true, 0, $edits );
1176 * @param int $userId User id in database.
1177 * @param string $userText User name in database.
1178 * @return string HTML fragment with user talk link
1180 public static function userTalkLink( $userId, $userText ) {
1181 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1182 $userTalkLink = self::link( $userTalkPage, wfMessage( 'talkpagelinktext' )->escaped() );
1183 return $userTalkLink;
1187 * @param int $userId Userid
1188 * @param string $userText User name in database.
1189 * @return string HTML fragment with block link
1191 public static function blockLink( $userId, $userText ) {
1192 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1193 $blockLink = self::link( $blockPage, wfMessage( 'blocklink' )->escaped() );
1194 return $blockLink;
1198 * @param int $userId Userid
1199 * @param string $userText User name in database.
1200 * @return string HTML fragment with e-mail user link
1202 public static function emailLink( $userId, $userText ) {
1203 $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1204 $emailLink = self::link( $emailPage, wfMessage( 'emaillink' )->escaped() );
1205 return $emailLink;
1209 * Generate a user link if the current user is allowed to view it
1210 * @param Revision $rev
1211 * @param bool $isPublic Show only if all users can see it
1212 * @return string HTML fragment
1214 public static function revUserLink( $rev, $isPublic = false ) {
1215 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1216 $link = wfMessage( 'rev-deleted-user' )->escaped();
1217 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1218 $link = self::userLink( $rev->getUser( Revision::FOR_THIS_USER ),
1219 $rev->getUserText( Revision::FOR_THIS_USER ) );
1220 } else {
1221 $link = wfMessage( 'rev-deleted-user' )->escaped();
1223 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1224 return '<span class="history-deleted">' . $link . '</span>';
1226 return $link;
1230 * Generate a user tool link cluster if the current user is allowed to view it
1231 * @param Revision $rev
1232 * @param bool $isPublic Show only if all users can see it
1233 * @return string HTML
1235 public static function revUserTools( $rev, $isPublic = false ) {
1236 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1237 $link = wfMessage( 'rev-deleted-user' )->escaped();
1238 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1239 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1240 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1241 $link = self::userLink( $userId, $userText )
1242 . self::userToolLinks( $userId, $userText );
1243 } else {
1244 $link = wfMessage( 'rev-deleted-user' )->escaped();
1246 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1247 return ' <span class="history-deleted">' . $link . '</span>';
1249 return $link;
1253 * This function is called by all recent changes variants, by the page history,
1254 * and by the user contributions list. It is responsible for formatting edit
1255 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1256 * auto-generated comments (from section editing) and formats [[wikilinks]].
1258 * @author Erik Moeller <moeller@scireview.de>
1260 * Note: there's not always a title to pass to this function.
1261 * Since you can't set a default parameter for a reference, I've turned it
1262 * temporarily to a value pass. Should be adjusted further. --brion
1264 * @param string $comment
1265 * @param Title|null $title Title object (to generate link to the section in autocomment)
1266 * or null
1267 * @param bool $local Whether section links should refer to local page
1268 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1269 * For use with external changes.
1271 * @return mixed|string
1273 public static function formatComment(
1274 $comment, $title = null, $local = false, $wikiId = null
1276 # Sanitize text a bit:
1277 $comment = str_replace( "\n", " ", $comment );
1278 # Allow HTML entities (for bug 13815)
1279 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1281 # Render autocomments and make links:
1282 $comment = self::formatAutocomments( $comment, $title, $local, $wikiId );
1283 $comment = self::formatLinksInComment( $comment, $title, $local, $wikiId );
1285 return $comment;
1289 * Converts autogenerated comments in edit summaries into section links.
1291 * The pattern for autogen comments is / * foo * /, which makes for
1292 * some nasty regex.
1293 * We look for all comments, match any text before and after the comment,
1294 * add a separator where needed and format the comment itself with CSS
1295 * Called by Linker::formatComment.
1297 * @param string $comment Comment text
1298 * @param Title|null $title An optional title object used to links to sections
1299 * @param bool $local Whether section links should refer to local page
1300 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1301 * as used by WikiMap.
1303 * @return string Formatted comment (wikitext)
1305 private static function formatAutocomments(
1306 $comment, $title = null, $local = false, $wikiId = null
1308 // @todo $append here is something of a hack to preserve the status
1309 // quo. Someone who knows more about bidi and such should decide
1310 // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1311 // wiki, both when autocomments exist and when they don't, and
1312 // (2) what markup will make that actually happen.
1313 $append = '';
1314 $comment = preg_replace_callback(
1315 // To detect the presence of content before or after the
1316 // auto-comment, we use capturing groups inside optional zero-width
1317 // assertions. But older versions of PCRE can't directly make
1318 // zero-width assertions optional, so wrap them in a non-capturing
1319 // group.
1320 '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1321 function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1322 global $wgLang;
1324 // Ensure all match positions are defined
1325 $match += array( '', '', '', '' );
1327 $pre = $match[1] !== '';
1328 $auto = $match[2];
1329 $post = $match[3] !== '';
1330 $comment = null;
1332 Hooks::run(
1333 'FormatAutocomments',
1334 array( &$comment, $pre, $auto, $post, $title, $local, $wikiId )
1337 if ( $comment === null ) {
1338 $link = '';
1339 if ( $title ) {
1340 $section = $auto;
1341 # Remove links that a user may have manually put in the autosummary
1342 # This could be improved by copying as much of Parser::stripSectionName as desired.
1343 $section = str_replace( '[[:', '', $section );
1344 $section = str_replace( '[[', '', $section );
1345 $section = str_replace( ']]', '', $section );
1347 $section = Sanitizer::normalizeSectionNameWhitespace( $section ); # bug 22784
1348 if ( $local ) {
1349 $sectionTitle = Title::newFromText( '#' . $section );
1350 } else {
1351 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1352 $title->getDBkey(), $section );
1354 if ( $sectionTitle ) {
1355 $link = Linker::makeCommentLink( $sectionTitle, $wgLang->getArrow(), $wikiId, 'noclasses' );
1356 } else {
1357 $link = '';
1360 if ( $pre ) {
1361 # written summary $presep autocomment (summary /* section */)
1362 $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1364 if ( $post ) {
1365 # autocomment $postsep written summary (/* section */ summary)
1366 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1368 $auto = '<span class="autocomment">' . $auto . '</span>';
1369 $comment = $pre . $link . $wgLang->getDirMark()
1370 . '<span dir="auto">' . $auto;
1371 $append .= '</span>';
1373 return $comment;
1375 $comment
1377 return $comment . $append;
1381 * Formats wiki links and media links in text; all other wiki formatting
1382 * is ignored
1384 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1385 * @param string $comment Text to format links in. WARNING! Since the output of this
1386 * function is html, $comment must be sanitized for use as html. You probably want
1387 * to pass $comment through Sanitizer::escapeHtmlAllowEntities() before calling
1388 * this function.
1389 * @param Title|null $title An optional title object used to links to sections
1390 * @param bool $local Whether section links should refer to local page
1391 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1392 * as used by WikiMap.
1394 * @return string
1396 public static function formatLinksInComment(
1397 $comment, $title = null, $local = false, $wikiId = null
1399 return preg_replace_callback(
1401 \[\[
1402 :? # ignore optional leading colon
1403 ([^\]|]+) # 1. link target; page names cannot include ] or |
1404 (?:\|
1405 # 2. a pipe-separated substring; only the last is captured
1406 # Stop matching at | and ]] without relying on backtracking.
1407 ((?:]?[^\]|])*+)
1409 \]\]
1410 ([^[]*) # 3. link trail (the text up until the next link)
1411 /x',
1412 function ( $match ) use ( $title, $local, $wikiId ) {
1413 global $wgContLang;
1415 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1416 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1418 $comment = $match[0];
1420 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1421 if ( strpos( $match[1], '%' ) !== false ) {
1422 $match[1] = strtr(
1423 rawurldecode( $match[1] ),
1424 array( '<' => '&lt;', '>' => '&gt;' )
1428 # Handle link renaming [[foo|text]] will show link as "text"
1429 if ( $match[2] != "" ) {
1430 $text = $match[2];
1431 } else {
1432 $text = $match[1];
1434 $submatch = array();
1435 $thelink = null;
1436 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1437 # Media link; trail not supported.
1438 $linkRegexp = '/\[\[(.*?)\]\]/';
1439 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1440 if ( $title ) {
1441 $thelink = Linker::makeMediaLinkObj( $title, $text );
1443 } else {
1444 # Other kind of link
1445 if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1446 $trail = $submatch[1];
1447 } else {
1448 $trail = "";
1450 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1451 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1452 $match[1] = substr( $match[1], 1 );
1454 list( $inside, $trail ) = Linker::splitTrail( $trail );
1456 $linkText = $text;
1457 $linkTarget = Linker::normalizeSubpageLink( $title, $match[1], $linkText );
1459 $target = Title::newFromText( $linkTarget );
1460 if ( $target ) {
1461 if ( $target->getText() == '' && !$target->isExternal()
1462 && !$local && $title
1464 $newTarget = clone $title;
1465 $newTarget->setFragment( '#' . $target->getFragment() );
1466 $target = $newTarget;
1469 $thelink = Linker::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1472 if ( $thelink ) {
1473 // If the link is still valid, go ahead and replace it in!
1474 $comment = preg_replace(
1475 $linkRegexp,
1476 StringUtils::escapeRegexReplacement( $thelink ),
1477 $comment,
1482 return $comment;
1484 $comment
1489 * Generates a link to the given Title
1491 * @note This is only public for technical reasons. It's not intended for use outside Linker.
1493 * @param Title $title
1494 * @param string $text
1495 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1496 * as used by WikiMap.
1497 * @param string|string[] $options See the $options parameter in Linker::link.
1499 * @return string HTML link
1501 public static function makeCommentLink(
1502 Title $title, $text, $wikiId = null, $options = array()
1504 if ( $wikiId !== null && !$title->isExternal() ) {
1505 $link = Linker::makeExternalLink(
1506 WikiMap::getForeignURL(
1507 $wikiId,
1508 $title->getPrefixedText(),
1509 $title->getFragment()
1511 $text,
1512 /* escape = */ false // Already escaped
1514 } else {
1515 $link = Linker::link( $title, $text, array(), array(), $options );
1518 return $link;
1522 * @param Title $contextTitle
1523 * @param string $target
1524 * @param string $text
1525 * @return string
1527 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1528 # Valid link forms:
1529 # Foobar -- normal
1530 # :Foobar -- override special treatment of prefix (images, language links)
1531 # /Foobar -- convert to CurrentPage/Foobar
1532 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1533 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1534 # ../Foobar -- convert to CurrentPage/Foobar,
1535 # (from CurrentPage/CurrentSubPage)
1536 # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1537 # (from CurrentPage/CurrentSubPage)
1539 $ret = $target; # default return value is no change
1541 # Some namespaces don't allow subpages,
1542 # so only perform processing if subpages are allowed
1543 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1544 $hash = strpos( $target, '#' );
1545 if ( $hash !== false ) {
1546 $suffix = substr( $target, $hash );
1547 $target = substr( $target, 0, $hash );
1548 } else {
1549 $suffix = '';
1551 # bug 7425
1552 $target = trim( $target );
1553 # Look at the first character
1554 if ( $target != '' && $target[0] === '/' ) {
1555 # / at end means we don't want the slash to be shown
1556 $m = array();
1557 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1558 if ( $trailingSlashes ) {
1559 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1560 } else {
1561 $noslash = substr( $target, 1 );
1564 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1565 if ( $text === '' ) {
1566 $text = $target . $suffix;
1567 } # this might be changed for ugliness reasons
1568 } else {
1569 # check for .. subpage backlinks
1570 $dotdotcount = 0;
1571 $nodotdot = $target;
1572 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1573 ++$dotdotcount;
1574 $nodotdot = substr( $nodotdot, 3 );
1576 if ( $dotdotcount > 0 ) {
1577 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1578 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1579 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1580 # / at the end means don't show full path
1581 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1582 $nodotdot = rtrim( $nodotdot, '/' );
1583 if ( $text === '' ) {
1584 $text = $nodotdot . $suffix;
1587 $nodotdot = trim( $nodotdot );
1588 if ( $nodotdot != '' ) {
1589 $ret .= '/' . $nodotdot;
1591 $ret .= $suffix;
1597 return $ret;
1601 * Wrap a comment in standard punctuation and formatting if
1602 * it's non-empty, otherwise return empty string.
1604 * @param string $comment
1605 * @param Title|null $title Title object (to generate link to section in autocomment) or null
1606 * @param bool $local Whether section links should refer to local page
1607 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1608 * For use with external changes.
1610 * @return string
1612 public static function commentBlock(
1613 $comment, $title = null, $local = false, $wikiId = null
1615 // '*' used to be the comment inserted by the software way back
1616 // in antiquity in case none was provided, here for backwards
1617 // compatibility, acc. to brion -ævar
1618 if ( $comment == '' || $comment == '*' ) {
1619 return '';
1620 } else {
1621 $formatted = self::formatComment( $comment, $title, $local, $wikiId );
1622 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1623 return " <span class=\"comment\">$formatted</span>";
1628 * Wrap and format the given revision's comment block, if the current
1629 * user is allowed to view it.
1631 * @param Revision $rev
1632 * @param bool $local Whether section links should refer to local page
1633 * @param bool $isPublic Show only if all users can see it
1634 * @return string HTML fragment
1636 public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1637 if ( $rev->getComment( Revision::RAW ) == "" ) {
1638 return "";
1640 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1641 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1642 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1643 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1644 $rev->getTitle(), $local );
1645 } else {
1646 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1648 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1649 return " <span class=\"history-deleted\">$block</span>";
1651 return $block;
1655 * @param int $size
1656 * @return string
1658 public static function formatRevisionSize( $size ) {
1659 if ( $size == 0 ) {
1660 $stxt = wfMessage( 'historyempty' )->escaped();
1661 } else {
1662 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1663 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1665 return "<span class=\"history-size\">$stxt</span>";
1669 * Add another level to the Table of Contents
1671 * @return string
1673 public static function tocIndent() {
1674 return "\n<ul>";
1678 * Finish one or more sublevels on the Table of Contents
1680 * @param int $level
1681 * @return string
1683 public static function tocUnindent( $level ) {
1684 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1688 * parameter level defines if we are on an indentation level
1690 * @param string $anchor
1691 * @param string $tocline
1692 * @param string $tocnumber
1693 * @param string $level
1694 * @param string|bool $sectionIndex
1695 * @return string
1697 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1698 $classes = "toclevel-$level";
1699 if ( $sectionIndex !== false ) {
1700 $classes .= " tocsection-$sectionIndex";
1702 return "\n<li class=\"$classes\"><a href=\"#" .
1703 $anchor . '"><span class="tocnumber">' .
1704 $tocnumber . '</span> <span class="toctext">' .
1705 $tocline . '</span></a>';
1709 * End a Table Of Contents line.
1710 * tocUnindent() will be used instead if we're ending a line below
1711 * the new level.
1712 * @return string
1714 public static function tocLineEnd() {
1715 return "</li>\n";
1719 * Wraps the TOC in a table and provides the hide/collapse javascript.
1721 * @param string $toc Html of the Table Of Contents
1722 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1723 * @return string Full html of the TOC
1725 public static function tocList( $toc, $lang = false ) {
1726 $lang = wfGetLangObj( $lang );
1727 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1729 return '<div id="toc" class="toc">'
1730 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1731 . $toc
1732 . "</ul>\n</div>\n";
1736 * Generate a table of contents from a section tree.
1738 * @param array $tree Return value of ParserOutput::getSections()
1739 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1740 * @return string HTML fragment
1742 public static function generateTOC( $tree, $lang = false ) {
1743 $toc = '';
1744 $lastLevel = 0;
1745 foreach ( $tree as $section ) {
1746 if ( $section['toclevel'] > $lastLevel ) {
1747 $toc .= self::tocIndent();
1748 } elseif ( $section['toclevel'] < $lastLevel ) {
1749 $toc .= self::tocUnindent(
1750 $lastLevel - $section['toclevel'] );
1751 } else {
1752 $toc .= self::tocLineEnd();
1755 $toc .= self::tocLine( $section['anchor'],
1756 $section['line'], $section['number'],
1757 $section['toclevel'], $section['index'] );
1758 $lastLevel = $section['toclevel'];
1760 $toc .= self::tocLineEnd();
1761 return self::tocList( $toc, $lang );
1765 * Create a headline for content
1767 * @param int $level The level of the headline (1-6)
1768 * @param string $attribs Any attributes for the headline, starting with
1769 * a space and ending with '>'
1770 * This *must* be at least '>' for no attribs
1771 * @param string $anchor The anchor to give the headline (the bit after the #)
1772 * @param string $html Html for the text of the header
1773 * @param string $link HTML to add for the section edit link
1774 * @param bool|string $legacyAnchor A second, optional anchor to give for
1775 * backward compatibility (false to omit)
1777 * @return string HTML headline
1779 public static function makeHeadline( $level, $attribs, $anchor, $html,
1780 $link, $legacyAnchor = false
1782 $ret = "<h$level$attribs"
1783 . "<span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1784 . $link
1785 . "</h$level>";
1786 if ( $legacyAnchor !== false ) {
1787 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1789 return $ret;
1793 * Split a link trail, return the "inside" portion and the remainder of the trail
1794 * as a two-element array
1795 * @param string $trail
1796 * @return array
1798 static function splitTrail( $trail ) {
1799 global $wgContLang;
1800 $regex = $wgContLang->linkTrail();
1801 $inside = '';
1802 if ( $trail !== '' ) {
1803 $m = array();
1804 if ( preg_match( $regex, $trail, $m ) ) {
1805 $inside = $m[1];
1806 $trail = $m[2];
1809 return array( $inside, $trail );
1813 * Generate a rollback link for a given revision. Currently it's the
1814 * caller's responsibility to ensure that the revision is the top one. If
1815 * it's not, of course, the user will get an error message.
1817 * If the calling page is called with the parameter &bot=1, all rollback
1818 * links also get that parameter. It causes the edit itself and the rollback
1819 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1820 * changes, so this allows sysops to combat a busy vandal without bothering
1821 * other users.
1823 * If the option verify is set this function will return the link only in case the
1824 * revision can be reverted. Please note that due to performance limitations
1825 * it might be assumed that a user isn't the only contributor of a page while
1826 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1827 * work if $wgShowRollbackEditCount is disabled, so this can only function
1828 * as an additional check.
1830 * If the option noBrackets is set the rollback link wont be enclosed in []
1832 * @param Revision $rev
1833 * @param IContextSource $context Context to use or null for the main context.
1834 * @param array $options
1835 * @return string
1837 public static function generateRollback( $rev, IContextSource $context = null,
1838 $options = array( 'verify' )
1840 if ( $context === null ) {
1841 $context = RequestContext::getMain();
1844 $editCount = false;
1845 if ( in_array( 'verify', $options ) ) {
1846 $editCount = self::getRollbackEditCount( $rev, true );
1847 if ( $editCount === false ) {
1848 return '';
1852 $inner = self::buildRollbackLink( $rev, $context, $editCount );
1854 if ( !in_array( 'noBrackets', $options ) ) {
1855 $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1858 return '<span class="mw-rollback-link">' . $inner . '</span>';
1862 * This function will return the number of revisions which a rollback
1863 * would revert and, if $verify is set it will verify that a revision
1864 * can be reverted (that the user isn't the only contributor and the
1865 * revision we might rollback to isn't deleted). These checks can only
1866 * function as an additional check as this function only checks against
1867 * the last $wgShowRollbackEditCount edits.
1869 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1870 * is set and the user is the only contributor of the page.
1872 * @param Revision $rev
1873 * @param bool $verify Try to verify that this revision can really be rolled back
1874 * @return int|bool|null
1876 public static function getRollbackEditCount( $rev, $verify ) {
1877 global $wgShowRollbackEditCount;
1878 if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
1879 // Nothing has happened, indicate this by returning 'null'
1880 return null;
1883 $dbr = wfGetDB( DB_SLAVE );
1885 // Up to the value of $wgShowRollbackEditCount revisions are counted
1886 $res = $dbr->select(
1887 'revision',
1888 array( 'rev_user_text', 'rev_deleted' ),
1889 // $rev->getPage() returns null sometimes
1890 array( 'rev_page' => $rev->getTitle()->getArticleID() ),
1891 __METHOD__,
1892 array(
1893 'USE INDEX' => array( 'revision' => 'page_timestamp' ),
1894 'ORDER BY' => 'rev_timestamp DESC',
1895 'LIMIT' => $wgShowRollbackEditCount + 1
1899 $editCount = 0;
1900 $moreRevs = false;
1901 foreach ( $res as $row ) {
1902 if ( $rev->getUserText( Revision::RAW ) != $row->rev_user_text ) {
1903 if ( $verify &&
1904 ( $row->rev_deleted & Revision::DELETED_TEXT
1905 || $row->rev_deleted & Revision::DELETED_USER
1906 ) ) {
1907 // If the user or the text of the revision we might rollback
1908 // to is deleted in some way we can't rollback. Similar to
1909 // the sanity checks in WikiPage::commitRollback.
1910 return false;
1912 $moreRevs = true;
1913 break;
1915 $editCount++;
1918 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1919 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1920 // and there weren't any other revisions. That means that the current user is the only
1921 // editor, so we can't rollback
1922 return false;
1924 return $editCount;
1928 * Build a raw rollback link, useful for collections of "tool" links
1930 * @param Revision $rev
1931 * @param IContextSource|null $context Context to use or null for the main context.
1932 * @param int $editCount Number of edits that would be reverted
1933 * @return string HTML fragment
1935 public static function buildRollbackLink( $rev, IContextSource $context = null,
1936 $editCount = false
1938 global $wgShowRollbackEditCount, $wgMiserMode;
1940 // To config which pages are affected by miser mode
1941 $disableRollbackEditCountSpecialPage = array( 'Recentchanges', 'Watchlist' );
1943 if ( $context === null ) {
1944 $context = RequestContext::getMain();
1947 $title = $rev->getTitle();
1948 $query = array(
1949 'action' => 'rollback',
1950 'from' => $rev->getUserText(),
1951 'token' => $context->getUser()->getEditToken( array(
1952 $title->getPrefixedText(),
1953 $rev->getUserText()
1954 ) ),
1956 if ( $context->getRequest()->getBool( 'bot' ) ) {
1957 $query['bot'] = '1';
1958 $query['hidediff'] = '1'; // bug 15999
1961 $disableRollbackEditCount = false;
1962 if ( $wgMiserMode ) {
1963 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1964 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1965 $disableRollbackEditCount = true;
1966 break;
1971 if ( !$disableRollbackEditCount
1972 && is_int( $wgShowRollbackEditCount )
1973 && $wgShowRollbackEditCount > 0
1975 if ( !is_numeric( $editCount ) ) {
1976 $editCount = self::getRollbackEditCount( $rev, false );
1979 if ( $editCount > $wgShowRollbackEditCount ) {
1980 $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )
1981 ->numParams( $wgShowRollbackEditCount )->parse();
1982 } else {
1983 $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1986 return self::link(
1987 $title,
1988 $editCount_output,
1989 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1990 $query,
1991 array( 'known', 'noclasses' )
1993 } else {
1994 return self::link(
1995 $title,
1996 $context->msg( 'rollbacklink' )->escaped(),
1997 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1998 $query,
1999 array( 'known', 'noclasses' )
2005 * Returns HTML for the "templates used on this page" list.
2007 * Make an HTML list of templates, and then add a "More..." link at
2008 * the bottom. If $more is null, do not add a "More..." link. If $more
2009 * is a Title, make a link to that title and use it. If $more is a string,
2010 * directly paste it in as the link (escaping needs to be done manually).
2011 * Finally, if $more is a Message, call toString().
2013 * @param array $templates Array of templates from Article::getUsedTemplate or similar
2014 * @param bool $preview Whether this is for a preview
2015 * @param bool $section Whether this is for a section edit
2016 * @param Title|Message|string|null $more An escaped link for "More..." of the templates
2017 * @return string HTML output
2019 public static function formatTemplates( $templates, $preview = false,
2020 $section = false, $more = null
2022 global $wgLang;
2024 $outText = '';
2025 if ( count( $templates ) > 0 ) {
2026 # Do a batch existence check
2027 $batch = new LinkBatch;
2028 foreach ( $templates as $title ) {
2029 $batch->addObj( $title );
2031 $batch->execute();
2033 # Construct the HTML
2034 $outText = '<div class="mw-templatesUsedExplanation">';
2035 if ( $preview ) {
2036 $outText .= wfMessage( 'templatesusedpreview' )->numParams( count( $templates ) )
2037 ->parseAsBlock();
2038 } elseif ( $section ) {
2039 $outText .= wfMessage( 'templatesusedsection' )->numParams( count( $templates ) )
2040 ->parseAsBlock();
2041 } else {
2042 $outText .= wfMessage( 'templatesused' )->numParams( count( $templates ) )
2043 ->parseAsBlock();
2045 $outText .= "</div><ul>\n";
2047 usort( $templates, 'Title::compare' );
2048 foreach ( $templates as $titleObj ) {
2049 $protected = '';
2050 $restrictions = $titleObj->getRestrictions( 'edit' );
2051 if ( $restrictions ) {
2052 // Check backwards-compatible messages
2053 $msg = null;
2054 if ( $restrictions === array( 'sysop' ) ) {
2055 $msg = wfMessage( 'template-protected' );
2056 } elseif ( $restrictions === array( 'autoconfirmed' ) ) {
2057 $msg = wfMessage( 'template-semiprotected' );
2059 if ( $msg && !$msg->isDisabled() ) {
2060 $protected = $msg->parse();
2061 } else {
2062 // Construct the message from restriction-level-*
2063 // e.g. restriction-level-sysop, restriction-level-autoconfirmed
2064 $msgs = array();
2065 foreach ( $restrictions as $r ) {
2066 $msgs[] = wfMessage( "restriction-level-$r" )->parse();
2068 $protected = wfMessage( 'parentheses' )
2069 ->rawParams( $wgLang->commaList( $msgs ) )->escaped();
2072 if ( $titleObj->quickUserCan( 'edit' ) ) {
2073 $editLink = self::link(
2074 $titleObj,
2075 wfMessage( 'editlink' )->escaped(),
2076 array(),
2077 array( 'action' => 'edit' )
2079 } else {
2080 $editLink = self::link(
2081 $titleObj,
2082 wfMessage( 'viewsourcelink' )->escaped(),
2083 array(),
2084 array( 'action' => 'edit' )
2087 $outText .= '<li>' . self::link( $titleObj )
2088 . wfMessage( 'word-separator' )->escaped()
2089 . wfMessage( 'parentheses' )->rawParams( $editLink )->escaped()
2090 . wfMessage( 'word-separator' )->escaped()
2091 . $protected . '</li>';
2094 if ( $more instanceof Title ) {
2095 $outText .= '<li>' . self::link( $more, wfMessage( 'moredotdotdot' ) ) . '</li>';
2096 } elseif ( $more ) {
2097 $outText .= "<li>$more</li>";
2100 $outText .= '</ul>';
2102 return $outText;
2106 * Returns HTML for the "hidden categories on this page" list.
2108 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
2109 * or similar
2110 * @return string HTML output
2112 public static function formatHiddenCategories( $hiddencats ) {
2114 $outText = '';
2115 if ( count( $hiddencats ) > 0 ) {
2116 # Construct the HTML
2117 $outText = '<div class="mw-hiddenCategoriesExplanation">';
2118 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
2119 $outText .= "</div><ul>\n";
2121 foreach ( $hiddencats as $titleObj ) {
2122 # If it's hidden, it must exist - no need to check with a LinkBatch
2123 $outText .= '<li>'
2124 . self::link( $titleObj, null, array(), array(), 'known' )
2125 . "</li>\n";
2127 $outText .= '</ul>';
2129 return $outText;
2133 * Format a size in bytes for output, using an appropriate
2134 * unit (B, KB, MB or GB) according to the magnitude in question
2136 * @param int $size Size to format
2137 * @return string
2139 public static function formatSize( $size ) {
2140 global $wgLang;
2141 return htmlspecialchars( $wgLang->formatSize( $size ) );
2145 * Given the id of an interface element, constructs the appropriate title
2146 * attribute from the system messages. (Note, this is usually the id but
2147 * isn't always, because sometimes the accesskey needs to go on a different
2148 * element than the id, for reverse-compatibility, etc.)
2150 * @param string $name Id of the element, minus prefixes.
2151 * @param string|null $options Null or the string 'withaccess' to add an access-
2152 * key hint
2153 * @param array $msgParams Parameters to pass to the message
2155 * @return string Contents of the title attribute (which you must HTML-
2156 * escape), or false for no title attribute
2158 public static function titleAttrib( $name, $options = null, array $msgParams = array() ) {
2159 $message = wfMessage( "tooltip-$name", $msgParams );
2160 if ( !$message->exists() ) {
2161 $tooltip = false;
2162 } else {
2163 $tooltip = $message->text();
2164 # Compatibility: formerly some tooltips had [alt-.] hardcoded
2165 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2166 # Message equal to '-' means suppress it.
2167 if ( $tooltip == '-' ) {
2168 $tooltip = false;
2172 if ( $options == 'withaccess' ) {
2173 $accesskey = self::accesskey( $name );
2174 if ( $accesskey !== false ) {
2175 // Should be build the same as in jquery.accessKeyLabel.js
2176 if ( $tooltip === false || $tooltip === '' ) {
2177 $tooltip = wfMessage( 'brackets', $accesskey )->text();
2178 } else {
2179 $tooltip .= wfMessage( 'word-separator' )->text();
2180 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
2185 return $tooltip;
2188 public static $accesskeycache;
2191 * Given the id of an interface element, constructs the appropriate
2192 * accesskey attribute from the system messages. (Note, this is usually
2193 * the id but isn't always, because sometimes the accesskey needs to go on
2194 * a different element than the id, for reverse-compatibility, etc.)
2196 * @param string $name Id of the element, minus prefixes.
2197 * @return string Contents of the accesskey attribute (which you must HTML-
2198 * escape), or false for no accesskey attribute
2200 public static function accesskey( $name ) {
2201 if ( isset( self::$accesskeycache[$name] ) ) {
2202 return self::$accesskeycache[$name];
2205 $message = wfMessage( "accesskey-$name" );
2207 if ( !$message->exists() ) {
2208 $accesskey = false;
2209 } else {
2210 $accesskey = $message->plain();
2211 if ( $accesskey === '' || $accesskey === '-' ) {
2212 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2213 # attribute, but this is broken for accesskey: that might be a useful
2214 # value.
2215 $accesskey = false;
2219 self::$accesskeycache[$name] = $accesskey;
2220 return self::$accesskeycache[$name];
2224 * Get a revision-deletion link, or disabled link, or nothing, depending
2225 * on user permissions & the settings on the revision.
2227 * Will use forward-compatible revision ID in the Special:RevDelete link
2228 * if possible, otherwise the timestamp-based ID which may break after
2229 * undeletion.
2231 * @param User $user
2232 * @param Revision $rev
2233 * @param Title $title
2234 * @return string HTML fragment
2236 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
2237 $canHide = $user->isAllowed( 'deleterevision' );
2238 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2239 return '';
2242 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
2243 return Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2244 } else {
2245 if ( $rev->getId() ) {
2246 // RevDelete links using revision ID are stable across
2247 // page deletion and undeletion; use when possible.
2248 $query = array(
2249 'type' => 'revision',
2250 'target' => $title->getPrefixedDBkey(),
2251 'ids' => $rev->getId()
2253 } else {
2254 // Older deleted entries didn't save a revision ID.
2255 // We have to refer to these by timestamp, ick!
2256 $query = array(
2257 'type' => 'archive',
2258 'target' => $title->getPrefixedDBkey(),
2259 'ids' => $rev->getTimestamp()
2262 return Linker::revDeleteLink( $query,
2263 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2268 * Creates a (show/hide) link for deleting revisions/log entries
2270 * @param array $query Query parameters to be passed to link()
2271 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2272 * @param bool $delete Set to true to use (show/hide) rather than (show)
2274 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2275 * span to allow for customization of appearance with CSS
2277 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
2278 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2279 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2280 $html = wfMessage( $msgKey )->escaped();
2281 $tag = $restricted ? 'strong' : 'span';
2282 $link = self::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
2283 return Xml::tags(
2284 $tag,
2285 array( 'class' => 'mw-revdelundel-link' ),
2286 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2291 * Creates a dead (show/hide) link for deleting revisions/log entries
2293 * @param bool $delete Set to true to use (show/hide) rather than (show)
2295 * @return string HTML text wrapped in a span to allow for customization
2296 * of appearance with CSS
2298 public static function revDeleteLinkDisabled( $delete = true ) {
2299 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2300 $html = wfMessage( $msgKey )->escaped();
2301 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2302 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), $htmlParentheses );
2305 /* Deprecated methods */
2308 * Returns the attributes for the tooltip and access key.
2310 * @param string $name
2311 * @param array $msgParams Params for constructing the message
2313 * @return array
2315 public static function tooltipAndAccesskeyAttribs( $name, array $msgParams = array() ) {
2316 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2317 # no attribute" instead of "output '' as value for attribute", this
2318 # would be three lines.
2319 $attribs = array(
2320 'title' => self::titleAttrib( $name, 'withaccess', $msgParams ),
2321 'accesskey' => self::accesskey( $name )
2323 if ( $attribs['title'] === false ) {
2324 unset( $attribs['title'] );
2326 if ( $attribs['accesskey'] === false ) {
2327 unset( $attribs['accesskey'] );
2329 return $attribs;
2333 * Returns raw bits of HTML, use titleAttrib()
2334 * @param string $name
2335 * @param array|null $options
2336 * @return null|string
2338 public static function tooltip( $name, $options = null ) {
2339 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2340 # no attribute" instead of "output '' as value for attribute", this
2341 # would be two lines.
2342 $tooltip = self::titleAttrib( $name, $options );
2343 if ( $tooltip === false ) {
2344 return '';
2346 return Xml::expandAttributes( array(
2347 'title' => $tooltip
2348 ) );
2354 * @since 1.18
2356 class DummyLinker {
2359 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2360 * into static calls to the new Linker for backwards compatibility.
2362 * @param string $fname Name of called method
2363 * @param array $args Arguments to the method
2364 * @return mixed
2366 public function __call( $fname, $args ) {
2367 return call_user_func_array( array( 'Linker', $fname ), $args );