Merge "Fixed spacing"
[mediawiki.git] / includes / Linker.php
blob7865020415f8fcfb6a5b7da7c05b025c0049e4ea
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 * @return string
264 public static function linkKnown(
265 $target, $html = null, $customAttribs = array(),
266 $query = array(), $options = array( 'known', 'noclasses' )
268 return self::link( $target, $html, $customAttribs, $query, $options );
272 * Returns the Url used to link to a Title
274 * @param Title $target
275 * @param array $query query parameters
276 * @param array $options
277 * @return string
279 private static function linkUrl( $target, $query, $options ) {
280 wfProfileIn( __METHOD__ );
281 # We don't want to include fragments for broken links, because they
282 # generally make no sense.
283 if ( in_array( 'broken', $options ) && $target->hasFragment() ) {
284 $target = clone $target;
285 $target->setFragment( '' );
288 # If it's a broken link, add the appropriate query pieces, unless
289 # there's already an action specified, or unless 'edit' makes no sense
290 # (i.e., for a nonexistent special page).
291 if ( in_array( 'broken', $options ) && empty( $query['action'] )
292 && !$target->isSpecialPage() ) {
293 $query['action'] = 'edit';
294 $query['redlink'] = '1';
297 if ( in_array( 'http', $options ) ) {
298 $proto = PROTO_HTTP;
299 } elseif ( in_array( 'https', $options ) ) {
300 $proto = PROTO_HTTPS;
301 } else {
302 $proto = PROTO_RELATIVE;
305 $ret = $target->getLinkURL( $query, false, $proto );
306 wfProfileOut( __METHOD__ );
307 return $ret;
311 * Returns the array of attributes used when linking to the Title $target
313 * @param Title $target
314 * @param array $attribs
315 * @param array $options
317 * @return array
319 private static function linkAttribs( $target, $attribs, $options ) {
320 wfProfileIn( __METHOD__ );
321 global $wgUser;
322 $defaults = array();
324 if ( !in_array( 'noclasses', $options ) ) {
325 wfProfileIn( __METHOD__ . '-getClasses' );
326 # Now build the classes.
327 $classes = array();
329 if ( in_array( 'broken', $options ) ) {
330 $classes[] = 'new';
333 if ( $target->isExternal() ) {
334 $classes[] = 'extiw';
337 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
338 $colour = self::getLinkColour( $target, $wgUser->getStubThreshold() );
339 if ( $colour !== '' ) {
340 $classes[] = $colour; # mw-redirect or stub
343 if ( $classes != array() ) {
344 $defaults['class'] = implode( ' ', $classes );
346 wfProfileOut( __METHOD__ . '-getClasses' );
349 # Get a default title attribute.
350 if ( $target->getPrefixedText() == '' ) {
351 # A link like [[#Foo]]. This used to mean an empty title
352 # attribute, but that's silly. Just don't output a title.
353 } elseif ( in_array( 'known', $options ) ) {
354 $defaults['title'] = $target->getPrefixedText();
355 } else {
356 $defaults['title'] = wfMessage( 'red-link-title', $target->getPrefixedText() )->text();
359 # Finally, merge the custom attribs with the default ones, and iterate
360 # over that, deleting all "false" attributes.
361 $ret = array();
362 $merged = Sanitizer::mergeAttributes( $defaults, $attribs );
363 foreach ( $merged as $key => $val ) {
364 # A false value suppresses the attribute, and we don't want the
365 # href attribute to be overridden.
366 if ( $key != 'href' and $val !== false ) {
367 $ret[$key] = $val;
370 wfProfileOut( __METHOD__ );
371 return $ret;
375 * Default text of the links to the Title $target
377 * @param Title $target
379 * @return string
381 private static function linkText( $target ) {
382 // We might be passed a non-Title by make*LinkObj(). Fail gracefully.
383 if ( !$target instanceof Title ) {
384 return '';
387 // If the target is just a fragment, with no title, we return the fragment
388 // text. Otherwise, we return the title text itself.
389 if ( $target->getPrefixedText() === '' && $target->hasFragment() ) {
390 return htmlspecialchars( $target->getFragment() );
393 return htmlspecialchars( $target->getPrefixedText() );
397 * Make appropriate markup for a link to the current article. This is
398 * currently rendered as the bold link text. The calling sequence is the
399 * same as the other make*LinkObj static functions, despite $query not
400 * being used.
402 * @param Title $nt
403 * @param string $html [optional]
404 * @param string $query [optional]
405 * @param string $trail [optional]
406 * @param string $prefix [optional]
408 * @return string
410 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
411 $ret = "<strong class=\"selflink\">{$prefix}{$html}</strong>{$trail}";
412 if ( !wfRunHooks( 'SelfLinkBegin', array( $nt, &$html, &$trail, &$prefix, &$ret ) ) ) {
413 return $ret;
416 if ( $html == '' ) {
417 $html = htmlspecialchars( $nt->getPrefixedText() );
419 list( $inside, $trail ) = self::splitTrail( $trail );
420 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
424 * Get a message saying that an invalid title was encountered.
425 * This should be called after a method like Title::makeTitleSafe() returned
426 * a value indicating that the title object is invalid.
428 * @param IContextSource $context Context to use to get the messages
429 * @param int $namespace Namespace number
430 * @param string $title Text of the title, without the namespace part
431 * @return string
433 public static function getInvalidTitleDescription( IContextSource $context, $namespace, $title ) {
434 global $wgContLang;
436 // First we check whether the namespace exists or not.
437 if ( MWNamespace::exists( $namespace ) ) {
438 if ( $namespace == NS_MAIN ) {
439 $name = $context->msg( 'blanknamespace' )->text();
440 } else {
441 $name = $wgContLang->getFormattedNsText( $namespace );
443 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
444 } else {
445 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
450 * @param Title $title
451 * @return Title
453 static function normaliseSpecialPage( Title $title ) {
454 if ( $title->isSpecialPage() ) {
455 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
456 if ( !$name ) {
457 return $title;
459 $ret = SpecialPage::getTitleFor( $name, $subpage, $title->getFragment() );
460 return $ret;
461 } else {
462 return $title;
467 * Returns the filename part of an url.
468 * Used as alternative text for external images.
470 * @param string $url
472 * @return string
474 private static function fnamePart( $url ) {
475 $basename = strrchr( $url, '/' );
476 if ( false === $basename ) {
477 $basename = $url;
478 } else {
479 $basename = substr( $basename, 1 );
481 return $basename;
485 * Return the code for images which were added via external links,
486 * via Parser::maybeMakeExternalImage().
488 * @param string $url
489 * @param string $alt
491 * @return string
493 public static function makeExternalImage( $url, $alt = '' ) {
494 if ( $alt == '' ) {
495 $alt = self::fnamePart( $url );
497 $img = '';
498 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
499 if ( !$success ) {
500 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
501 . "with url {$url} and alt text {$alt} to {$img}\n", true );
502 return $img;
504 return Html::element( 'img',
505 array(
506 'src' => $url,
507 'alt' => $alt ) );
511 * Given parameters derived from [[Image:Foo|options...]], generate the
512 * HTML that that syntax inserts in the page.
514 * @param Parser $parser
515 * @param Title $title Title object of the file (not the currently viewed page)
516 * @param File $file File object, or false if it doesn't exist
517 * @param array $frameParams Associative array of parameters external to the media handler.
518 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
519 * will often be false.
520 * thumbnail If present, downscale and frame
521 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
522 * framed Shows image in original size in a frame
523 * frameless Downscale but don't frame
524 * upright If present, tweak default sizes for portrait orientation
525 * upright_factor Fudge factor for "upright" tweak (default 0.75)
526 * border If present, show a border around the image
527 * align Horizontal alignment (left, right, center, none)
528 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
529 * bottom, text-bottom)
530 * alt Alternate text for image (i.e. alt attribute). Plain text.
531 * class HTML for image classes. Plain text.
532 * caption HTML for image caption.
533 * link-url URL to link to
534 * link-title Title object to link to
535 * link-target Value for the target attribute, only with link-url
536 * no-link Boolean, suppress description link
538 * @param array $handlerParams Associative array of media handler parameters, to be passed
539 * to transform(). Typical keys are "width" and "page".
540 * @param string|bool $time Timestamp of the file, set as false for current
541 * @param string $query Query params for desc url
542 * @param int|null $widthOption Used by the parser to remember the user preference thumbnailsize
543 * @since 1.20
544 * @return string HTML for an image, with links, wrappers, etc.
546 public static function makeImageLink( /*Parser*/ $parser, Title $title,
547 $file, $frameParams = array(), $handlerParams = array(), $time = false,
548 $query = "", $widthOption = null
550 $res = null;
551 $dummy = new DummyLinker;
552 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
553 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
554 return $res;
557 if ( $file && !$file->allowInlineDisplay() ) {
558 wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
559 return self::link( $title );
562 // Shortcuts
563 $fp =& $frameParams;
564 $hp =& $handlerParams;
566 // Clean up parameters
567 $page = isset( $hp['page'] ) ? $hp['page'] : false;
568 if ( !isset( $fp['align'] ) ) {
569 $fp['align'] = '';
571 if ( !isset( $fp['alt'] ) ) {
572 $fp['alt'] = '';
574 if ( !isset( $fp['title'] ) ) {
575 $fp['title'] = '';
577 if ( !isset( $fp['class'] ) ) {
578 $fp['class'] = '';
581 $prefix = $postfix = '';
583 if ( 'center' == $fp['align'] ) {
584 $prefix = '<div class="center">';
585 $postfix = '</div>';
586 $fp['align'] = 'none';
588 if ( $file && !isset( $hp['width'] ) ) {
589 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
590 // If its a vector image, and user only specifies height
591 // we don't want it to be limited by its "normal" width.
592 global $wgSVGMaxSize;
593 $hp['width'] = $wgSVGMaxSize;
594 } else {
595 $hp['width'] = $file->getWidth( $page );
598 if ( isset( $fp['thumbnail'] )
599 || isset( $fp['manualthumb'] )
600 || isset( $fp['framed'] )
601 || isset( $fp['frameless'] )
602 || !$hp['width']
604 global $wgThumbLimits, $wgThumbUpright;
606 if ( $widthOption === null || !isset( $wgThumbLimits[$widthOption] ) ) {
607 $widthOption = User::getDefaultOption( 'thumbsize' );
610 // Reduce width for upright images when parameter 'upright' is used
611 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
612 $fp['upright'] = $wgThumbUpright;
615 // For caching health: If width scaled down due to upright
616 // parameter, round to full __0 pixel to avoid the creation of a
617 // lot of odd thumbs.
618 $prefWidth = isset( $fp['upright'] ) ?
619 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
620 $wgThumbLimits[$widthOption];
622 // Use width which is smaller: real image width or user preference width
623 // Unless image is scalable vector.
624 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
625 $prefWidth < $hp['width'] || $file->isVectorized() ) ) {
626 $hp['width'] = $prefWidth;
631 if ( isset( $fp['thumbnail'] ) || isset( $fp['manualthumb'] ) || isset( $fp['framed'] ) ) {
632 # Create a thumbnail. Alignment depends on the writing direction of
633 # the page content language (right-aligned for LTR languages,
634 # left-aligned for RTL languages)
636 # If a thumbnail width has not been provided, it is set
637 # to the default user option as specified in Language*.php
638 if ( $fp['align'] == '' ) {
639 if ( $parser instanceof Parser ) {
640 $fp['align'] = $parser->getTargetLanguage()->alignEnd();
641 } else {
642 # backwards compatibility, remove with makeImageLink2()
643 global $wgContLang;
644 $fp['align'] = $wgContLang->alignEnd();
647 return $prefix . self::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
650 if ( $file && isset( $fp['frameless'] ) ) {
651 $srcWidth = $file->getWidth( $page );
652 # For "frameless" option: do not present an image bigger than the
653 # source (for bitmap-style images). This is the same behavior as the
654 # "thumb" option does it already.
655 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
656 $hp['width'] = $srcWidth;
660 if ( $file && isset( $hp['width'] ) ) {
661 # Create a resized image, without the additional thumbnail features
662 $thumb = $file->transform( $hp );
663 } else {
664 $thumb = false;
667 if ( !$thumb ) {
668 $s = self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
669 } else {
670 self::processResponsiveImages( $file, $thumb, $hp );
671 $params = array(
672 'alt' => $fp['alt'],
673 'title' => $fp['title'],
674 'valign' => isset( $fp['valign'] ) ? $fp['valign'] : false,
675 'img-class' => $fp['class'] );
676 if ( isset( $fp['border'] ) ) {
677 $params['img-class'] .= ( $params['img-class'] !== '' ? ' ' : '' ) . 'thumbborder';
679 $params = self::getImageLinkMTOParams( $fp, $query, $parser ) + $params;
681 $s = $thumb->toHtml( $params );
683 if ( $fp['align'] != '' ) {
684 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
686 return str_replace( "\n", ' ', $prefix . $s . $postfix );
690 * See makeImageLink()
691 * When this function is removed, remove if( $parser instanceof Parser ) check there too
692 * @deprecated since 1.20
694 public static function makeImageLink2( Title $title, $file, $frameParams = array(),
695 $handlerParams = array(), $time = false, $query = "", $widthOption = null ) {
696 return self::makeImageLink( null, $title, $file, $frameParams,
697 $handlerParams, $time, $query, $widthOption );
701 * Get the link parameters for MediaTransformOutput::toHtml() from given
702 * frame parameters supplied by the Parser.
703 * @param array $frameParams The frame parameters
704 * @param string $query An optional query string to add to description page links
705 * @return array
707 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
708 $mtoParams = array();
709 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
710 $mtoParams['custom-url-link'] = $frameParams['link-url'];
711 if ( isset( $frameParams['link-target'] ) ) {
712 $mtoParams['custom-target-link'] = $frameParams['link-target'];
714 if ( $parser ) {
715 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
716 foreach ( $extLinkAttrs as $name => $val ) {
717 // Currently could include 'rel' and 'target'
718 $mtoParams['parser-extlink-' . $name] = $val;
721 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
722 $mtoParams['custom-title-link'] = self::normaliseSpecialPage( $frameParams['link-title'] );
723 } elseif ( !empty( $frameParams['no-link'] ) ) {
724 // No link
725 } else {
726 $mtoParams['desc-link'] = true;
727 $mtoParams['desc-query'] = $query;
729 return $mtoParams;
733 * Make HTML for a thumbnail including image, border and caption
734 * @param Title $title
735 * @param File|bool $file File object or false if it doesn't exist
736 * @param string $label
737 * @param string $alt
738 * @param string $align
739 * @param array $params
740 * @param bool $framed
741 * @param string $manualthumb
742 * @return string
744 public static function makeThumbLinkObj( Title $title, $file, $label = '', $alt,
745 $align = 'right', $params = array(), $framed = false, $manualthumb = ""
747 $frameParams = array(
748 'alt' => $alt,
749 'caption' => $label,
750 'align' => $align
752 if ( $framed ) {
753 $frameParams['framed'] = true;
755 if ( $manualthumb ) {
756 $frameParams['manualthumb'] = $manualthumb;
758 return self::makeThumbLink2( $title, $file, $frameParams, $params );
762 * @param Title $title
763 * @param File $file
764 * @param array $frameParams
765 * @param array $handlerParams
766 * @param bool $time
767 * @param string $query
768 * @return string
770 public static function makeThumbLink2( Title $title, $file, $frameParams = array(),
771 $handlerParams = array(), $time = false, $query = ""
773 global $wgStylePath, $wgContLang;
774 $exists = $file && $file->exists();
776 # Shortcuts
777 $fp =& $frameParams;
778 $hp =& $handlerParams;
780 $page = isset( $hp['page'] ) ? $hp['page'] : false;
781 if ( !isset( $fp['align'] ) ) {
782 $fp['align'] = 'right';
784 if ( !isset( $fp['alt'] ) ) {
785 $fp['alt'] = '';
787 if ( !isset( $fp['title'] ) ) {
788 $fp['title'] = '';
790 if ( !isset( $fp['caption'] ) ) {
791 $fp['caption'] = '';
794 if ( empty( $hp['width'] ) ) {
795 // Reduce width for upright images when parameter 'upright' is used
796 $hp['width'] = isset( $fp['upright'] ) ? 130 : 180;
798 $thumb = false;
799 $noscale = false;
800 $manualthumb = false;
802 if ( !$exists ) {
803 $outerWidth = $hp['width'] + 2;
804 } else {
805 if ( isset( $fp['manualthumb'] ) ) {
806 # Use manually specified thumbnail
807 $manual_title = Title::makeTitleSafe( NS_FILE, $fp['manualthumb'] );
808 if ( $manual_title ) {
809 $manual_img = wfFindFile( $manual_title );
810 if ( $manual_img ) {
811 $thumb = $manual_img->getUnscaledThumb( $hp );
812 $manualthumb = true;
813 } else {
814 $exists = false;
817 } elseif ( isset( $fp['framed'] ) ) {
818 // Use image dimensions, don't scale
819 $thumb = $file->getUnscaledThumb( $hp );
820 $noscale = true;
821 } else {
822 # Do not present an image bigger than the source, for bitmap-style images
823 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
824 $srcWidth = $file->getWidth( $page );
825 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
826 $hp['width'] = $srcWidth;
828 $thumb = $file->transform( $hp );
831 if ( $thumb ) {
832 $outerWidth = $thumb->getWidth() + 2;
833 } else {
834 $outerWidth = $hp['width'] + 2;
838 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
839 # So we don't need to pass it here in $query. However, the URL for the
840 # zoom icon still needs it, so we make a unique query for it. See bug 14771
841 $url = $title->getLocalURL( $query );
842 if ( $page ) {
843 $url = wfAppendQuery( $url, array( 'page' => $page ) );
845 if ( $manualthumb
846 && !isset( $fp['link-title'] )
847 && !isset( $fp['link-url'] )
848 && !isset( $fp['no-link'] ) ) {
849 $fp['link-url'] = $url;
852 $s = "<div class=\"thumb t{$fp['align']}\">"
853 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
855 if ( !$exists ) {
856 $s .= self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
857 $zoomIcon = '';
858 } elseif ( !$thumb ) {
859 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
860 $zoomIcon = '';
861 } else {
862 if ( !$noscale && !$manualthumb ) {
863 self::processResponsiveImages( $file, $thumb, $hp );
865 $params = array(
866 'alt' => $fp['alt'],
867 'title' => $fp['title'],
868 'img-class' => ( isset( $fp['class'] ) && $fp['class'] !== ''
869 ? $fp['class'] . ' '
870 : '' ) . 'thumbimage'
872 $params = self::getImageLinkMTOParams( $fp, $query ) + $params;
873 $s .= $thumb->toHtml( $params );
874 if ( isset( $fp['framed'] ) ) {
875 $zoomIcon = "";
876 } else {
877 $zoomIcon = Html::rawElement( 'div', array( 'class' => 'magnify' ),
878 Html::rawElement( 'a', array(
879 'href' => $url,
880 'class' => 'internal',
881 'title' => wfMessage( 'thumbnail-more' )->text() ),
882 Html::element( 'img', array(
883 'src' => $wgStylePath . '/common/images/magnify-clip'
884 . ( $wgContLang->isRTL() ? '-rtl' : '' ) . '.png',
885 'width' => 15,
886 'height' => 11,
887 'alt' => "" ) ) ) );
890 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
891 return str_replace( "\n", ' ', $s );
895 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
896 * applicable.
898 * @param File $file
899 * @param MediaTransformOutput $thumb
900 * @param array $hp Image parameters
902 public static function processResponsiveImages( $file, $thumb, $hp ) {
903 global $wgResponsiveImages;
904 if ( $wgResponsiveImages ) {
905 $hp15 = $hp;
906 $hp15['width'] = round( $hp['width'] * 1.5 );
907 $hp20 = $hp;
908 $hp20['width'] = $hp['width'] * 2;
909 if ( isset( $hp['height'] ) ) {
910 $hp15['height'] = round( $hp['height'] * 1.5 );
911 $hp20['height'] = $hp['height'] * 2;
914 $thumb15 = $file->transform( $hp15 );
915 $thumb20 = $file->transform( $hp20 );
916 if ( $thumb15 && $thumb15->getUrl() !== $thumb->getUrl() ) {
917 $thumb->responsiveUrls['1.5'] = $thumb15->getUrl();
919 if ( $thumb20 && $thumb20->getUrl() !== $thumb->getUrl() ) {
920 $thumb->responsiveUrls['2'] = $thumb20->getUrl();
926 * Make a "broken" link to an image
928 * @param Title $title
929 * @param string $label Link label (plain text)
930 * @param string $query Query string
931 * @param string $unused1 Unused parameter kept for b/c
932 * @param string $unused2 Unused parameter kept for b/c
933 * @param bool $time A file of a certain timestamp was requested
934 * @return string
936 public static function makeBrokenImageLinkObj( $title, $label = '',
937 $query = '', $unused1 = '', $unused2 = '', $time = false
939 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
940 if ( !$title instanceof Title ) {
941 return "<!-- ERROR -->" . htmlspecialchars( $label );
943 wfProfileIn( __METHOD__ );
944 if ( $label == '' ) {
945 $label = $title->getPrefixedText();
947 $encLabel = htmlspecialchars( $label );
948 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
950 if ( ( $wgUploadMissingFileUrl || $wgUploadNavigationUrl || $wgEnableUploads )
951 && !$currentExists
953 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
955 if ( $redir ) {
956 wfProfileOut( __METHOD__ );
957 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
960 $href = self::getUploadUrl( $title, $query );
962 wfProfileOut( __METHOD__ );
963 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
964 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES ) . '">' .
965 $encLabel . '</a>';
968 wfProfileOut( __METHOD__ );
969 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
973 * Get the URL to upload a certain file
975 * @param Title $destFile Title object of the file to upload
976 * @param string $query Urlencoded query string to prepend
977 * @return string Urlencoded URL
979 protected static function getUploadUrl( $destFile, $query = '' ) {
980 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
981 $q = 'wpDestFile=' . $destFile->getPartialURL();
982 if ( $query != '' ) {
983 $q .= '&' . $query;
986 if ( $wgUploadMissingFileUrl ) {
987 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
988 } elseif ( $wgUploadNavigationUrl ) {
989 return wfAppendQuery( $wgUploadNavigationUrl, $q );
990 } else {
991 $upload = SpecialPage::getTitleFor( 'Upload' );
992 return $upload->getLocalURL( $q );
997 * Create a direct link to a given uploaded file.
999 * @param Title $title
1000 * @param string $html Pre-sanitized HTML
1001 * @param string $time MW timestamp of file creation time
1002 * @return string HTML
1004 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
1005 $img = wfFindFile( $title, array( 'time' => $time ) );
1006 return self::makeMediaLinkFile( $title, $img, $html );
1010 * Create a direct link to a given uploaded file.
1011 * This will make a broken link if $file is false.
1013 * @param Title $title
1014 * @param File|bool $file File object or false
1015 * @param string $html Pre-sanitized HTML
1016 * @return string HTML
1018 * @todo Handle invalid or missing images better.
1020 public static function makeMediaLinkFile( Title $title, $file, $html = '' ) {
1021 if ( $file && $file->exists() ) {
1022 $url = $file->getURL();
1023 $class = 'internal';
1024 } else {
1025 $url = self::getUploadUrl( $title );
1026 $class = 'new';
1029 $alt = $title->getText();
1030 if ( $html == '' ) {
1031 $html = $alt;
1034 $ret = '';
1035 $attribs = array(
1036 'href' => $url,
1037 'class' => $class,
1038 'title' => $alt
1041 if ( !wfRunHooks( 'LinkerMakeMediaLinkFile',
1042 array( $title, $file, &$html, &$attribs, &$ret ) ) ) {
1043 wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
1044 . "with url {$url} and text {$html} to {$ret}\n", true );
1045 return $ret;
1048 return Html::rawElement( 'a', $attribs, $html );
1052 * Make a link to a special page given its name and, optionally,
1053 * a message key from the link text.
1054 * Usage example: Linker::specialLink( 'Recentchanges' )
1056 * @param string $name
1057 * @param string $key
1058 * @return string
1060 public static function specialLink( $name, $key = '' ) {
1061 if ( $key == '' ) {
1062 $key = strtolower( $name );
1065 return self::linkKnown( SpecialPage::getTitleFor( $name ), wfMessage( $key )->text() );
1069 * Make an external link
1070 * @param string $url URL to link to
1071 * @param string $text Text of link
1072 * @param bool $escape Do we escape the link text?
1073 * @param string $linktype Type of external link. Gets added to the classes
1074 * @param array $attribs Array of extra attributes to <a>
1075 * @param Title|null $title Title object used for title specific link attributes
1076 * @return string
1078 public static function makeExternalLink( $url, $text, $escape = true,
1079 $linktype = '', $attribs = array(), $title = null
1081 global $wgTitle;
1082 $class = "external";
1083 if ( $linktype ) {
1084 $class .= " $linktype";
1086 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1087 $class .= " {$attribs['class']}";
1089 $attribs['class'] = $class;
1091 if ( $escape ) {
1092 $text = htmlspecialchars( $text );
1095 if ( !$title ) {
1096 $title = $wgTitle;
1098 $attribs['rel'] = Parser::getExternalLinkRel( $url, $title );
1099 $link = '';
1100 $success = wfRunHooks( 'LinkerMakeExternalLink',
1101 array( &$url, &$text, &$link, &$attribs, $linktype ) );
1102 if ( !$success ) {
1103 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
1104 . "with url {$url} and text {$text} to {$link}\n", true );
1105 return $link;
1107 $attribs['href'] = $url;
1108 return Html::rawElement( 'a', $attribs, $text );
1112 * Make user link (or user contributions for unregistered users)
1113 * @param int $userId User id in database.
1114 * @param string $userName User name in database.
1115 * @param string $altUserName Text to display instead of the user name (optional)
1116 * @return string HTML fragment
1117 * @since 1.19 Method exists for a long time. $altUserName was added in 1.19.
1119 public static function userLink( $userId, $userName, $altUserName = false ) {
1120 $classes = 'mw-userlink';
1121 if ( $userId == 0 ) {
1122 $page = SpecialPage::getTitleFor( 'Contributions', $userName );
1123 if ( $altUserName === false ) {
1124 $altUserName = IP::prettifyIP( $userName );
1126 $classes .= ' mw-anonuserlink'; // Separate link class for anons (bug 43179)
1127 } else {
1128 $page = Title::makeTitle( NS_USER, $userName );
1131 return self::link(
1132 $page,
1133 htmlspecialchars( $altUserName !== false ? $altUserName : $userName ),
1134 array( 'class' => $classes )
1139 * Generate standard user tool links (talk, contributions, block link, etc.)
1141 * @param int $userId User identifier
1142 * @param string $userText User name or IP address
1143 * @param bool $redContribsWhenNoEdits Should the contributions link be
1144 * red if the user has no edits?
1145 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
1146 * and Linker::TOOL_LINKS_EMAIL).
1147 * @param int $edits User edit count (optional, for performance)
1148 * @return string HTML fragment
1150 public static function userToolLinks(
1151 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1153 global $wgUser, $wgDisableAnonTalk, $wgLang;
1154 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1155 $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1156 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1158 $items = array();
1159 if ( $talkable ) {
1160 $items[] = self::userTalkLink( $userId, $userText );
1162 if ( $userId ) {
1163 // check if the user has an edit
1164 $attribs = array();
1165 if ( $redContribsWhenNoEdits ) {
1166 if ( intval( $edits ) === 0 && $edits !== 0 ) {
1167 $user = User::newFromId( $userId );
1168 $edits = $user->getEditCount();
1170 if ( $edits === 0 ) {
1171 $attribs['class'] = 'new';
1174 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1176 $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1178 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1179 $items[] = self::blockLink( $userId, $userText );
1182 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1183 $items[] = self::emailLink( $userId, $userText );
1186 wfRunHooks( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1188 if ( $items ) {
1189 return wfMessage( 'word-separator' )->plain()
1190 . '<span class="mw-usertoollinks">'
1191 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1192 . '</span>';
1193 } else {
1194 return '';
1199 * Alias for userToolLinks( $userId, $userText, true );
1200 * @param int $userId User identifier
1201 * @param string $userText User name or IP address
1202 * @param int $edits User edit count (optional, for performance)
1203 * @return string
1205 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1206 return self::userToolLinks( $userId, $userText, true, 0, $edits );
1210 * @param int $userId User id in database.
1211 * @param string $userText User name in database.
1212 * @return string HTML fragment with user talk link
1214 public static function userTalkLink( $userId, $userText ) {
1215 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1216 $userTalkLink = self::link( $userTalkPage, wfMessage( 'talkpagelinktext' )->escaped() );
1217 return $userTalkLink;
1221 * @param int $userId Userid
1222 * @param string $userText User name in database.
1223 * @return string HTML fragment with block link
1225 public static function blockLink( $userId, $userText ) {
1226 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1227 $blockLink = self::link( $blockPage, wfMessage( 'blocklink' )->escaped() );
1228 return $blockLink;
1232 * @param int $userId Userid
1233 * @param string $userText User name in database.
1234 * @return string HTML fragment with e-mail user link
1236 public static function emailLink( $userId, $userText ) {
1237 $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1238 $emailLink = self::link( $emailPage, wfMessage( 'emaillink' )->escaped() );
1239 return $emailLink;
1243 * Generate a user link if the current user is allowed to view it
1244 * @param Revision $rev
1245 * @param bool $isPublic Show only if all users can see it
1246 * @return string HTML fragment
1248 public static function revUserLink( $rev, $isPublic = false ) {
1249 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1250 $link = wfMessage( 'rev-deleted-user' )->escaped();
1251 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1252 $link = self::userLink( $rev->getUser( Revision::FOR_THIS_USER ),
1253 $rev->getUserText( Revision::FOR_THIS_USER ) );
1254 } else {
1255 $link = wfMessage( 'rev-deleted-user' )->escaped();
1257 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1258 return '<span class="history-deleted">' . $link . '</span>';
1260 return $link;
1264 * Generate a user tool link cluster if the current user is allowed to view it
1265 * @param Revision $rev
1266 * @param bool $isPublic Show only if all users can see it
1267 * @return string HTML
1269 public static function revUserTools( $rev, $isPublic = false ) {
1270 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1271 $link = wfMessage( 'rev-deleted-user' )->escaped();
1272 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1273 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1274 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1275 $link = self::userLink( $userId, $userText )
1276 . wfMessage( 'word-separator' )->plain()
1277 . self::userToolLinks( $userId, $userText );
1278 } else {
1279 $link = wfMessage( 'rev-deleted-user' )->escaped();
1281 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1282 return ' <span class="history-deleted">' . $link . '</span>';
1284 return $link;
1288 * This function is called by all recent changes variants, by the page history,
1289 * and by the user contributions list. It is responsible for formatting edit
1290 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1291 * auto-generated comments (from section editing) and formats [[wikilinks]].
1293 * @author Erik Moeller <moeller@scireview.de>
1295 * Note: there's not always a title to pass to this function.
1296 * Since you can't set a default parameter for a reference, I've turned it
1297 * temporarily to a value pass. Should be adjusted further. --brion
1299 * @param string $comment
1300 * @param Title|null $title Title object (to generate link to the section in autocomment) or null
1301 * @param bool $local Whether section links should refer to local page
1302 * @return mixed|string
1304 public static function formatComment( $comment, $title = null, $local = false ) {
1305 wfProfileIn( __METHOD__ );
1307 # Sanitize text a bit:
1308 $comment = str_replace( "\n", " ", $comment );
1309 # Allow HTML entities (for bug 13815)
1310 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1312 # Render autocomments and make links:
1313 $comment = self::formatAutocomments( $comment, $title, $local );
1314 $comment = self::formatLinksInComment( $comment, $title, $local );
1316 wfProfileOut( __METHOD__ );
1317 return $comment;
1321 * Converts autogenerated comments in edit summaries into section links.
1322 * The pattern for autogen comments is / * foo * /, which makes for
1323 * some nasty regex.
1324 * We look for all comments, match any text before and after the comment,
1325 * add a separator where needed and format the comment itself with CSS
1326 * Called by Linker::formatComment.
1328 * @param string $comment Comment text
1329 * @param Title|null $title An optional title object used to links to sections
1330 * @param bool $local Whether section links should refer to local page
1331 * @return string Formatted comment
1333 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1334 return preg_replace_callback(
1335 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1336 function ( $match ) use ( $title, $local ) {
1337 global $wgLang;
1339 $pre = $match[1];
1340 $auto = $match[2];
1341 $post = $match[3];
1342 $comment = null;
1343 wfRunHooks( 'FormatAutocomments', array( &$comment, $pre, $auto, $post, $title, $local ) );
1344 if ( $comment === null ) {
1345 $link = '';
1346 if ( $title ) {
1347 $section = $auto;
1348 # Remove links that a user may have manually put in the autosummary
1349 # This could be improved by copying as much of Parser::stripSectionName as desired.
1350 $section = str_replace( '[[:', '', $section );
1351 $section = str_replace( '[[', '', $section );
1352 $section = str_replace( ']]', '', $section );
1354 $section = Sanitizer::normalizeSectionNameWhitespace( $section ); # bug 22784
1355 if ( $local ) {
1356 $sectionTitle = Title::newFromText( '#' . $section );
1357 } else {
1358 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1359 $title->getDBkey(), $section );
1361 if ( $sectionTitle ) {
1362 $link = Linker::link( $sectionTitle,
1363 $wgLang->getArrow(), array(), array(),
1364 'noclasses' );
1365 } else {
1366 $link = '';
1369 if ( $pre ) {
1370 # written summary $presep autocomment (summary /* section */)
1371 $pre .= wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1373 if ( $post ) {
1374 # autocomment $postsep written summary (/* section */ summary)
1375 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1377 $auto = '<span class="autocomment">' . $auto . '</span>';
1378 $comment = $pre . $link . $wgLang->getDirMark()
1379 . '<span dir="auto">' . $auto . $post . '</span>';
1381 return $comment;
1383 $comment
1388 * Formats wiki links and media links in text; all other wiki formatting
1389 * is ignored
1391 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1392 * @param string $comment Text to format links in
1393 * @param Title|null $title An optional title object used to links to sections
1394 * @param bool $local Whether section links should refer to local page
1395 * @return string
1397 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1398 return preg_replace_callback(
1400 \[\[
1401 :? # ignore optional leading colon
1402 ([^\]|]+) # 1. link target; page names cannot include ] or |
1403 (?:\|
1404 # 2. a pipe-separated substring; only the last is captured
1405 # Stop matching at | and ]] without relying on backtracking.
1406 ((?:]?[^\]|])*+)
1408 \]\]
1409 ([^[]*) # 3. link trail (the text up until the next link)
1410 /x',
1411 function ( $match ) use ( $title, $local ) {
1412 global $wgContLang;
1414 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1415 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1417 $comment = $match[0];
1419 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1420 if ( strpos( $match[1], '%' ) !== false ) {
1421 $match[1] = str_replace(
1422 array( '<', '>' ),
1423 array( '&lt;', '&gt;' ),
1424 rawurldecode( $match[1] )
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;
1468 $thelink = Linker::link(
1469 $target,
1470 $linkText . $inside
1471 ) . $trail;
1474 if ( $thelink ) {
1475 // If the link is still valid, go ahead and replace it in!
1476 $comment = preg_replace(
1477 $linkRegexp,
1478 StringUtils::escapeRegexReplacement( $thelink ),
1479 $comment,
1484 return $comment;
1486 $comment
1491 * @param Title $contextTitle
1492 * @param string $target
1493 * @param string $text
1494 * @return string
1496 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1497 # Valid link forms:
1498 # Foobar -- normal
1499 # :Foobar -- override special treatment of prefix (images, language links)
1500 # /Foobar -- convert to CurrentPage/Foobar
1501 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1502 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1503 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1505 wfProfileIn( __METHOD__ );
1506 $ret = $target; # default return value is no change
1508 # Some namespaces don't allow subpages,
1509 # so only perform processing if subpages are allowed
1510 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1511 $hash = strpos( $target, '#' );
1512 if ( $hash !== false ) {
1513 $suffix = substr( $target, $hash );
1514 $target = substr( $target, 0, $hash );
1515 } else {
1516 $suffix = '';
1518 # bug 7425
1519 $target = trim( $target );
1520 # Look at the first character
1521 if ( $target != '' && $target[0] === '/' ) {
1522 # / at end means we don't want the slash to be shown
1523 $m = array();
1524 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1525 if ( $trailingSlashes ) {
1526 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1527 } else {
1528 $noslash = substr( $target, 1 );
1531 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1532 if ( $text === '' ) {
1533 $text = $target . $suffix;
1534 } # this might be changed for ugliness reasons
1535 } else {
1536 # check for .. subpage backlinks
1537 $dotdotcount = 0;
1538 $nodotdot = $target;
1539 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1540 ++$dotdotcount;
1541 $nodotdot = substr( $nodotdot, 3 );
1543 if ( $dotdotcount > 0 ) {
1544 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1545 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1546 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1547 # / at the end means don't show full path
1548 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1549 $nodotdot = substr( $nodotdot, 0, -1 );
1550 if ( $text === '' ) {
1551 $text = $nodotdot . $suffix;
1554 $nodotdot = trim( $nodotdot );
1555 if ( $nodotdot != '' ) {
1556 $ret .= '/' . $nodotdot;
1558 $ret .= $suffix;
1564 wfProfileOut( __METHOD__ );
1565 return $ret;
1569 * Wrap a comment in standard punctuation and formatting if
1570 * it's non-empty, otherwise return empty string.
1572 * @param string $comment
1573 * @param Title|null $title Title object (to generate link to section in autocomment) or null
1574 * @param bool $local Whether section links should refer to local page
1576 * @return string
1578 public static function commentBlock( $comment, $title = null, $local = false ) {
1579 // '*' used to be the comment inserted by the software way back
1580 // in antiquity in case none was provided, here for backwards
1581 // compatibility, acc. to brion -ævar
1582 if ( $comment == '' || $comment == '*' ) {
1583 return '';
1584 } else {
1585 $formatted = self::formatComment( $comment, $title, $local );
1586 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1587 return " <span class=\"comment\">$formatted</span>";
1592 * Wrap and format the given revision's comment block, if the current
1593 * user is allowed to view it.
1595 * @param Revision $rev
1596 * @param bool $local Whether section links should refer to local page
1597 * @param bool $isPublic Show only if all users can see it
1598 * @return string HTML fragment
1600 public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1601 if ( $rev->getRawComment() == "" ) {
1602 return "";
1604 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1605 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1606 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1607 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1608 $rev->getTitle(), $local );
1609 } else {
1610 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1612 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1613 return " <span class=\"history-deleted\">$block</span>";
1615 return $block;
1619 * @param int $size
1620 * @return string
1622 public static function formatRevisionSize( $size ) {
1623 if ( $size == 0 ) {
1624 $stxt = wfMessage( 'historyempty' )->escaped();
1625 } else {
1626 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1627 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1629 return "<span class=\"history-size\">$stxt</span>";
1633 * Add another level to the Table of Contents
1635 * @return string
1637 public static function tocIndent() {
1638 return "\n<ul>";
1642 * Finish one or more sublevels on the Table of Contents
1644 * @param int $level
1645 * @return string
1647 public static function tocUnindent( $level ) {
1648 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1652 * parameter level defines if we are on an indentation level
1654 * @param string $anchor
1655 * @param string $tocline
1656 * @param string $tocnumber
1657 * @param string $level
1658 * @param string|bool $sectionIndex
1659 * @return string
1661 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1662 $classes = "toclevel-$level";
1663 if ( $sectionIndex !== false ) {
1664 $classes .= " tocsection-$sectionIndex";
1666 return "\n<li class=\"$classes\"><a href=\"#" .
1667 $anchor . '"><span class="tocnumber">' .
1668 $tocnumber . '</span> <span class="toctext">' .
1669 $tocline . '</span></a>';
1673 * End a Table Of Contents line.
1674 * tocUnindent() will be used instead if we're ending a line below
1675 * the new level.
1676 * @return string
1678 public static function tocLineEnd() {
1679 return "</li>\n";
1683 * Wraps the TOC in a table and provides the hide/collapse javascript.
1685 * @param string $toc Html of the Table Of Contents
1686 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1687 * @return string Full html of the TOC
1689 public static function tocList( $toc, $lang = false ) {
1690 $lang = wfGetLangObj( $lang );
1691 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1693 return '<div id="toc" class="toc">'
1694 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1695 . $toc
1696 . "</ul>\n</div>\n";
1700 * Generate a table of contents from a section tree
1701 * Currently unused.
1703 * @param array $tree Return value of ParserOutput::getSections()
1704 * @return string HTML fragment
1706 public static function generateTOC( $tree ) {
1707 $toc = '';
1708 $lastLevel = 0;
1709 foreach ( $tree as $section ) {
1710 if ( $section['toclevel'] > $lastLevel ) {
1711 $toc .= self::tocIndent();
1712 } elseif ( $section['toclevel'] < $lastLevel ) {
1713 $toc .= self::tocUnindent(
1714 $lastLevel - $section['toclevel'] );
1715 } else {
1716 $toc .= self::tocLineEnd();
1719 $toc .= self::tocLine( $section['anchor'],
1720 $section['line'], $section['number'],
1721 $section['toclevel'], $section['index'] );
1722 $lastLevel = $section['toclevel'];
1724 $toc .= self::tocLineEnd();
1725 return self::tocList( $toc );
1729 * Create a headline for content
1731 * @param int $level The level of the headline (1-6)
1732 * @param string $attribs Any attributes for the headline, starting with
1733 * a space and ending with '>'
1734 * This *must* be at least '>' for no attribs
1735 * @param string $anchor The anchor to give the headline (the bit after the #)
1736 * @param string $html Html for the text of the header
1737 * @param string $link HTML to add for the section edit link
1738 * @param bool|string $legacyAnchor A second, optional anchor to give for
1739 * backward compatibility (false to omit)
1741 * @return string HTML headline
1743 public static function makeHeadline( $level, $attribs, $anchor, $html,
1744 $link, $legacyAnchor = false
1746 $ret = "<h$level$attribs"
1747 . "<span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1748 . $link
1749 . "</h$level>";
1750 if ( $legacyAnchor !== false ) {
1751 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1753 return $ret;
1757 * Split a link trail, return the "inside" portion and the remainder of the trail
1758 * as a two-element array
1759 * @param string $trail
1760 * @return array
1762 static function splitTrail( $trail ) {
1763 global $wgContLang;
1764 $regex = $wgContLang->linkTrail();
1765 $inside = '';
1766 if ( $trail !== '' ) {
1767 $m = array();
1768 if ( preg_match( $regex, $trail, $m ) ) {
1769 $inside = $m[1];
1770 $trail = $m[2];
1773 return array( $inside, $trail );
1777 * Generate a rollback link for a given revision. Currently it's the
1778 * caller's responsibility to ensure that the revision is the top one. If
1779 * it's not, of course, the user will get an error message.
1781 * If the calling page is called with the parameter &bot=1, all rollback
1782 * links also get that parameter. It causes the edit itself and the rollback
1783 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1784 * changes, so this allows sysops to combat a busy vandal without bothering
1785 * other users.
1787 * If the option verify is set this function will return the link only in case the
1788 * revision can be reverted. Please note that due to performance limitations
1789 * it might be assumed that a user isn't the only contributor of a page while
1790 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1791 * work if $wgShowRollbackEditCount is disabled, so this can only function
1792 * as an additional check.
1794 * If the option noBrackets is set the rollback link wont be enclosed in []
1796 * @param Revision $rev
1797 * @param IContextSource $context Context to use or null for the main context.
1798 * @param array $options
1799 * @return string
1801 public static function generateRollback( $rev, IContextSource $context = null,
1802 $options = array( 'verify' )
1804 if ( $context === null ) {
1805 $context = RequestContext::getMain();
1808 $editCount = false;
1809 if ( in_array( 'verify', $options ) ) {
1810 $editCount = self::getRollbackEditCount( $rev, true );
1811 if ( $editCount === false ) {
1812 return '';
1816 $inner = self::buildRollbackLink( $rev, $context, $editCount );
1818 if ( !in_array( 'noBrackets', $options ) ) {
1819 $inner = $context->msg( 'brackets' )->rawParams( $inner )->plain();
1822 return '<span class="mw-rollback-link">' . $inner . '</span>';
1826 * This function will return the number of revisions which a rollback
1827 * would revert and, if $verify is set it will verify that a revision
1828 * can be reverted (that the user isn't the only contributor and the
1829 * revision we might rollback to isn't deleted). These checks can only
1830 * function as an additional check as this function only checks against
1831 * the last $wgShowRollbackEditCount edits.
1833 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1834 * is set and the user is the only contributor of the page.
1836 * @param Revision $rev
1837 * @param bool $verify Try to verify that this revision can really be rolled back
1838 * @return int|bool|null
1840 public static function getRollbackEditCount( $rev, $verify ) {
1841 global $wgShowRollbackEditCount;
1842 if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
1843 // Nothing has happened, indicate this by returning 'null'
1844 return null;
1847 $dbr = wfGetDB( DB_SLAVE );
1849 // Up to the value of $wgShowRollbackEditCount revisions are counted
1850 $res = $dbr->select(
1851 'revision',
1852 array( 'rev_user_text', 'rev_deleted' ),
1853 // $rev->getPage() returns null sometimes
1854 array( 'rev_page' => $rev->getTitle()->getArticleID() ),
1855 __METHOD__,
1856 array(
1857 'USE INDEX' => array( 'revision' => 'page_timestamp' ),
1858 'ORDER BY' => 'rev_timestamp DESC',
1859 'LIMIT' => $wgShowRollbackEditCount + 1
1863 $editCount = 0;
1864 $moreRevs = false;
1865 foreach ( $res as $row ) {
1866 if ( $rev->getRawUserText() != $row->rev_user_text ) {
1867 if ( $verify &&
1868 ( $row->rev_deleted & Revision::DELETED_TEXT
1869 || $row->rev_deleted & Revision::DELETED_USER
1870 ) ) {
1871 // If the user or the text of the revision we might rollback
1872 // to is deleted in some way we can't rollback. Similar to
1873 // the sanity checks in WikiPage::commitRollback.
1874 return false;
1876 $moreRevs = true;
1877 break;
1879 $editCount++;
1882 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1883 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1884 // and there weren't any other revisions. That means that the current user is the only
1885 // editor, so we can't rollback
1886 return false;
1888 return $editCount;
1892 * Build a raw rollback link, useful for collections of "tool" links
1894 * @param Revision $rev
1895 * @param IContextSource|null $context Context to use or null for the main context.
1896 * @param int $editCount Number of edits that would be reverted
1897 * @return string HTML fragment
1899 public static function buildRollbackLink( $rev, IContextSource $context = null,
1900 $editCount = false
1902 global $wgShowRollbackEditCount, $wgMiserMode;
1904 // To config which pages are effected by miser mode
1905 $disableRollbackEditCountSpecialPage = array( 'Recentchanges', 'Watchlist' );
1907 if ( $context === null ) {
1908 $context = RequestContext::getMain();
1911 $title = $rev->getTitle();
1912 $query = array(
1913 'action' => 'rollback',
1914 'from' => $rev->getUserText(),
1915 'token' => $context->getUser()->getEditToken( array(
1916 $title->getPrefixedText(),
1917 $rev->getUserText()
1918 ) ),
1920 if ( $context->getRequest()->getBool( 'bot' ) ) {
1921 $query['bot'] = '1';
1922 $query['hidediff'] = '1'; // bug 15999
1925 $disableRollbackEditCount = false;
1926 if ( $wgMiserMode ) {
1927 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1928 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1929 $disableRollbackEditCount = true;
1930 break;
1935 if ( !$disableRollbackEditCount
1936 && is_int( $wgShowRollbackEditCount )
1937 && $wgShowRollbackEditCount > 0
1939 if ( !is_numeric( $editCount ) ) {
1940 $editCount = self::getRollbackEditCount( $rev, false );
1943 if ( $editCount > $wgShowRollbackEditCount ) {
1944 $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )
1945 ->numParams( $wgShowRollbackEditCount )->parse();
1946 } else {
1947 $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1950 return self::link(
1951 $title,
1952 $editCount_output,
1953 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1954 $query,
1955 array( 'known', 'noclasses' )
1957 } else {
1958 return self::link(
1959 $title,
1960 $context->msg( 'rollbacklink' )->escaped(),
1961 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1962 $query,
1963 array( 'known', 'noclasses' )
1969 * Returns HTML for the "templates used on this page" list.
1971 * Make an HTML list of templates, and then add a "More..." link at
1972 * the bottom. If $more is null, do not add a "More..." link. If $more
1973 * is a Title, make a link to that title and use it. If $more is a string,
1974 * directly paste it in as the link (escaping needs to be done manually).
1975 * Finally, if $more is a Message, call toString().
1977 * @param array $templates Array of templates from Article::getUsedTemplate or similar
1978 * @param bool $preview Whether this is for a preview
1979 * @param bool $section Whether this is for a section edit
1980 * @param Title|Message|string|null $more An escaped link for "More..." of the templates
1981 * @return string HTML output
1983 public static function formatTemplates( $templates, $preview = false,
1984 $section = false, $more = null
1986 global $wgLang;
1987 wfProfileIn( __METHOD__ );
1989 $outText = '';
1990 if ( count( $templates ) > 0 ) {
1991 # Do a batch existence check
1992 $batch = new LinkBatch;
1993 foreach ( $templates as $title ) {
1994 $batch->addObj( $title );
1996 $batch->execute();
1998 # Construct the HTML
1999 $outText = '<div class="mw-templatesUsedExplanation">';
2000 if ( $preview ) {
2001 $outText .= wfMessage( 'templatesusedpreview' )->numParams( count( $templates ) )
2002 ->parseAsBlock();
2003 } elseif ( $section ) {
2004 $outText .= wfMessage( 'templatesusedsection' )->numParams( count( $templates ) )
2005 ->parseAsBlock();
2006 } else {
2007 $outText .= wfMessage( 'templatesused' )->numParams( count( $templates ) )
2008 ->parseAsBlock();
2010 $outText .= "</div><ul>\n";
2012 usort( $templates, 'Title::compare' );
2013 foreach ( $templates as $titleObj ) {
2014 $protected = '';
2015 $restrictions = $titleObj->getRestrictions( 'edit' );
2016 if ( $restrictions ) {
2017 // Check backwards-compatible messages
2018 $msg = null;
2019 if ( $restrictions === array( 'sysop' ) ) {
2020 $msg = wfMessage( 'template-protected' );
2021 } elseif ( $restrictions === array( 'autoconfirmed' ) ) {
2022 $msg = wfMessage( 'template-semiprotected' );
2024 if ( $msg && !$msg->isDisabled() ) {
2025 $protected = $msg->parse();
2026 } else {
2027 // Construct the message from restriction-level-*
2028 // e.g. restriction-level-sysop, restriction-level-autoconfirmed
2029 $msgs = array();
2030 foreach ( $restrictions as $r ) {
2031 $msgs[] = wfMessage( "restriction-level-$r" )->parse();
2033 $protected = wfMessage( 'parentheses' )
2034 ->rawParams( $wgLang->commaList( $msgs ) )->escaped();
2037 if ( $titleObj->quickUserCan( 'edit' ) ) {
2038 $editLink = self::link(
2039 $titleObj,
2040 wfMessage( 'editlink' )->text(),
2041 array(),
2042 array( 'action' => 'edit' )
2044 } else {
2045 $editLink = self::link(
2046 $titleObj,
2047 wfMessage( 'viewsourcelink' )->text(),
2048 array(),
2049 array( 'action' => 'edit' )
2052 $outText .= '<li>' . self::link( $titleObj )
2053 . wfMessage( 'word-separator' )->escaped()
2054 . wfMessage( 'parentheses' )->rawParams( $editLink )->escaped()
2055 . wfMessage( 'word-separator' )->escaped()
2056 . $protected . '</li>';
2059 if ( $more instanceof Title ) {
2060 $outText .= '<li>' . self::link( $more, wfMessage( 'moredotdotdot' ) ) . '</li>';
2061 } elseif ( $more ) {
2062 $outText .= "<li>$more</li>";
2065 $outText .= '</ul>';
2067 wfProfileOut( __METHOD__ );
2068 return $outText;
2072 * Returns HTML for the "hidden categories on this page" list.
2074 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
2075 * or similar
2076 * @return string HTML output
2078 public static function formatHiddenCategories( $hiddencats ) {
2079 wfProfileIn( __METHOD__ );
2081 $outText = '';
2082 if ( count( $hiddencats ) > 0 ) {
2083 # Construct the HTML
2084 $outText = '<div class="mw-hiddenCategoriesExplanation">';
2085 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
2086 $outText .= "</div><ul>\n";
2088 foreach ( $hiddencats as $titleObj ) {
2089 # If it's hidden, it must exist - no need to check with a LinkBatch
2090 $outText .= '<li>'
2091 . self::link( $titleObj, null, array(), array(), 'known' )
2092 . "</li>\n";
2094 $outText .= '</ul>';
2096 wfProfileOut( __METHOD__ );
2097 return $outText;
2101 * Format a size in bytes for output, using an appropriate
2102 * unit (B, KB, MB or GB) according to the magnitude in question
2104 * @param int $size Size to format
2105 * @return string
2107 public static function formatSize( $size ) {
2108 global $wgLang;
2109 return htmlspecialchars( $wgLang->formatSize( $size ) );
2113 * Given the id of an interface element, constructs the appropriate title
2114 * attribute from the system messages. (Note, this is usually the id but
2115 * isn't always, because sometimes the accesskey needs to go on a different
2116 * element than the id, for reverse-compatibility, etc.)
2118 * @param string $name Id of the element, minus prefixes.
2119 * @param string|null $options Null or the string 'withaccess' to add an access-
2120 * key hint
2121 * @return string Contents of the title attribute (which you must HTML-
2122 * escape), or false for no title attribute
2124 public static function titleAttrib( $name, $options = null ) {
2125 wfProfileIn( __METHOD__ );
2127 $message = wfMessage( "tooltip-$name" );
2129 if ( !$message->exists() ) {
2130 $tooltip = false;
2131 } else {
2132 $tooltip = $message->text();
2133 # Compatibility: formerly some tooltips had [alt-.] hardcoded
2134 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2135 # Message equal to '-' means suppress it.
2136 if ( $tooltip == '-' ) {
2137 $tooltip = false;
2141 if ( $options == 'withaccess' ) {
2142 $accesskey = self::accesskey( $name );
2143 if ( $accesskey !== false ) {
2144 // Should be build the same as in jquery.accessKeyLabel.js
2145 if ( $tooltip === false || $tooltip === '' ) {
2146 $tooltip = wfMessage( 'brackets', $accesskey )->text();
2147 } else {
2148 $tooltip .= wfMessage( 'word-separator' )->text();
2149 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
2154 wfProfileOut( __METHOD__ );
2155 return $tooltip;
2158 private static $accesskeycache;
2161 * Given the id of an interface element, constructs the appropriate
2162 * accesskey attribute from the system messages. (Note, this is usually
2163 * the id but isn't always, because sometimes the accesskey needs to go on
2164 * a different element than the id, for reverse-compatibility, etc.)
2166 * @param string $name Id of the element, minus prefixes.
2167 * @return string Contents of the accesskey attribute (which you must HTML-
2168 * escape), or false for no accesskey attribute
2170 public static function accesskey( $name ) {
2171 if ( isset( self::$accesskeycache[$name] ) ) {
2172 return self::$accesskeycache[$name];
2174 wfProfileIn( __METHOD__ );
2176 $message = wfMessage( "accesskey-$name" );
2178 if ( !$message->exists() ) {
2179 $accesskey = false;
2180 } else {
2181 $accesskey = $message->plain();
2182 if ( $accesskey === '' || $accesskey === '-' ) {
2183 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2184 # attribute, but this is broken for accesskey: that might be a useful
2185 # value.
2186 $accesskey = false;
2190 wfProfileOut( __METHOD__ );
2191 self::$accesskeycache[$name] = $accesskey;
2192 return self::$accesskeycache[$name];
2196 * Get a revision-deletion link, or disabled link, or nothing, depending
2197 * on user permissions & the settings on the revision.
2199 * Will use forward-compatible revision ID in the Special:RevDelete link
2200 * if possible, otherwise the timestamp-based ID which may break after
2201 * undeletion.
2203 * @param User $user
2204 * @param Revision $rev
2205 * @param Revision $title
2206 * @return string HTML fragment
2208 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
2209 $canHide = $user->isAllowed( 'deleterevision' );
2210 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2211 return '';
2214 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
2215 return Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2216 } else {
2217 if ( $rev->getId() ) {
2218 // RevDelete links using revision ID are stable across
2219 // page deletion and undeletion; use when possible.
2220 $query = array(
2221 'type' => 'revision',
2222 'target' => $title->getPrefixedDBkey(),
2223 'ids' => $rev->getId()
2225 } else {
2226 // Older deleted entries didn't save a revision ID.
2227 // We have to refer to these by timestamp, ick!
2228 $query = array(
2229 'type' => 'archive',
2230 'target' => $title->getPrefixedDBkey(),
2231 'ids' => $rev->getTimestamp()
2234 return Linker::revDeleteLink( $query,
2235 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2240 * Creates a (show/hide) link for deleting revisions/log entries
2242 * @param array $query Query parameters to be passed to link()
2243 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2244 * @param bool $delete Set to true to use (show/hide) rather than (show)
2246 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2247 * span to allow for customization of appearance with CSS
2249 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
2250 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2251 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2252 $html = wfMessage( $msgKey )->escaped();
2253 $tag = $restricted ? 'strong' : 'span';
2254 $link = self::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
2255 return Xml::tags(
2256 $tag,
2257 array( 'class' => 'mw-revdelundel-link' ),
2258 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2263 * Creates a dead (show/hide) link for deleting revisions/log entries
2265 * @param bool $delete Set to true to use (show/hide) rather than (show)
2267 * @return string HTML text wrapped in a span to allow for customization
2268 * of appearance with CSS
2270 public static function revDeleteLinkDisabled( $delete = true ) {
2271 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2272 $html = wfMessage( $msgKey )->escaped();
2273 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2274 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), $htmlParentheses );
2277 /* Deprecated methods */
2280 * @deprecated since 1.16 Use link(); warnings since 1.21
2282 * Make a link for a title which may or may not be in the database. If you need to
2283 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
2284 * call to this will result in a DB query.
2286 * @param Title $nt The title object to make the link from, e.g. from Title::newFromText.
2287 * @param string $text Link text
2288 * @param string $query Optional query part
2289 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
2290 * be included in the link text. Other characters will be appended after
2291 * the end of the link.
2292 * @param string $prefix Optional prefix. As trail, only before instead of after.
2293 * @return string
2295 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
2296 wfDeprecated( __METHOD__, '1.21' );
2298 wfProfileIn( __METHOD__ );
2299 $query = wfCgiToArray( $query );
2300 list( $inside, $trail ) = self::splitTrail( $trail );
2301 if ( $text === '' ) {
2302 $text = self::linkText( $nt );
2305 $ret = self::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
2307 wfProfileOut( __METHOD__ );
2308 return $ret;
2312 * @deprecated since 1.16 Use link(); warnings since 1.21
2314 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
2315 * it doesn't have to do a database query. It's also valid for interwiki titles and special
2316 * pages.
2318 * @param Title $title Title object of target page
2319 * @param string $text Text to replace the title
2320 * @param string $query Link target
2321 * @param string $trail Text after link
2322 * @param string $prefix Text before link text
2323 * @param string $aprops Extra attributes to the a-element
2324 * @param string $style Style to apply - if empty, use getInternalLinkAttributesObj instead
2325 * @return string The a-element
2327 static function makeKnownLinkObj(
2328 $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = '', $style = ''
2330 wfDeprecated( __METHOD__, '1.21' );
2332 wfProfileIn( __METHOD__ );
2334 if ( $text == '' ) {
2335 $text = self::linkText( $title );
2337 $attribs = Sanitizer::mergeAttributes(
2338 Sanitizer::decodeTagAttributes( $aprops ),
2339 Sanitizer::decodeTagAttributes( $style )
2341 $query = wfCgiToArray( $query );
2342 list( $inside, $trail ) = self::splitTrail( $trail );
2344 $ret = self::link( $title, "$prefix$text$inside", $attribs, $query,
2345 array( 'known', 'noclasses' ) ) . $trail;
2347 wfProfileOut( __METHOD__ );
2348 return $ret;
2352 * Returns the attributes for the tooltip and access key.
2353 * @param string $name
2354 * @return array
2356 public static function tooltipAndAccesskeyAttribs( $name ) {
2357 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2358 # no attribute" instead of "output '' as value for attribute", this
2359 # would be three lines.
2360 $attribs = array(
2361 'title' => self::titleAttrib( $name, 'withaccess' ),
2362 'accesskey' => self::accesskey( $name )
2364 if ( $attribs['title'] === false ) {
2365 unset( $attribs['title'] );
2367 if ( $attribs['accesskey'] === false ) {
2368 unset( $attribs['accesskey'] );
2370 return $attribs;
2374 * Returns raw bits of HTML, use titleAttrib()
2375 * @param string $name
2376 * @param array|null $options
2377 * @return null|string
2379 public static function tooltip( $name, $options = null ) {
2380 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2381 # no attribute" instead of "output '' as value for attribute", this
2382 # would be two lines.
2383 $tooltip = self::titleAttrib( $name, $options );
2384 if ( $tooltip === false ) {
2385 return '';
2387 return Xml::expandAttributes( array(
2388 'title' => $tooltip
2389 ) );
2394 * @since 1.18
2396 class DummyLinker {
2399 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2400 * into static calls to the new Linker for backwards compatibility.
2402 * @param string $fname Name of called method
2403 * @param array $args Arguments to the method
2404 * @return mixed
2406 public function __call( $fname, $args ) {
2407 return call_user_func_array( array( 'Linker', $fname ), $args );