Make sure processResponsiveImages checks for valid thumb object
[mediawiki.git] / includes / Linker.php
blob012bc1ba64c5913b594646f0f8731aa7e2584d17
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
41 * external link, as created by [wikisyntax].
43 * @param string $class The contents of the class attribute; if an empty
44 * string is passed, which is the default value, defaults to 'external'.
45 * @return string
46 * @deprecated since 1.18 Just pass the external class directly to something
47 * using Html::expandAttributes.
49 static function getExternalLinkAttributes( $class = 'external' ) {
50 wfDeprecated( __METHOD__, '1.18' );
51 return self::getLinkAttributesInternal( '', $class );
54 /**
55 * Get the appropriate HTML attributes to add to the "a" element of an interwiki link.
57 * @param string $title The title text for the link, URL-encoded (???) but
58 * not HTML-escaped
59 * @param string $unused Unused
60 * @param string $class The contents of the class attribute; if an empty
61 * string is passed, which is the default value, defaults to 'external'.
62 * @return string
64 static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
65 global $wgContLang;
67 # @todo FIXME: We have a whole bunch of handling here that doesn't happen in
68 # getExternalLinkAttributes, why?
69 $title = urldecode( $title );
70 $title = $wgContLang->checkTitleEncoding( $title );
71 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
73 return self::getLinkAttributesInternal( $title, $class );
76 /**
77 * Get the appropriate HTML attributes to add to the "a" element of an internal link.
79 * @param string $title The title text for the link, URL-encoded (???) but
80 * not HTML-escaped
81 * @param string $unused Unused
82 * @param string $class The contents of the class attribute, default none
83 * @return string
85 static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
86 $title = urldecode( $title );
87 $title = str_replace( '_', ' ', $title );
88 return self::getLinkAttributesInternal( $title, $class );
91 /**
92 * Get the appropriate HTML attributes to add to the "a" element of an internal
93 * link, given the Title object for the page we want to link to.
95 * @param Title $nt
96 * @param string $unused Unused
97 * @param string $class The contents of the class attribute, default none
98 * @param string|bool $title Optional (unescaped) string to use in the title
99 * attribute; if false, default to the name of the page we're linking to
100 * @return string
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 string $title
113 * @param string $class
115 * @return string
117 private static function getLinkAttributesInternal( $title, $class ) {
118 $title = htmlspecialchars( $title );
119 $class = htmlspecialchars( $class );
120 $r = '';
121 if ( $class != '' ) {
122 $r .= " class=\"$class\"";
124 if ( $title != '' ) {
125 $r .= " title=\"$title\"";
127 return $r;
131 * Return the CSS colour of a known link
133 * @param Title $t
134 * @param int $threshold User defined threshold
135 * @return string CSS class
137 public static function getLinkColour( $t, $threshold ) {
138 $colour = '';
139 if ( $t->isRedirect() ) {
140 # Page is a redirect
141 $colour = 'mw-redirect';
142 } elseif ( $threshold > 0 && $t->isContentPage() &&
143 $t->exists() && $t->getLength() < $threshold
145 # Page is a stub
146 $colour = 'stub';
148 return $colour;
152 * This function returns an HTML link to the given target. It serves a few
153 * purposes:
154 * 1) If $target is a Title, the correct URL to link to will be figured
155 * out automatically.
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.
165 * @param Title $target Can currently only be a Title, but this may
166 * change to support Images, literal URLs, etc.
167 * @param string $html The HTML contents of the <a> element, i.e.,
168 * the link text. This is raw HTML and will not be escaped. If null,
169 * defaults to the prefixed text of the Title; or if the Title is just a
170 * fragment, the contents of the fragment.
171 * @param array $customAttribs A key => value array of extra HTML attributes,
172 * such as title and class. (href is ignored.) Classes will be
173 * merged with the default classes, while other attributes will replace
174 * default attributes. All passed attribute values will be HTML-escaped.
175 * A false attribute value means to suppress that attribute.
176 * @param array $query The query string to append to the URL
177 * you're linking to, in key => value array form. Query keys and values
178 * will be URL-encoded.
179 * @param string|array $options String or array of strings:
180 * 'known': Page is known to exist, so don't check if it does.
181 * 'broken': Page is known not to exist, so don't check if it does.
182 * 'noclasses': Don't add any classes automatically (includes "new",
183 * "stub", "mw-redirect", "extiw"). Only use the class attribute
184 * provided, if any, so you get a simple blue link with no funny i-
185 * cons.
186 * 'forcearticlepath': Use the article path always, even with a querystring.
187 * Has compatibility issues on some setups, so avoid wherever possible.
188 * 'http': Force a full URL with http:// as the scheme.
189 * 'https': Force a full URL with https:// as the scheme.
190 * @return string HTML <a> attribute
192 public static function link(
193 $target, $html = null, $customAttribs = array(), $query = array(), $options = array()
195 wfProfileIn( __METHOD__ );
196 if ( !$target instanceof Title ) {
197 wfProfileOut( __METHOD__ );
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 ( !wfRunHooks( 'LinkBegin', array( $dummy, $target, &$html,
212 &$customAttribs, &$query, &$options, &$ret ) ) ) {
213 wfProfileOut( __METHOD__ );
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 wfProfileIn( __METHOD__ . '-checkPageExistence' );
222 if ( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
223 if ( $target->isKnown() ) {
224 $options[] = 'known';
225 } else {
226 $options[] = 'broken';
229 wfProfileOut( __METHOD__ . '-checkPageExistence' );
231 $oldquery = array();
232 if ( in_array( "forcearticlepath", $options ) && $query ) {
233 $oldquery = $query;
234 $query = array();
237 # Note: we want the href attribute first, for prettiness.
238 $attribs = array( 'href' => self::linkUrl( $target, $query, $options ) );
239 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
240 $attribs['href'] = wfAppendQuery( $attribs['href'], $oldquery );
243 $attribs = array_merge(
244 $attribs,
245 self::linkAttribs( $target, $customAttribs, $options )
247 if ( is_null( $html ) ) {
248 $html = self::linkText( $target );
251 $ret = null;
252 if ( wfRunHooks( 'LinkEnd', array( $dummy, $target, $options, &$html, &$attribs, &$ret ) ) ) {
253 $ret = Html::rawElement( 'a', $attribs, $html );
256 wfProfileOut( __METHOD__ );
257 return $ret;
261 * Identical to link(), except $options defaults to 'known'.
262 * @see Linker::link
263 * @return string
265 public static function linkKnown(
266 $target, $html = null, $customAttribs = array(),
267 $query = array(), $options = array( 'known', 'noclasses' )
269 return self::link( $target, $html, $customAttribs, $query, $options );
273 * Returns the Url used to link to a Title
275 * @param Title $target
276 * @param array $query Query parameters
277 * @param array $options
278 * @return string
280 private static function linkUrl( $target, $query, $options ) {
281 wfProfileIn( __METHOD__ );
282 # We don't want to include fragments for broken links, because they
283 # generally make no sense.
284 if ( in_array( 'broken', $options ) && $target->hasFragment() ) {
285 $target = clone $target;
286 $target->setFragment( '' );
289 # If it's a broken link, add the appropriate query pieces, unless
290 # there's already an action specified, or unless 'edit' makes no sense
291 # (i.e., for a nonexistent special page).
292 if ( in_array( 'broken', $options ) && empty( $query['action'] )
293 && !$target->isSpecialPage() ) {
294 $query['action'] = 'edit';
295 $query['redlink'] = '1';
298 if ( in_array( 'http', $options ) ) {
299 $proto = PROTO_HTTP;
300 } elseif ( in_array( 'https', $options ) ) {
301 $proto = PROTO_HTTPS;
302 } else {
303 $proto = PROTO_RELATIVE;
306 $ret = $target->getLinkURL( $query, false, $proto );
307 wfProfileOut( __METHOD__ );
308 return $ret;
312 * Returns the array of attributes used when linking to the Title $target
314 * @param Title $target
315 * @param array $attribs
316 * @param array $options
318 * @return array
320 private static function linkAttribs( $target, $attribs, $options ) {
321 wfProfileIn( __METHOD__ );
322 global $wgUser;
323 $defaults = array();
325 if ( !in_array( 'noclasses', $options ) ) {
326 wfProfileIn( __METHOD__ . '-getClasses' );
327 # Now build the classes.
328 $classes = array();
330 if ( in_array( 'broken', $options ) ) {
331 $classes[] = 'new';
334 if ( $target->isExternal() ) {
335 $classes[] = 'extiw';
338 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
339 $colour = self::getLinkColour( $target, $wgUser->getStubThreshold() );
340 if ( $colour !== '' ) {
341 $classes[] = $colour; # mw-redirect or stub
344 if ( $classes != array() ) {
345 $defaults['class'] = implode( ' ', $classes );
347 wfProfileOut( __METHOD__ . '-getClasses' );
350 # Get a default title attribute.
351 if ( $target->getPrefixedText() == '' ) {
352 # A link like [[#Foo]]. This used to mean an empty title
353 # attribute, but that's silly. Just don't output a title.
354 } elseif ( in_array( 'known', $options ) ) {
355 $defaults['title'] = $target->getPrefixedText();
356 } else {
357 $defaults['title'] = wfMessage( 'red-link-title', $target->getPrefixedText() )->text();
360 # Finally, merge the custom attribs with the default ones, and iterate
361 # over that, deleting all "false" attributes.
362 $ret = array();
363 $merged = Sanitizer::mergeAttributes( $defaults, $attribs );
364 foreach ( $merged as $key => $val ) {
365 # A false value suppresses the attribute, and we don't want the
366 # href attribute to be overridden.
367 if ( $key != 'href' and $val !== false ) {
368 $ret[$key] = $val;
371 wfProfileOut( __METHOD__ );
372 return $ret;
376 * Default text of the links to the Title $target
378 * @param Title $target
380 * @return string
382 private static function linkText( $target ) {
383 // We might be passed a non-Title by make*LinkObj(). Fail gracefully.
384 if ( !$target instanceof Title ) {
385 return '';
388 // If the target is just a fragment, with no title, we return the fragment
389 // text. Otherwise, we return the title text itself.
390 if ( $target->getPrefixedText() === '' && $target->hasFragment() ) {
391 return htmlspecialchars( $target->getFragment() );
394 return htmlspecialchars( $target->getPrefixedText() );
398 * Make appropriate markup for a link to the current article. This is
399 * currently rendered as the bold link text. The calling sequence is the
400 * same as the other make*LinkObj static functions, despite $query not
401 * being used.
403 * @param Title $nt
404 * @param string $html [optional]
405 * @param string $query [optional]
406 * @param string $trail [optional]
407 * @param string $prefix [optional]
409 * @return string
411 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
412 $ret = "<strong class=\"selflink\">{$prefix}{$html}</strong>{$trail}";
413 if ( !wfRunHooks( 'SelfLinkBegin', array( $nt, &$html, &$trail, &$prefix, &$ret ) ) ) {
414 return $ret;
417 if ( $html == '' ) {
418 $html = htmlspecialchars( $nt->getPrefixedText() );
420 list( $inside, $trail ) = self::splitTrail( $trail );
421 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
425 * Get a message saying that an invalid title was encountered.
426 * This should be called after a method like Title::makeTitleSafe() returned
427 * a value indicating that the title object is invalid.
429 * @param IContextSource $context Context to use to get the messages
430 * @param int $namespace Namespace number
431 * @param string $title Text of the title, without the namespace part
432 * @return string
434 public static function getInvalidTitleDescription( IContextSource $context, $namespace, $title ) {
435 global $wgContLang;
437 // First we check whether the namespace exists or not.
438 if ( MWNamespace::exists( $namespace ) ) {
439 if ( $namespace == NS_MAIN ) {
440 $name = $context->msg( 'blanknamespace' )->text();
441 } else {
442 $name = $wgContLang->getFormattedNsText( $namespace );
444 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
445 } else {
446 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
451 * @param Title $title
452 * @return Title
454 static function normaliseSpecialPage( Title $title ) {
455 if ( $title->isSpecialPage() ) {
456 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
457 if ( !$name ) {
458 return $title;
460 $ret = SpecialPage::getTitleFor( $name, $subpage, $title->getFragment() );
461 return $ret;
462 } else {
463 return $title;
468 * Returns the filename part of an url.
469 * Used as alternative text for external images.
471 * @param string $url
473 * @return string
475 private static function fnamePart( $url ) {
476 $basename = strrchr( $url, '/' );
477 if ( false === $basename ) {
478 $basename = $url;
479 } else {
480 $basename = substr( $basename, 1 );
482 return $basename;
486 * Return the code for images which were added via external links,
487 * via Parser::maybeMakeExternalImage().
489 * @param string $url
490 * @param string $alt
492 * @return string
494 public static function makeExternalImage( $url, $alt = '' ) {
495 if ( $alt == '' ) {
496 $alt = self::fnamePart( $url );
498 $img = '';
499 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
500 if ( !$success ) {
501 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
502 . "with url {$url} and alt text {$alt} to {$img}\n", true );
503 return $img;
505 return Html::element( 'img',
506 array(
507 'src' => $url,
508 'alt' => $alt ) );
512 * Given parameters derived from [[Image:Foo|options...]], generate the
513 * HTML that that syntax inserts in the page.
515 * @param Parser $parser
516 * @param Title $title Title object of the file (not the currently viewed page)
517 * @param File $file File object, or false if it doesn't exist
518 * @param array $frameParams Associative array of parameters external to the media handler.
519 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
520 * will often be false.
521 * thumbnail If present, downscale and frame
522 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
523 * framed Shows image in original size in a frame
524 * frameless Downscale but don't frame
525 * upright If present, tweak default sizes for portrait orientation
526 * upright_factor Fudge factor for "upright" tweak (default 0.75)
527 * border If present, show a border around the image
528 * align Horizontal alignment (left, right, center, none)
529 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
530 * bottom, text-bottom)
531 * alt Alternate text for image (i.e. alt attribute). Plain text.
532 * class HTML for image classes. 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 attribute, only with link-url
537 * no-link Boolean, suppress description link
539 * @param array $handlerParams Associative array of media handler parameters, to be passed
540 * to transform(). Typical keys are "width" and "page".
541 * @param string|bool $time Timestamp of the file, set as false for current
542 * @param string $query Query params for desc url
543 * @param int|null $widthOption Used by the parser to remember the user preference thumbnailsize
544 * @since 1.20
545 * @return string HTML for an image, with links, wrappers, etc.
547 public static function makeImageLink( /*Parser*/ $parser, Title $title,
548 $file, $frameParams = array(), $handlerParams = array(), $time = false,
549 $query = "", $widthOption = null
551 $res = null;
552 $dummy = new DummyLinker;
553 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
554 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
555 return $res;
558 if ( $file && !$file->allowInlineDisplay() ) {
559 wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
560 return self::link( $title );
563 // Shortcuts
564 $fp =& $frameParams;
565 $hp =& $handlerParams;
567 // Clean up parameters
568 $page = isset( $hp['page'] ) ? $hp['page'] : false;
569 if ( !isset( $fp['align'] ) ) {
570 $fp['align'] = '';
572 if ( !isset( $fp['alt'] ) ) {
573 $fp['alt'] = '';
575 if ( !isset( $fp['title'] ) ) {
576 $fp['title'] = '';
578 if ( !isset( $fp['class'] ) ) {
579 $fp['class'] = '';
582 $prefix = $postfix = '';
584 if ( 'center' == $fp['align'] ) {
585 $prefix = '<div class="center">';
586 $postfix = '</div>';
587 $fp['align'] = 'none';
589 if ( $file && !isset( $hp['width'] ) ) {
590 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
591 // If its a vector image, and user only specifies height
592 // we don't want it to be limited by its "normal" width.
593 global $wgSVGMaxSize;
594 $hp['width'] = $wgSVGMaxSize;
595 } else {
596 $hp['width'] = $file->getWidth( $page );
599 if ( isset( $fp['thumbnail'] )
600 || isset( $fp['manualthumb'] )
601 || isset( $fp['framed'] )
602 || isset( $fp['frameless'] )
603 || !$hp['width']
605 global $wgThumbLimits, $wgThumbUpright;
607 if ( $widthOption === null || !isset( $wgThumbLimits[$widthOption] ) ) {
608 $widthOption = User::getDefaultOption( 'thumbsize' );
611 // Reduce width for upright images when parameter 'upright' is used
612 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
613 $fp['upright'] = $wgThumbUpright;
616 // For caching health: If width scaled down due to upright
617 // parameter, round to full __0 pixel to avoid the creation of a
618 // lot of odd thumbs.
619 $prefWidth = isset( $fp['upright'] ) ?
620 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
621 $wgThumbLimits[$widthOption];
623 // Use width which is smaller: real image width or user preference width
624 // Unless image is scalable vector.
625 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
626 $prefWidth < $hp['width'] || $file->isVectorized() ) ) {
627 $hp['width'] = $prefWidth;
632 if ( isset( $fp['thumbnail'] ) || isset( $fp['manualthumb'] ) || isset( $fp['framed'] ) ) {
633 # Create a thumbnail. Alignment depends on the writing direction of
634 # the page content language (right-aligned for LTR languages,
635 # left-aligned for RTL languages)
637 # If a thumbnail width has not been provided, it is set
638 # to the default user option as specified in Language*.php
639 if ( $fp['align'] == '' ) {
640 if ( $parser instanceof Parser ) {
641 $fp['align'] = $parser->getTargetLanguage()->alignEnd();
642 } else {
643 # backwards compatibility, remove with makeImageLink2()
644 global $wgContLang;
645 $fp['align'] = $wgContLang->alignEnd();
648 return $prefix . self::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
651 if ( $file && isset( $fp['frameless'] ) ) {
652 $srcWidth = $file->getWidth( $page );
653 # For "frameless" option: do not present an image bigger than the
654 # source (for bitmap-style images). This is the same behavior as the
655 # "thumb" option does it already.
656 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
657 $hp['width'] = $srcWidth;
661 if ( $file && isset( $hp['width'] ) ) {
662 # Create a resized image, without the additional thumbnail features
663 $thumb = $file->transform( $hp );
664 } else {
665 $thumb = false;
668 if ( !$thumb ) {
669 $s = self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
670 } else {
671 self::processResponsiveImages( $file, $thumb, $hp );
672 $params = array(
673 'alt' => $fp['alt'],
674 'title' => $fp['title'],
675 'valign' => isset( $fp['valign'] ) ? $fp['valign'] : false,
676 'img-class' => $fp['class'] );
677 if ( isset( $fp['border'] ) ) {
678 $params['img-class'] .= ( $params['img-class'] !== '' ? ' ' : '' ) . 'thumbborder';
680 $params = self::getImageLinkMTOParams( $fp, $query, $parser ) + $params;
682 $s = $thumb->toHtml( $params );
684 if ( $fp['align'] != '' ) {
685 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
687 return str_replace( "\n", ' ', $prefix . $s . $postfix );
691 * See makeImageLink()
692 * When this function is removed, remove if( $parser instanceof Parser ) check there too
693 * @deprecated since 1.20
695 public static function makeImageLink2( Title $title, $file, $frameParams = array(),
696 $handlerParams = array(), $time = false, $query = "", $widthOption = null ) {
697 return self::makeImageLink( null, $title, $file, $frameParams,
698 $handlerParams, $time, $query, $widthOption );
702 * Get the link parameters for MediaTransformOutput::toHtml() from given
703 * frame parameters supplied by the Parser.
704 * @param array $frameParams The frame parameters
705 * @param string $query An optional query string to add to description page links
706 * @param Parser|null $parser
707 * @return array
709 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
710 $mtoParams = array();
711 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
712 $mtoParams['custom-url-link'] = $frameParams['link-url'];
713 if ( isset( $frameParams['link-target'] ) ) {
714 $mtoParams['custom-target-link'] = $frameParams['link-target'];
716 if ( $parser ) {
717 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
718 foreach ( $extLinkAttrs as $name => $val ) {
719 // Currently could include 'rel' and 'target'
720 $mtoParams['parser-extlink-' . $name] = $val;
723 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
724 $mtoParams['custom-title-link'] = self::normaliseSpecialPage( $frameParams['link-title'] );
725 } elseif ( !empty( $frameParams['no-link'] ) ) {
726 // No link
727 } else {
728 $mtoParams['desc-link'] = true;
729 $mtoParams['desc-query'] = $query;
731 return $mtoParams;
735 * Make HTML for a thumbnail including image, border and caption
736 * @param Title $title
737 * @param File|bool $file File object or false if it doesn't exist
738 * @param string $label
739 * @param string $alt
740 * @param string $align
741 * @param array $params
742 * @param bool $framed
743 * @param string $manualthumb
744 * @return string
746 public static function makeThumbLinkObj( Title $title, $file, $label = '', $alt,
747 $align = 'right', $params = array(), $framed = false, $manualthumb = ""
749 $frameParams = array(
750 'alt' => $alt,
751 'caption' => $label,
752 'align' => $align
754 if ( $framed ) {
755 $frameParams['framed'] = true;
757 if ( $manualthumb ) {
758 $frameParams['manualthumb'] = $manualthumb;
760 return self::makeThumbLink2( $title, $file, $frameParams, $params );
764 * @param Title $title
765 * @param File $file
766 * @param array $frameParams
767 * @param array $handlerParams
768 * @param bool $time
769 * @param string $query
770 * @return string
772 public static function makeThumbLink2( Title $title, $file, $frameParams = array(),
773 $handlerParams = array(), $time = false, $query = ""
775 $exists = $file && $file->exists();
777 # Shortcuts
778 $fp =& $frameParams;
779 $hp =& $handlerParams;
781 $page = isset( $hp['page'] ) ? $hp['page'] : false;
782 if ( !isset( $fp['align'] ) ) {
783 $fp['align'] = 'right';
785 if ( !isset( $fp['alt'] ) ) {
786 $fp['alt'] = '';
788 if ( !isset( $fp['title'] ) ) {
789 $fp['title'] = '';
791 if ( !isset( $fp['caption'] ) ) {
792 $fp['caption'] = '';
795 if ( empty( $hp['width'] ) ) {
796 // Reduce width for upright images when parameter 'upright' is used
797 $hp['width'] = isset( $fp['upright'] ) ? 130 : 180;
799 $thumb = false;
800 $noscale = false;
801 $manualthumb = false;
803 if ( !$exists ) {
804 $outerWidth = $hp['width'] + 2;
805 } else {
806 if ( isset( $fp['manualthumb'] ) ) {
807 # Use manually specified thumbnail
808 $manual_title = Title::makeTitleSafe( NS_FILE, $fp['manualthumb'] );
809 if ( $manual_title ) {
810 $manual_img = wfFindFile( $manual_title );
811 if ( $manual_img ) {
812 $thumb = $manual_img->getUnscaledThumb( $hp );
813 $manualthumb = true;
814 } else {
815 $exists = false;
818 } elseif ( isset( $fp['framed'] ) ) {
819 // Use image dimensions, don't scale
820 $thumb = $file->getUnscaledThumb( $hp );
821 $noscale = true;
822 } else {
823 # Do not present an image bigger than the source, for bitmap-style images
824 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
825 $srcWidth = $file->getWidth( $page );
826 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
827 $hp['width'] = $srcWidth;
829 $thumb = $file->transform( $hp );
832 if ( $thumb ) {
833 $outerWidth = $thumb->getWidth() + 2;
834 } else {
835 $outerWidth = $hp['width'] + 2;
839 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
840 # So we don't need to pass it here in $query. However, the URL for the
841 # zoom icon still needs it, so we make a unique query for it. See bug 14771
842 $url = $title->getLocalURL( $query );
843 if ( $page ) {
844 $url = wfAppendQuery( $url, array( 'page' => $page ) );
846 if ( $manualthumb
847 && !isset( $fp['link-title'] )
848 && !isset( $fp['link-url'] )
849 && !isset( $fp['no-link'] ) ) {
850 $fp['link-url'] = $url;
853 $s = "<div class=\"thumb t{$fp['align']}\">"
854 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
856 if ( !$exists ) {
857 $s .= self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
858 $zoomIcon = '';
859 } elseif ( !$thumb ) {
860 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
861 $zoomIcon = '';
862 } else {
863 if ( !$noscale && !$manualthumb ) {
864 self::processResponsiveImages( $file, $thumb, $hp );
866 $params = array(
867 'alt' => $fp['alt'],
868 'title' => $fp['title'],
869 'img-class' => ( isset( $fp['class'] ) && $fp['class'] !== ''
870 ? $fp['class'] . ' '
871 : '' ) . 'thumbimage'
873 $params = self::getImageLinkMTOParams( $fp, $query ) + $params;
874 $s .= $thumb->toHtml( $params );
875 if ( isset( $fp['framed'] ) ) {
876 $zoomIcon = "";
877 } else {
878 $zoomIcon = Html::rawElement( 'div', array( 'class' => 'magnify' ),
879 Html::rawElement( 'a', array(
880 'href' => $url,
881 'class' => 'internal',
882 'title' => wfMessage( 'thumbnail-more' )->text() ),
883 "" ) );
886 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
887 return str_replace( "\n", ' ', $s );
891 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
892 * applicable.
894 * @param File $file
895 * @param MediaTransformOutput $thumb
896 * @param array $hp Image parameters
898 public static function processResponsiveImages( $file, $thumb, $hp ) {
899 global $wgResponsiveImages;
900 if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
901 $hp15 = $hp;
902 $hp15['width'] = round( $hp['width'] * 1.5 );
903 $hp20 = $hp;
904 $hp20['width'] = $hp['width'] * 2;
905 if ( isset( $hp['height'] ) ) {
906 $hp15['height'] = round( $hp['height'] * 1.5 );
907 $hp20['height'] = $hp['height'] * 2;
910 $thumb15 = $file->transform( $hp15 );
911 $thumb20 = $file->transform( $hp20 );
912 if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
913 $thumb->responsiveUrls['1.5'] = $thumb15->getUrl();
915 if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
916 $thumb->responsiveUrls['2'] = $thumb20->getUrl();
922 * Make a "broken" link to an image
924 * @param Title $title
925 * @param string $label Link label (plain text)
926 * @param string $query Query string
927 * @param string $unused1 Unused parameter kept for b/c
928 * @param string $unused2 Unused parameter kept for b/c
929 * @param bool $time A file of a certain timestamp was requested
930 * @return string
932 public static function makeBrokenImageLinkObj( $title, $label = '',
933 $query = '', $unused1 = '', $unused2 = '', $time = false
935 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
936 if ( !$title instanceof Title ) {
937 return "<!-- ERROR -->" . htmlspecialchars( $label );
939 wfProfileIn( __METHOD__ );
940 if ( $label == '' ) {
941 $label = $title->getPrefixedText();
943 $encLabel = htmlspecialchars( $label );
944 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
946 if ( ( $wgUploadMissingFileUrl || $wgUploadNavigationUrl || $wgEnableUploads )
947 && !$currentExists
949 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
951 if ( $redir ) {
952 wfProfileOut( __METHOD__ );
953 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
956 $href = self::getUploadUrl( $title, $query );
958 wfProfileOut( __METHOD__ );
959 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
960 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES ) . '">' .
961 $encLabel . '</a>';
964 wfProfileOut( __METHOD__ );
965 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
969 * Get the URL to upload a certain file
971 * @param Title $destFile Title object of the file to upload
972 * @param string $query Urlencoded query string to prepend
973 * @return string Urlencoded URL
975 protected static function getUploadUrl( $destFile, $query = '' ) {
976 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
977 $q = 'wpDestFile=' . $destFile->getPartialURL();
978 if ( $query != '' ) {
979 $q .= '&' . $query;
982 if ( $wgUploadMissingFileUrl ) {
983 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
984 } elseif ( $wgUploadNavigationUrl ) {
985 return wfAppendQuery( $wgUploadNavigationUrl, $q );
986 } else {
987 $upload = SpecialPage::getTitleFor( 'Upload' );
988 return $upload->getLocalURL( $q );
993 * Create a direct link to a given uploaded file.
995 * @param Title $title
996 * @param string $html Pre-sanitized HTML
997 * @param string $time MW timestamp of file creation time
998 * @return string HTML
1000 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
1001 $img = wfFindFile( $title, array( 'time' => $time ) );
1002 return self::makeMediaLinkFile( $title, $img, $html );
1006 * Create a direct link to a given uploaded file.
1007 * This will make a broken link if $file is false.
1009 * @param Title $title
1010 * @param File|bool $file File object or false
1011 * @param string $html Pre-sanitized HTML
1012 * @return string HTML
1014 * @todo Handle invalid or missing images better.
1016 public static function makeMediaLinkFile( Title $title, $file, $html = '' ) {
1017 if ( $file && $file->exists() ) {
1018 $url = $file->getURL();
1019 $class = 'internal';
1020 } else {
1021 $url = self::getUploadUrl( $title );
1022 $class = 'new';
1025 $alt = $title->getText();
1026 if ( $html == '' ) {
1027 $html = $alt;
1030 $ret = '';
1031 $attribs = array(
1032 'href' => $url,
1033 'class' => $class,
1034 'title' => $alt
1037 if ( !wfRunHooks( 'LinkerMakeMediaLinkFile',
1038 array( $title, $file, &$html, &$attribs, &$ret ) ) ) {
1039 wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
1040 . "with url {$url} and text {$html} to {$ret}\n", true );
1041 return $ret;
1044 return Html::rawElement( 'a', $attribs, $html );
1048 * Make a link to a special page given its name and, optionally,
1049 * a message key from the link text.
1050 * Usage example: Linker::specialLink( 'Recentchanges' )
1052 * @param string $name
1053 * @param string $key
1054 * @return string
1056 public static function specialLink( $name, $key = '' ) {
1057 if ( $key == '' ) {
1058 $key = strtolower( $name );
1061 return self::linkKnown( SpecialPage::getTitleFor( $name ), wfMessage( $key )->text() );
1065 * Make an external link
1066 * @param string $url URL to link to
1067 * @param string $text Text of link
1068 * @param bool $escape Do we escape the link text?
1069 * @param string $linktype Type of external link. Gets added to the classes
1070 * @param array $attribs Array of extra attributes to <a>
1071 * @param Title|null $title Title object used for title specific link attributes
1072 * @return string
1074 public static function makeExternalLink( $url, $text, $escape = true,
1075 $linktype = '', $attribs = array(), $title = null
1077 global $wgTitle;
1078 $class = "external";
1079 if ( $linktype ) {
1080 $class .= " $linktype";
1082 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1083 $class .= " {$attribs['class']}";
1085 $attribs['class'] = $class;
1087 if ( $escape ) {
1088 $text = htmlspecialchars( $text );
1091 if ( !$title ) {
1092 $title = $wgTitle;
1094 $attribs['rel'] = Parser::getExternalLinkRel( $url, $title );
1095 $link = '';
1096 $success = wfRunHooks( 'LinkerMakeExternalLink',
1097 array( &$url, &$text, &$link, &$attribs, $linktype ) );
1098 if ( !$success ) {
1099 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
1100 . "with url {$url} and text {$text} to {$link}\n", true );
1101 return $link;
1103 $attribs['href'] = $url;
1104 return Html::rawElement( 'a', $attribs, $text );
1108 * Make user link (or user contributions for unregistered users)
1109 * @param int $userId User id in database.
1110 * @param string $userName User name in database.
1111 * @param string $altUserName Text to display instead of the user name (optional)
1112 * @return string HTML fragment
1113 * @since 1.19 Method exists for a long time. $altUserName was added in 1.19.
1115 public static function userLink( $userId, $userName, $altUserName = false ) {
1116 $classes = 'mw-userlink';
1117 if ( $userId == 0 ) {
1118 $page = SpecialPage::getTitleFor( 'Contributions', $userName );
1119 if ( $altUserName === false ) {
1120 $altUserName = IP::prettifyIP( $userName );
1122 $classes .= ' mw-anonuserlink'; // Separate link class for anons (bug 43179)
1123 } else {
1124 $page = Title::makeTitle( NS_USER, $userName );
1127 return self::link(
1128 $page,
1129 htmlspecialchars( $altUserName !== false ? $altUserName : $userName ),
1130 array( 'class' => $classes )
1135 * Generate standard user tool links (talk, contributions, block link, etc.)
1137 * @param int $userId User identifier
1138 * @param string $userText User name or IP address
1139 * @param bool $redContribsWhenNoEdits Should the contributions link be
1140 * red if the user has no edits?
1141 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
1142 * and Linker::TOOL_LINKS_EMAIL).
1143 * @param int $edits User edit count (optional, for performance)
1144 * @return string HTML fragment
1146 public static function userToolLinks(
1147 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1149 global $wgUser, $wgDisableAnonTalk, $wgLang;
1150 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1151 $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1152 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1154 $items = array();
1155 if ( $talkable ) {
1156 $items[] = self::userTalkLink( $userId, $userText );
1158 if ( $userId ) {
1159 // check if the user has an edit
1160 $attribs = array();
1161 if ( $redContribsWhenNoEdits ) {
1162 if ( intval( $edits ) === 0 && $edits !== 0 ) {
1163 $user = User::newFromId( $userId );
1164 $edits = $user->getEditCount();
1166 if ( $edits === 0 ) {
1167 $attribs['class'] = 'new';
1170 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1172 $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1174 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1175 $items[] = self::blockLink( $userId, $userText );
1178 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1179 $items[] = self::emailLink( $userId, $userText );
1182 wfRunHooks( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1184 if ( $items ) {
1185 return wfMessage( 'word-separator' )->plain()
1186 . '<span class="mw-usertoollinks">'
1187 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1188 . '</span>';
1189 } else {
1190 return '';
1195 * Alias for userToolLinks( $userId, $userText, true );
1196 * @param int $userId User identifier
1197 * @param string $userText User name or IP address
1198 * @param int $edits User edit count (optional, for performance)
1199 * @return string
1201 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1202 return self::userToolLinks( $userId, $userText, true, 0, $edits );
1206 * @param int $userId User id in database.
1207 * @param string $userText User name in database.
1208 * @return string HTML fragment with user talk link
1210 public static function userTalkLink( $userId, $userText ) {
1211 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1212 $userTalkLink = self::link( $userTalkPage, wfMessage( 'talkpagelinktext' )->escaped() );
1213 return $userTalkLink;
1217 * @param int $userId Userid
1218 * @param string $userText User name in database.
1219 * @return string HTML fragment with block link
1221 public static function blockLink( $userId, $userText ) {
1222 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1223 $blockLink = self::link( $blockPage, wfMessage( 'blocklink' )->escaped() );
1224 return $blockLink;
1228 * @param int $userId Userid
1229 * @param string $userText User name in database.
1230 * @return string HTML fragment with e-mail user link
1232 public static function emailLink( $userId, $userText ) {
1233 $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1234 $emailLink = self::link( $emailPage, wfMessage( 'emaillink' )->escaped() );
1235 return $emailLink;
1239 * Generate a user link if the current user is allowed to view it
1240 * @param Revision $rev
1241 * @param bool $isPublic Show only if all users can see it
1242 * @return string HTML fragment
1244 public static function revUserLink( $rev, $isPublic = false ) {
1245 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1246 $link = wfMessage( 'rev-deleted-user' )->escaped();
1247 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1248 $link = self::userLink( $rev->getUser( Revision::FOR_THIS_USER ),
1249 $rev->getUserText( Revision::FOR_THIS_USER ) );
1250 } else {
1251 $link = wfMessage( 'rev-deleted-user' )->escaped();
1253 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1254 return '<span class="history-deleted">' . $link . '</span>';
1256 return $link;
1260 * Generate a user tool link cluster if the current user is allowed to view it
1261 * @param Revision $rev
1262 * @param bool $isPublic Show only if all users can see it
1263 * @return string HTML
1265 public static function revUserTools( $rev, $isPublic = false ) {
1266 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1267 $link = wfMessage( 'rev-deleted-user' )->escaped();
1268 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1269 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1270 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1271 $link = self::userLink( $userId, $userText )
1272 . wfMessage( 'word-separator' )->plain()
1273 . self::userToolLinks( $userId, $userText );
1274 } else {
1275 $link = wfMessage( 'rev-deleted-user' )->escaped();
1277 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1278 return ' <span class="history-deleted">' . $link . '</span>';
1280 return $link;
1284 * This function is called by all recent changes variants, by the page history,
1285 * and by the user contributions list. It is responsible for formatting edit
1286 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1287 * auto-generated comments (from section editing) and formats [[wikilinks]].
1289 * @author Erik Moeller <moeller@scireview.de>
1291 * Note: there's not always a title to pass to this function.
1292 * Since you can't set a default parameter for a reference, I've turned it
1293 * temporarily to a value pass. Should be adjusted further. --brion
1295 * @param string $comment
1296 * @param Title|null $title Title object (to generate link to the section in autocomment) or null
1297 * @param bool $local Whether section links should refer to local page
1298 * @return mixed|string
1300 public static function formatComment( $comment, $title = null, $local = false ) {
1301 wfProfileIn( __METHOD__ );
1303 # Sanitize text a bit:
1304 $comment = str_replace( "\n", " ", $comment );
1305 # Allow HTML entities (for bug 13815)
1306 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1308 # Render autocomments and make links:
1309 $comment = self::formatAutocomments( $comment, $title, $local );
1310 $comment = self::formatLinksInComment( $comment, $title, $local );
1312 wfProfileOut( __METHOD__ );
1313 return $comment;
1317 * Converts autogenerated comments in edit summaries into section links.
1318 * The pattern for autogen comments is / * foo * /, which makes for
1319 * some nasty regex.
1320 * We look for all comments, match any text before and after the comment,
1321 * add a separator where needed and format the comment itself with CSS
1322 * Called by Linker::formatComment.
1324 * @param string $comment Comment text
1325 * @param Title|null $title An optional title object used to links to sections
1326 * @param bool $local Whether section links should refer to local page
1327 * @return string Formatted comment
1329 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1330 return preg_replace_callback(
1331 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1332 function ( $match ) use ( $title, $local ) {
1333 global $wgLang;
1335 $pre = $match[1];
1336 $auto = $match[2];
1337 $post = $match[3];
1338 $comment = null;
1339 wfRunHooks( 'FormatAutocomments', array( &$comment, $pre, $auto, $post, $title, $local ) );
1340 if ( $comment === null ) {
1341 $link = '';
1342 if ( $title ) {
1343 $section = $auto;
1344 # Remove links that a user may have manually put in the autosummary
1345 # This could be improved by copying as much of Parser::stripSectionName as desired.
1346 $section = str_replace( '[[:', '', $section );
1347 $section = str_replace( '[[', '', $section );
1348 $section = str_replace( ']]', '', $section );
1350 $section = Sanitizer::normalizeSectionNameWhitespace( $section ); # bug 22784
1351 if ( $local ) {
1352 $sectionTitle = Title::newFromText( '#' . $section );
1353 } else {
1354 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1355 $title->getDBkey(), $section );
1357 if ( $sectionTitle ) {
1358 $link = Linker::link( $sectionTitle,
1359 $wgLang->getArrow(), array(), array(),
1360 'noclasses' );
1361 } else {
1362 $link = '';
1365 if ( $pre ) {
1366 # written summary $presep autocomment (summary /* section */)
1367 $pre .= wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1369 if ( $post ) {
1370 # autocomment $postsep written summary (/* section */ summary)
1371 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1373 $auto = '<span class="autocomment">' . $auto . '</span>';
1374 $comment = $pre . $link . $wgLang->getDirMark()
1375 . '<span dir="auto">' . $auto . $post . '</span>';
1377 return $comment;
1379 $comment
1384 * Formats wiki links and media links in text; all other wiki formatting
1385 * is ignored
1387 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1388 * @param string $comment Text to format links in
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 * @return string
1393 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1394 return preg_replace_callback(
1396 \[\[
1397 :? # ignore optional leading colon
1398 ([^\]|]+) # 1. link target; page names cannot include ] or |
1399 (?:\|
1400 # 2. a pipe-separated substring; only the last is captured
1401 # Stop matching at | and ]] without relying on backtracking.
1402 ((?:]?[^\]|])*+)
1404 \]\]
1405 ([^[]*) # 3. link trail (the text up until the next link)
1406 /x',
1407 function ( $match ) use ( $title, $local ) {
1408 global $wgContLang;
1410 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1411 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1413 $comment = $match[0];
1415 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1416 if ( strpos( $match[1], '%' ) !== false ) {
1417 $match[1] = str_replace(
1418 array( '<', '>' ),
1419 array( '&lt;', '&gt;' ),
1420 rawurldecode( $match[1] )
1424 # Handle link renaming [[foo|text]] will show link as "text"
1425 if ( $match[2] != "" ) {
1426 $text = $match[2];
1427 } else {
1428 $text = $match[1];
1430 $submatch = array();
1431 $thelink = null;
1432 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1433 # Media link; trail not supported.
1434 $linkRegexp = '/\[\[(.*?)\]\]/';
1435 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1436 if ( $title ) {
1437 $thelink = Linker::makeMediaLinkObj( $title, $text );
1439 } else {
1440 # Other kind of link
1441 if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1442 $trail = $submatch[1];
1443 } else {
1444 $trail = "";
1446 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1447 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1448 $match[1] = substr( $match[1], 1 );
1450 list( $inside, $trail ) = Linker::splitTrail( $trail );
1452 $linkText = $text;
1453 $linkTarget = Linker::normalizeSubpageLink( $title, $match[1], $linkText );
1455 $target = Title::newFromText( $linkTarget );
1456 if ( $target ) {
1457 if ( $target->getText() == '' && !$target->isExternal()
1458 && !$local && $title
1460 $newTarget = clone ( $title );
1461 $newTarget->setFragment( '#' . $target->getFragment() );
1462 $target = $newTarget;
1464 $thelink = Linker::link(
1465 $target,
1466 $linkText . $inside
1467 ) . $trail;
1470 if ( $thelink ) {
1471 // If the link is still valid, go ahead and replace it in!
1472 $comment = preg_replace(
1473 $linkRegexp,
1474 StringUtils::escapeRegexReplacement( $thelink ),
1475 $comment,
1480 return $comment;
1482 $comment
1487 * @param Title $contextTitle
1488 * @param string $target
1489 * @param string $text
1490 * @return string
1492 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1493 # Valid link forms:
1494 # Foobar -- normal
1495 # :Foobar -- override special treatment of prefix (images, language links)
1496 # /Foobar -- convert to CurrentPage/Foobar
1497 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1498 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1499 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1501 wfProfileIn( __METHOD__ );
1502 $ret = $target; # default return value is no change
1504 # Some namespaces don't allow subpages,
1505 # so only perform processing if subpages are allowed
1506 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1507 $hash = strpos( $target, '#' );
1508 if ( $hash !== false ) {
1509 $suffix = substr( $target, $hash );
1510 $target = substr( $target, 0, $hash );
1511 } else {
1512 $suffix = '';
1514 # bug 7425
1515 $target = trim( $target );
1516 # Look at the first character
1517 if ( $target != '' && $target[0] === '/' ) {
1518 # / at end means we don't want the slash to be shown
1519 $m = array();
1520 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1521 if ( $trailingSlashes ) {
1522 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1523 } else {
1524 $noslash = substr( $target, 1 );
1527 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1528 if ( $text === '' ) {
1529 $text = $target . $suffix;
1530 } # this might be changed for ugliness reasons
1531 } else {
1532 # check for .. subpage backlinks
1533 $dotdotcount = 0;
1534 $nodotdot = $target;
1535 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1536 ++$dotdotcount;
1537 $nodotdot = substr( $nodotdot, 3 );
1539 if ( $dotdotcount > 0 ) {
1540 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1541 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1542 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1543 # / at the end means don't show full path
1544 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1545 $nodotdot = substr( $nodotdot, 0, -1 );
1546 if ( $text === '' ) {
1547 $text = $nodotdot . $suffix;
1550 $nodotdot = trim( $nodotdot );
1551 if ( $nodotdot != '' ) {
1552 $ret .= '/' . $nodotdot;
1554 $ret .= $suffix;
1560 wfProfileOut( __METHOD__ );
1561 return $ret;
1565 * Wrap a comment in standard punctuation and formatting if
1566 * it's non-empty, otherwise return empty string.
1568 * @param string $comment
1569 * @param Title|null $title Title object (to generate link to section in autocomment) or null
1570 * @param bool $local Whether section links should refer to local page
1572 * @return string
1574 public static function commentBlock( $comment, $title = null, $local = false ) {
1575 // '*' used to be the comment inserted by the software way back
1576 // in antiquity in case none was provided, here for backwards
1577 // compatibility, acc. to brion -ævar
1578 if ( $comment == '' || $comment == '*' ) {
1579 return '';
1580 } else {
1581 $formatted = self::formatComment( $comment, $title, $local );
1582 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1583 return " <span class=\"comment\">$formatted</span>";
1588 * Wrap and format the given revision's comment block, if the current
1589 * user is allowed to view it.
1591 * @param Revision $rev
1592 * @param bool $local Whether section links should refer to local page
1593 * @param bool $isPublic Show only if all users can see it
1594 * @return string HTML fragment
1596 public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1597 if ( $rev->getRawComment() == "" ) {
1598 return "";
1600 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1601 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1602 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1603 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1604 $rev->getTitle(), $local );
1605 } else {
1606 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1608 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1609 return " <span class=\"history-deleted\">$block</span>";
1611 return $block;
1615 * @param int $size
1616 * @return string
1618 public static function formatRevisionSize( $size ) {
1619 if ( $size == 0 ) {
1620 $stxt = wfMessage( 'historyempty' )->escaped();
1621 } else {
1622 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1623 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1625 return "<span class=\"history-size\">$stxt</span>";
1629 * Add another level to the Table of Contents
1631 * @return string
1633 public static function tocIndent() {
1634 return "\n<ul>";
1638 * Finish one or more sublevels on the Table of Contents
1640 * @param int $level
1641 * @return string
1643 public static function tocUnindent( $level ) {
1644 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1648 * parameter level defines if we are on an indentation level
1650 * @param string $anchor
1651 * @param string $tocline
1652 * @param string $tocnumber
1653 * @param string $level
1654 * @param string|bool $sectionIndex
1655 * @return string
1657 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1658 $classes = "toclevel-$level";
1659 if ( $sectionIndex !== false ) {
1660 $classes .= " tocsection-$sectionIndex";
1662 return "\n<li class=\"$classes\"><a href=\"#" .
1663 $anchor . '"><span class="tocnumber">' .
1664 $tocnumber . '</span> <span class="toctext">' .
1665 $tocline . '</span></a>';
1669 * End a Table Of Contents line.
1670 * tocUnindent() will be used instead if we're ending a line below
1671 * the new level.
1672 * @return string
1674 public static function tocLineEnd() {
1675 return "</li>\n";
1679 * Wraps the TOC in a table and provides the hide/collapse javascript.
1681 * @param string $toc Html of the Table Of Contents
1682 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1683 * @return string Full html of the TOC
1685 public static function tocList( $toc, $lang = false ) {
1686 $lang = wfGetLangObj( $lang );
1687 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1689 return '<div id="toc" class="toc">'
1690 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1691 . $toc
1692 . "</ul>\n</div>\n";
1696 * Generate a table of contents from a section tree
1697 * Currently unused.
1699 * @param array $tree Return value of ParserOutput::getSections()
1700 * @return string HTML fragment
1702 public static function generateTOC( $tree ) {
1703 $toc = '';
1704 $lastLevel = 0;
1705 foreach ( $tree as $section ) {
1706 if ( $section['toclevel'] > $lastLevel ) {
1707 $toc .= self::tocIndent();
1708 } elseif ( $section['toclevel'] < $lastLevel ) {
1709 $toc .= self::tocUnindent(
1710 $lastLevel - $section['toclevel'] );
1711 } else {
1712 $toc .= self::tocLineEnd();
1715 $toc .= self::tocLine( $section['anchor'],
1716 $section['line'], $section['number'],
1717 $section['toclevel'], $section['index'] );
1718 $lastLevel = $section['toclevel'];
1720 $toc .= self::tocLineEnd();
1721 return self::tocList( $toc );
1725 * Create a headline for content
1727 * @param int $level The level of the headline (1-6)
1728 * @param string $attribs Any attributes for the headline, starting with
1729 * a space and ending with '>'
1730 * This *must* be at least '>' for no attribs
1731 * @param string $anchor The anchor to give the headline (the bit after the #)
1732 * @param string $html Html for the text of the header
1733 * @param string $link HTML to add for the section edit link
1734 * @param bool|string $legacyAnchor A second, optional anchor to give for
1735 * backward compatibility (false to omit)
1737 * @return string HTML headline
1739 public static function makeHeadline( $level, $attribs, $anchor, $html,
1740 $link, $legacyAnchor = false
1742 $ret = "<h$level$attribs"
1743 . "<span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1744 . $link
1745 . "</h$level>";
1746 if ( $legacyAnchor !== false ) {
1747 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1749 return $ret;
1753 * Split a link trail, return the "inside" portion and the remainder of the trail
1754 * as a two-element array
1755 * @param string $trail
1756 * @return array
1758 static function splitTrail( $trail ) {
1759 global $wgContLang;
1760 $regex = $wgContLang->linkTrail();
1761 $inside = '';
1762 if ( $trail !== '' ) {
1763 $m = array();
1764 if ( preg_match( $regex, $trail, $m ) ) {
1765 $inside = $m[1];
1766 $trail = $m[2];
1769 return array( $inside, $trail );
1773 * Generate a rollback link for a given revision. Currently it's the
1774 * caller's responsibility to ensure that the revision is the top one. If
1775 * it's not, of course, the user will get an error message.
1777 * If the calling page is called with the parameter &bot=1, all rollback
1778 * links also get that parameter. It causes the edit itself and the rollback
1779 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1780 * changes, so this allows sysops to combat a busy vandal without bothering
1781 * other users.
1783 * If the option verify is set this function will return the link only in case the
1784 * revision can be reverted. Please note that due to performance limitations
1785 * it might be assumed that a user isn't the only contributor of a page while
1786 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1787 * work if $wgShowRollbackEditCount is disabled, so this can only function
1788 * as an additional check.
1790 * If the option noBrackets is set the rollback link wont be enclosed in []
1792 * @param Revision $rev
1793 * @param IContextSource $context Context to use or null for the main context.
1794 * @param array $options
1795 * @return string
1797 public static function generateRollback( $rev, IContextSource $context = null,
1798 $options = array( 'verify' )
1800 if ( $context === null ) {
1801 $context = RequestContext::getMain();
1804 $editCount = false;
1805 if ( in_array( 'verify', $options ) ) {
1806 $editCount = self::getRollbackEditCount( $rev, true );
1807 if ( $editCount === false ) {
1808 return '';
1812 $inner = self::buildRollbackLink( $rev, $context, $editCount );
1814 if ( !in_array( 'noBrackets', $options ) ) {
1815 $inner = $context->msg( 'brackets' )->rawParams( $inner )->plain();
1818 return '<span class="mw-rollback-link">' . $inner . '</span>';
1822 * This function will return the number of revisions which a rollback
1823 * would revert and, if $verify is set it will verify that a revision
1824 * can be reverted (that the user isn't the only contributor and the
1825 * revision we might rollback to isn't deleted). These checks can only
1826 * function as an additional check as this function only checks against
1827 * the last $wgShowRollbackEditCount edits.
1829 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1830 * is set and the user is the only contributor of the page.
1832 * @param Revision $rev
1833 * @param bool $verify Try to verify that this revision can really be rolled back
1834 * @return int|bool|null
1836 public static function getRollbackEditCount( $rev, $verify ) {
1837 global $wgShowRollbackEditCount;
1838 if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
1839 // Nothing has happened, indicate this by returning 'null'
1840 return null;
1843 $dbr = wfGetDB( DB_SLAVE );
1845 // Up to the value of $wgShowRollbackEditCount revisions are counted
1846 $res = $dbr->select(
1847 'revision',
1848 array( 'rev_user_text', 'rev_deleted' ),
1849 // $rev->getPage() returns null sometimes
1850 array( 'rev_page' => $rev->getTitle()->getArticleID() ),
1851 __METHOD__,
1852 array(
1853 'USE INDEX' => array( 'revision' => 'page_timestamp' ),
1854 'ORDER BY' => 'rev_timestamp DESC',
1855 'LIMIT' => $wgShowRollbackEditCount + 1
1859 $editCount = 0;
1860 $moreRevs = false;
1861 foreach ( $res as $row ) {
1862 if ( $rev->getRawUserText() != $row->rev_user_text ) {
1863 if ( $verify &&
1864 ( $row->rev_deleted & Revision::DELETED_TEXT
1865 || $row->rev_deleted & Revision::DELETED_USER
1866 ) ) {
1867 // If the user or the text of the revision we might rollback
1868 // to is deleted in some way we can't rollback. Similar to
1869 // the sanity checks in WikiPage::commitRollback.
1870 return false;
1872 $moreRevs = true;
1873 break;
1875 $editCount++;
1878 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1879 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1880 // and there weren't any other revisions. That means that the current user is the only
1881 // editor, so we can't rollback
1882 return false;
1884 return $editCount;
1888 * Build a raw rollback link, useful for collections of "tool" links
1890 * @param Revision $rev
1891 * @param IContextSource|null $context Context to use or null for the main context.
1892 * @param int $editCount Number of edits that would be reverted
1893 * @return string HTML fragment
1895 public static function buildRollbackLink( $rev, IContextSource $context = null,
1896 $editCount = false
1898 global $wgShowRollbackEditCount, $wgMiserMode;
1900 // To config which pages are effected by miser mode
1901 $disableRollbackEditCountSpecialPage = array( 'Recentchanges', 'Watchlist' );
1903 if ( $context === null ) {
1904 $context = RequestContext::getMain();
1907 $title = $rev->getTitle();
1908 $query = array(
1909 'action' => 'rollback',
1910 'from' => $rev->getUserText(),
1911 'token' => $context->getUser()->getEditToken( array(
1912 $title->getPrefixedText(),
1913 $rev->getUserText()
1914 ) ),
1916 if ( $context->getRequest()->getBool( 'bot' ) ) {
1917 $query['bot'] = '1';
1918 $query['hidediff'] = '1'; // bug 15999
1921 $disableRollbackEditCount = false;
1922 if ( $wgMiserMode ) {
1923 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1924 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1925 $disableRollbackEditCount = true;
1926 break;
1931 if ( !$disableRollbackEditCount
1932 && is_int( $wgShowRollbackEditCount )
1933 && $wgShowRollbackEditCount > 0
1935 if ( !is_numeric( $editCount ) ) {
1936 $editCount = self::getRollbackEditCount( $rev, false );
1939 if ( $editCount > $wgShowRollbackEditCount ) {
1940 $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )
1941 ->numParams( $wgShowRollbackEditCount )->parse();
1942 } else {
1943 $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1946 return self::link(
1947 $title,
1948 $editCount_output,
1949 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1950 $query,
1951 array( 'known', 'noclasses' )
1953 } else {
1954 return self::link(
1955 $title,
1956 $context->msg( 'rollbacklink' )->escaped(),
1957 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1958 $query,
1959 array( 'known', 'noclasses' )
1965 * Returns HTML for the "templates used on this page" list.
1967 * Make an HTML list of templates, and then add a "More..." link at
1968 * the bottom. If $more is null, do not add a "More..." link. If $more
1969 * is a Title, make a link to that title and use it. If $more is a string,
1970 * directly paste it in as the link (escaping needs to be done manually).
1971 * Finally, if $more is a Message, call toString().
1973 * @param array $templates Array of templates from Article::getUsedTemplate or similar
1974 * @param bool $preview Whether this is for a preview
1975 * @param bool $section Whether this is for a section edit
1976 * @param Title|Message|string|null $more An escaped link for "More..." of the templates
1977 * @return string HTML output
1979 public static function formatTemplates( $templates, $preview = false,
1980 $section = false, $more = null
1982 global $wgLang;
1983 wfProfileIn( __METHOD__ );
1985 $outText = '';
1986 if ( count( $templates ) > 0 ) {
1987 # Do a batch existence check
1988 $batch = new LinkBatch;
1989 foreach ( $templates as $title ) {
1990 $batch->addObj( $title );
1992 $batch->execute();
1994 # Construct the HTML
1995 $outText = '<div class="mw-templatesUsedExplanation">';
1996 if ( $preview ) {
1997 $outText .= wfMessage( 'templatesusedpreview' )->numParams( count( $templates ) )
1998 ->parseAsBlock();
1999 } elseif ( $section ) {
2000 $outText .= wfMessage( 'templatesusedsection' )->numParams( count( $templates ) )
2001 ->parseAsBlock();
2002 } else {
2003 $outText .= wfMessage( 'templatesused' )->numParams( count( $templates ) )
2004 ->parseAsBlock();
2006 $outText .= "</div><ul>\n";
2008 usort( $templates, 'Title::compare' );
2009 foreach ( $templates as $titleObj ) {
2010 $protected = '';
2011 $restrictions = $titleObj->getRestrictions( 'edit' );
2012 if ( $restrictions ) {
2013 // Check backwards-compatible messages
2014 $msg = null;
2015 if ( $restrictions === array( 'sysop' ) ) {
2016 $msg = wfMessage( 'template-protected' );
2017 } elseif ( $restrictions === array( 'autoconfirmed' ) ) {
2018 $msg = wfMessage( 'template-semiprotected' );
2020 if ( $msg && !$msg->isDisabled() ) {
2021 $protected = $msg->parse();
2022 } else {
2023 // Construct the message from restriction-level-*
2024 // e.g. restriction-level-sysop, restriction-level-autoconfirmed
2025 $msgs = array();
2026 foreach ( $restrictions as $r ) {
2027 $msgs[] = wfMessage( "restriction-level-$r" )->parse();
2029 $protected = wfMessage( 'parentheses' )
2030 ->rawParams( $wgLang->commaList( $msgs ) )->escaped();
2033 if ( $titleObj->quickUserCan( 'edit' ) ) {
2034 $editLink = self::link(
2035 $titleObj,
2036 wfMessage( 'editlink' )->text(),
2037 array(),
2038 array( 'action' => 'edit' )
2040 } else {
2041 $editLink = self::link(
2042 $titleObj,
2043 wfMessage( 'viewsourcelink' )->text(),
2044 array(),
2045 array( 'action' => 'edit' )
2048 $outText .= '<li>' . self::link( $titleObj )
2049 . wfMessage( 'word-separator' )->escaped()
2050 . wfMessage( 'parentheses' )->rawParams( $editLink )->escaped()
2051 . wfMessage( 'word-separator' )->escaped()
2052 . $protected . '</li>';
2055 if ( $more instanceof Title ) {
2056 $outText .= '<li>' . self::link( $more, wfMessage( 'moredotdotdot' ) ) . '</li>';
2057 } elseif ( $more ) {
2058 $outText .= "<li>$more</li>";
2061 $outText .= '</ul>';
2063 wfProfileOut( __METHOD__ );
2064 return $outText;
2068 * Returns HTML for the "hidden categories on this page" list.
2070 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
2071 * or similar
2072 * @return string HTML output
2074 public static function formatHiddenCategories( $hiddencats ) {
2075 wfProfileIn( __METHOD__ );
2077 $outText = '';
2078 if ( count( $hiddencats ) > 0 ) {
2079 # Construct the HTML
2080 $outText = '<div class="mw-hiddenCategoriesExplanation">';
2081 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
2082 $outText .= "</div><ul>\n";
2084 foreach ( $hiddencats as $titleObj ) {
2085 # If it's hidden, it must exist - no need to check with a LinkBatch
2086 $outText .= '<li>'
2087 . self::link( $titleObj, null, array(), array(), 'known' )
2088 . "</li>\n";
2090 $outText .= '</ul>';
2092 wfProfileOut( __METHOD__ );
2093 return $outText;
2097 * Format a size in bytes for output, using an appropriate
2098 * unit (B, KB, MB or GB) according to the magnitude in question
2100 * @param int $size Size to format
2101 * @return string
2103 public static function formatSize( $size ) {
2104 global $wgLang;
2105 return htmlspecialchars( $wgLang->formatSize( $size ) );
2109 * Given the id of an interface element, constructs the appropriate title
2110 * attribute from the system messages. (Note, this is usually the id but
2111 * isn't always, because sometimes the accesskey needs to go on a different
2112 * element than the id, for reverse-compatibility, etc.)
2114 * @param string $name Id of the element, minus prefixes.
2115 * @param string|null $options Null or the string 'withaccess' to add an access-
2116 * key hint
2117 * @return string Contents of the title attribute (which you must HTML-
2118 * escape), or false for no title attribute
2120 public static function titleAttrib( $name, $options = null ) {
2121 wfProfileIn( __METHOD__ );
2123 $message = wfMessage( "tooltip-$name" );
2125 if ( !$message->exists() ) {
2126 $tooltip = false;
2127 } else {
2128 $tooltip = $message->text();
2129 # Compatibility: formerly some tooltips had [alt-.] hardcoded
2130 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2131 # Message equal to '-' means suppress it.
2132 if ( $tooltip == '-' ) {
2133 $tooltip = false;
2137 if ( $options == 'withaccess' ) {
2138 $accesskey = self::accesskey( $name );
2139 if ( $accesskey !== false ) {
2140 // Should be build the same as in jquery.accessKeyLabel.js
2141 if ( $tooltip === false || $tooltip === '' ) {
2142 $tooltip = wfMessage( 'brackets', $accesskey )->text();
2143 } else {
2144 $tooltip .= wfMessage( 'word-separator' )->text();
2145 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
2150 wfProfileOut( __METHOD__ );
2151 return $tooltip;
2154 public static $accesskeycache;
2157 * Given the id of an interface element, constructs the appropriate
2158 * accesskey attribute from the system messages. (Note, this is usually
2159 * the id but isn't always, because sometimes the accesskey needs to go on
2160 * a different element than the id, for reverse-compatibility, etc.)
2162 * @param string $name Id of the element, minus prefixes.
2163 * @return string Contents of the accesskey attribute (which you must HTML-
2164 * escape), or false for no accesskey attribute
2166 public static function accesskey( $name ) {
2167 if ( isset( self::$accesskeycache[$name] ) ) {
2168 return self::$accesskeycache[$name];
2170 wfProfileIn( __METHOD__ );
2172 $message = wfMessage( "accesskey-$name" );
2174 if ( !$message->exists() ) {
2175 $accesskey = false;
2176 } else {
2177 $accesskey = $message->plain();
2178 if ( $accesskey === '' || $accesskey === '-' ) {
2179 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2180 # attribute, but this is broken for accesskey: that might be a useful
2181 # value.
2182 $accesskey = false;
2186 wfProfileOut( __METHOD__ );
2187 self::$accesskeycache[$name] = $accesskey;
2188 return self::$accesskeycache[$name];
2192 * Get a revision-deletion link, or disabled link, or nothing, depending
2193 * on user permissions & the settings on the revision.
2195 * Will use forward-compatible revision ID in the Special:RevDelete link
2196 * if possible, otherwise the timestamp-based ID which may break after
2197 * undeletion.
2199 * @param User $user
2200 * @param Revision $rev
2201 * @param Title $title
2202 * @return string HTML fragment
2204 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
2205 $canHide = $user->isAllowed( 'deleterevision' );
2206 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2207 return '';
2210 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
2211 return Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2212 } else {
2213 if ( $rev->getId() ) {
2214 // RevDelete links using revision ID are stable across
2215 // page deletion and undeletion; use when possible.
2216 $query = array(
2217 'type' => 'revision',
2218 'target' => $title->getPrefixedDBkey(),
2219 'ids' => $rev->getId()
2221 } else {
2222 // Older deleted entries didn't save a revision ID.
2223 // We have to refer to these by timestamp, ick!
2224 $query = array(
2225 'type' => 'archive',
2226 'target' => $title->getPrefixedDBkey(),
2227 'ids' => $rev->getTimestamp()
2230 return Linker::revDeleteLink( $query,
2231 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2236 * Creates a (show/hide) link for deleting revisions/log entries
2238 * @param array $query Query parameters to be passed to link()
2239 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2240 * @param bool $delete Set to true to use (show/hide) rather than (show)
2242 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2243 * span to allow for customization of appearance with CSS
2245 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
2246 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2247 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2248 $html = wfMessage( $msgKey )->escaped();
2249 $tag = $restricted ? 'strong' : 'span';
2250 $link = self::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
2251 return Xml::tags(
2252 $tag,
2253 array( 'class' => 'mw-revdelundel-link' ),
2254 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2259 * Creates a dead (show/hide) link for deleting revisions/log entries
2261 * @param bool $delete Set to true to use (show/hide) rather than (show)
2263 * @return string HTML text wrapped in a span to allow for customization
2264 * of appearance with CSS
2266 public static function revDeleteLinkDisabled( $delete = true ) {
2267 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2268 $html = wfMessage( $msgKey )->escaped();
2269 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2270 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), $htmlParentheses );
2273 /* Deprecated methods */
2276 * @deprecated since 1.16 Use link(); warnings since 1.21
2278 * Make a link for a title which may or may not be in the database. If you need to
2279 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
2280 * call to this will result in a DB query.
2282 * @param Title $nt The title object to make the link from, e.g. from Title::newFromText.
2283 * @param string $text Link text
2284 * @param string $query Optional query part
2285 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
2286 * be included in the link text. Other characters will be appended after
2287 * the end of the link.
2288 * @param string $prefix Optional prefix. As trail, only before instead of after.
2289 * @return string
2291 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
2292 wfDeprecated( __METHOD__, '1.21' );
2294 wfProfileIn( __METHOD__ );
2295 $query = wfCgiToArray( $query );
2296 list( $inside, $trail ) = self::splitTrail( $trail );
2297 if ( $text === '' ) {
2298 $text = self::linkText( $nt );
2301 $ret = self::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
2303 wfProfileOut( __METHOD__ );
2304 return $ret;
2308 * @deprecated since 1.16 Use link(); warnings since 1.21
2310 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
2311 * it doesn't have to do a database query. It's also valid for interwiki titles and special
2312 * pages.
2314 * @param Title $title Title object of target page
2315 * @param string $text Text to replace the title
2316 * @param string $query Link target
2317 * @param string $trail Text after link
2318 * @param string $prefix Text before link text
2319 * @param string $aprops Extra attributes to the a-element
2320 * @param string $style Style to apply - if empty, use getInternalLinkAttributesObj instead
2321 * @return string The a-element
2323 static function makeKnownLinkObj(
2324 $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = '', $style = ''
2326 wfDeprecated( __METHOD__, '1.21' );
2328 wfProfileIn( __METHOD__ );
2330 if ( $text == '' ) {
2331 $text = self::linkText( $title );
2333 $attribs = Sanitizer::mergeAttributes(
2334 Sanitizer::decodeTagAttributes( $aprops ),
2335 Sanitizer::decodeTagAttributes( $style )
2337 $query = wfCgiToArray( $query );
2338 list( $inside, $trail ) = self::splitTrail( $trail );
2340 $ret = self::link( $title, "$prefix$text$inside", $attribs, $query,
2341 array( 'known', 'noclasses' ) ) . $trail;
2343 wfProfileOut( __METHOD__ );
2344 return $ret;
2348 * Returns the attributes for the tooltip and access key.
2349 * @param string $name
2350 * @return array
2352 public static function tooltipAndAccesskeyAttribs( $name ) {
2353 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2354 # no attribute" instead of "output '' as value for attribute", this
2355 # would be three lines.
2356 $attribs = array(
2357 'title' => self::titleAttrib( $name, 'withaccess' ),
2358 'accesskey' => self::accesskey( $name )
2360 if ( $attribs['title'] === false ) {
2361 unset( $attribs['title'] );
2363 if ( $attribs['accesskey'] === false ) {
2364 unset( $attribs['accesskey'] );
2366 return $attribs;
2370 * Returns raw bits of HTML, use titleAttrib()
2371 * @param string $name
2372 * @param array|null $options
2373 * @return null|string
2375 public static function tooltip( $name, $options = null ) {
2376 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2377 # no attribute" instead of "output '' as value for attribute", this
2378 # would be two lines.
2379 $tooltip = self::titleAttrib( $name, $options );
2380 if ( $tooltip === false ) {
2381 return '';
2383 return Xml::expandAttributes( array(
2384 'title' => $tooltip
2385 ) );
2390 * @since 1.18
2392 class DummyLinker {
2395 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2396 * into static calls to the new Linker for backwards compatibility.
2398 * @param string $fname Name of called method
2399 * @param array $args Arguments to the method
2400 * @return mixed
2402 public function __call( $fname, $args ) {
2403 return call_user_func_array( array( 'Linker', $fname ), $args );