Merge "Combine JavaScript and JSON encoding logic"
[mediawiki.git] / includes / Linker.php
bloba347549dfdfe960b18ec4a4e744c22f6703a2b86
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 * @ingroup Skins
30 class Linker {
32 /**
33 * Flags for userToolLinks()
35 const TOOL_LINKS_NOBLOCK = 1;
36 const TOOL_LINKS_EMAIL = 2;
38 /**
39 * Get the appropriate HTML attributes to add to the "a" element of an
40 * external link, as created by [wikisyntax].
42 * @param string $class the contents of the class attribute; if an empty
43 * string is passed, which is the default value, defaults to 'external'.
44 * @return string
45 * @deprecated since 1.18 Just pass the external class directly to something using Html::expandAttributes
47 static function getExternalLinkAttributes( $class = 'external' ) {
48 wfDeprecated( __METHOD__, '1.18' );
49 return self::getLinkAttributesInternal( '', $class );
52 /**
53 * Get the appropriate HTML attributes to add to the "a" element of an interwiki link.
55 * @param string $title the title text for the link, URL-encoded (???) but
56 * not HTML-escaped
57 * @param string $unused unused
58 * @param string $class the contents of the class attribute; if an empty
59 * string is passed, which is the default value, defaults to 'external'.
60 * @return string
62 static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
63 global $wgContLang;
65 # @todo FIXME: We have a whole bunch of handling here that doesn't happen in
66 # getExternalLinkAttributes, why?
67 $title = urldecode( $title );
68 $title = $wgContLang->checkTitleEncoding( $title );
69 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
71 return self::getLinkAttributesInternal( $title, $class );
74 /**
75 * Get the appropriate HTML attributes to add to the "a" element of an internal link.
77 * @param string $title the title text for the link, URL-encoded (???) but
78 * not HTML-escaped
79 * @param string $unused unused
80 * @param string $class the contents of the class attribute, default none
81 * @return string
83 static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
84 $title = urldecode( $title );
85 $title = str_replace( '_', ' ', $title );
86 return self::getLinkAttributesInternal( $title, $class );
89 /**
90 * Get the appropriate HTML attributes to add to the "a" element of an internal
91 * link, given the Title object for the page we want to link to.
93 * @param $nt Title
94 * @param string $unused unused
95 * @param string $class the contents of the class attribute, default none
96 * @param $title Mixed: optional (unescaped) string to use in the title
97 * attribute; if false, default to the name of the page we're linking to
98 * @return string
100 static function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
101 if ( $title === false ) {
102 $title = $nt->getPrefixedText();
104 return self::getLinkAttributesInternal( $title, $class );
108 * Common code for getLinkAttributesX functions
110 * @param $title string
111 * @param $class string
113 * @return string
115 private static function getLinkAttributesInternal( $title, $class ) {
116 $title = htmlspecialchars( $title );
117 $class = htmlspecialchars( $class );
118 $r = '';
119 if ( $class != '' ) {
120 $r .= " class=\"$class\"";
122 if ( $title != '' ) {
123 $r .= " title=\"$title\"";
125 return $r;
129 * Return the CSS colour of a known link
131 * @param $t Title object
132 * @param $threshold Integer: user defined threshold
133 * @return String: CSS class
135 public static function getLinkColour( $t, $threshold ) {
136 $colour = '';
137 if ( $t->isRedirect() ) {
138 # Page is a redirect
139 $colour = 'mw-redirect';
140 } elseif ( $threshold > 0 && $t->isContentPage() &&
141 $t->exists() && $t->getLength() < $threshold
143 # Page is a stub
144 $colour = 'stub';
146 return $colour;
150 * This function returns an HTML link to the given target. It serves a few
151 * purposes:
152 * 1) If $target is a Title, the correct URL to link to will be figured
153 * out automatically.
154 * 2) It automatically adds the usual classes for various types of link
155 * targets: "new" for red links, "stub" for short articles, etc.
156 * 3) It escapes all attribute values safely so there's no risk of XSS.
157 * 4) It provides a default tooltip if the target is a Title (the page
158 * name of the target).
159 * link() replaces the old functions in the makeLink() family.
161 * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
162 * You can call it using this if you want to keep compat with these:
163 * $linker = class_exists( 'DummyLinker' ) ? new DummyLinker() : new Linker();
164 * $linker->link( ... );
166 * @param $target Title Can currently only be a Title, but this may
167 * change to support Images, literal URLs, etc.
168 * @param $html string The HTML contents of the <a> element, i.e.,
169 * the link text. This is raw HTML and will not be escaped. If null,
170 * defaults to the prefixed text of the Title; or if the Title is just a
171 * fragment, the contents of the fragment.
172 * @param array $customAttribs A key => value array of extra HTML attributes,
173 * such as title and class. (href is ignored.) Classes will be
174 * merged with the default classes, while other attributes will replace
175 * default attributes. All passed attribute values will be HTML-escaped.
176 * A false attribute value means to suppress that attribute.
177 * @param $query array The query string to append to the URL
178 * you're linking to, in key => value array form. Query keys and values
179 * will be URL-encoded.
180 * @param string|array $options String or array of strings:
181 * 'known': Page is known to exist, so don't check if it does.
182 * 'broken': Page is known not to exist, so don't check if it does.
183 * 'noclasses': Don't add any classes automatically (includes "new",
184 * "stub", "mw-redirect", "extiw"). Only use the class attribute
185 * provided, if any, so you get a simple blue link with no funny i-
186 * cons.
187 * 'forcearticlepath': Use the article path always, even with a querystring.
188 * Has compatibility issues on some setups, so avoid wherever possible.
189 * 'http': Force a full URL with http:// as the scheme.
190 * 'https': Force a full URL with https:// as the scheme.
191 * @return string HTML <a> attribute
193 public static function link(
194 $target, $html = null, $customAttribs = array(), $query = array(), $options = array()
196 wfProfileIn( __METHOD__ );
197 if ( !$target instanceof Title ) {
198 wfProfileOut( __METHOD__ );
199 return "<!-- ERROR -->$html";
202 if( is_string( $query ) ) {
203 // some functions withing core using this still hand over query strings
204 wfDeprecated( __METHOD__ . ' with parameter $query as string (should be array)', '1.20' );
205 $query = wfCgiToArray( $query );
207 $options = (array)$options;
209 $dummy = new DummyLinker; // dummy linker instance for bc on the hooks
211 $ret = null;
212 if ( !wfRunHooks( 'LinkBegin', array( $dummy, $target, &$html,
213 &$customAttribs, &$query, &$options, &$ret ) ) ) {
214 wfProfileOut( __METHOD__ );
215 return $ret;
218 # Normalize the Title if it's a special page
219 $target = self::normaliseSpecialPage( $target );
221 # If we don't know whether the page exists, let's find out.
222 wfProfileIn( __METHOD__ . '-checkPageExistence' );
223 if ( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
224 if ( $target->isKnown() ) {
225 $options[] = 'known';
226 } else {
227 $options[] = 'broken';
230 wfProfileOut( __METHOD__ . '-checkPageExistence' );
232 $oldquery = array();
233 if ( in_array( "forcearticlepath", $options ) && $query ) {
234 $oldquery = $query;
235 $query = array();
238 # Note: we want the href attribute first, for prettiness.
239 $attribs = array( 'href' => self::linkUrl( $target, $query, $options ) );
240 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
241 $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
244 $attribs = array_merge(
245 $attribs,
246 self::linkAttribs( $target, $customAttribs, $options )
248 if ( is_null( $html ) ) {
249 $html = self::linkText( $target );
252 $ret = null;
253 if ( wfRunHooks( 'LinkEnd', array( $dummy, $target, $options, &$html, &$attribs, &$ret ) ) ) {
254 $ret = Html::rawElement( 'a', $attribs, $html );
257 wfProfileOut( __METHOD__ );
258 return $ret;
262 * Identical to link(), except $options defaults to 'known'.
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 $target Title
276 * @param array $query query parameters
277 * @param $options Array
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->mFragment !== '' ) {
285 $target = clone $target;
286 $target->mFragment = '';
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 $target Title
315 * @param $attribs
316 * @param $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 $target Title
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->getFragment() !== '' ) {
391 return htmlspecialchars( $target->getFragment() );
393 return htmlspecialchars( $target->getPrefixedText() );
397 * Generate either a normal exists-style link or a stub link, depending
398 * on the given page size.
400 * @param $size Integer
401 * @param $nt Title object.
402 * @param $text String
403 * @param $query String
404 * @param $trail String
405 * @param $prefix String
406 * @return string HTML of link
407 * @deprecated since 1.17
409 static function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
410 global $wgUser;
411 wfDeprecated( __METHOD__, '1.17' );
413 $threshold = $wgUser->getStubThreshold();
414 $colour = ( $size < $threshold ) ? 'stub' : '';
415 // @todo FIXME: Replace deprecated makeColouredLinkObj by link()
416 return self::makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
420 * Make appropriate markup for a link to the current article. This is currently rendered
421 * as the bold link text. The calling sequence is the same as the other make*LinkObj static functions,
422 * despite $query not being used.
424 * @param $nt Title
425 * @param string $html [optional]
426 * @param string $query [optional]
427 * @param string $trail [optional]
428 * @param string $prefix [optional]
431 * @return string
433 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
434 if ( $html == '' ) {
435 $html = htmlspecialchars( $nt->getPrefixedText() );
437 list( $inside, $trail ) = self::splitTrail( $trail );
438 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
442 * Get a message saying that an invalid title was encountered.
443 * This should be called after a method like Title::makeTitleSafe() returned
444 * a value indicating that the title object is invalid.
446 * @param $context IContextSource context to use to get the messages
447 * @param int $namespace Namespace number
448 * @param string $title Text of the title, without the namespace part
449 * @return string
451 public static function getInvalidTitleDescription( IContextSource $context, $namespace, $title ) {
452 global $wgContLang;
454 // First we check whether the namespace exists or not.
455 if ( MWNamespace::exists( $namespace ) ) {
456 if ( $namespace == NS_MAIN ) {
457 $name = $context->msg( 'blanknamespace' )->text();
458 } else {
459 $name = $wgContLang->getFormattedNsText( $namespace );
461 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
462 } else {
463 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
468 * @param $title Title
469 * @return Title
471 static function normaliseSpecialPage( Title $title ) {
472 if ( $title->isSpecialPage() ) {
473 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
474 if ( !$name ) {
475 return $title;
477 $ret = SpecialPage::getTitleFor( $name, $subpage );
478 $ret->mFragment = $title->getFragment();
479 return $ret;
480 } else {
481 return $title;
486 * Returns the filename part of an url.
487 * Used as alternative text for external images.
489 * @param $url string
491 * @return string
493 private static function fnamePart( $url ) {
494 $basename = strrchr( $url, '/' );
495 if ( false === $basename ) {
496 $basename = $url;
497 } else {
498 $basename = substr( $basename, 1 );
500 return $basename;
504 * Return the code for images which were added via external links,
505 * via Parser::maybeMakeExternalImage().
507 * @param $url
508 * @param $alt
510 * @return string
512 public static function makeExternalImage( $url, $alt = '' ) {
513 if ( $alt == '' ) {
514 $alt = self::fnamePart( $url );
516 $img = '';
517 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
518 if ( !$success ) {
519 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
520 return $img;
522 return Html::element( 'img',
523 array(
524 'src' => $url,
525 'alt' => $alt ) );
529 * Given parameters derived from [[Image:Foo|options...]], generate the
530 * HTML that that syntax inserts in the page.
532 * @param $parser Parser object
533 * @param $title Title object of the file (not the currently viewed page)
534 * @param $file File object, or false if it doesn't exist
535 * @param array $frameParams associative array of parameters external to the media handler.
536 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
537 * will often be false.
538 * thumbnail If present, downscale and frame
539 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
540 * framed Shows image in original size in a frame
541 * frameless Downscale but don't frame
542 * upright If present, tweak default sizes for portrait orientation
543 * upright_factor Fudge factor for "upright" tweak (default 0.75)
544 * border If present, show a border around the image
545 * align Horizontal alignment (left, right, center, none)
546 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
547 * bottom, text-bottom)
548 * alt Alternate text for image (i.e. alt attribute). Plain text.
549 * class HTML for image classes. Plain text.
550 * caption HTML for image caption.
551 * link-url URL to link to
552 * link-title Title object to link to
553 * link-target Value for the target attribute, only with link-url
554 * no-link Boolean, suppress description link
556 * @param array $handlerParams associative array of media handler parameters, to be passed
557 * to transform(). Typical keys are "width" and "page".
558 * @param string $time timestamp of the file, set as false for current
559 * @param string $query query params for desc url
560 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
561 * @since 1.20
562 * @return String: HTML for an image, with links, wrappers, etc.
564 public static function makeImageLink( /*Parser*/ $parser, Title $title, $file, $frameParams = array(),
565 $handlerParams = array(), $time = false, $query = "", $widthOption = null )
567 $res = null;
568 $dummy = new DummyLinker;
569 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
570 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
571 return $res;
574 if ( $file && !$file->allowInlineDisplay() ) {
575 wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
576 return self::link( $title );
579 // Shortcuts
580 $fp =& $frameParams;
581 $hp =& $handlerParams;
583 // Clean up parameters
584 $page = isset( $hp['page'] ) ? $hp['page'] : false;
585 if ( !isset( $fp['align'] ) ) {
586 $fp['align'] = '';
588 if ( !isset( $fp['alt'] ) ) {
589 $fp['alt'] = '';
591 if ( !isset( $fp['title'] ) ) {
592 $fp['title'] = '';
594 if ( !isset( $fp['class'] ) ) {
595 $fp['class'] = '';
598 $prefix = $postfix = '';
600 if ( 'center' == $fp['align'] ) {
601 $prefix = '<div class="center">';
602 $postfix = '</div>';
603 $fp['align'] = 'none';
605 if ( $file && !isset( $hp['width'] ) ) {
606 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
607 // If its a vector image, and user only specifies height
608 // we don't want it to be limited by its "normal" width.
609 global $wgSVGMaxSize;
610 $hp['width'] = $wgSVGMaxSize;
611 } else {
612 $hp['width'] = $file->getWidth( $page );
615 if ( isset( $fp['thumbnail'] ) || isset( $fp['framed'] ) || isset( $fp['frameless'] ) || !$hp['width'] ) {
616 global $wgThumbLimits, $wgThumbUpright;
617 if ( $widthOption === null || !isset( $wgThumbLimits[$widthOption] ) ) {
618 $widthOption = User::getDefaultOption( 'thumbsize' );
621 // Reduce width for upright images when parameter 'upright' is used
622 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
623 $fp['upright'] = $wgThumbUpright;
625 // For caching health: If width scaled down due to upright parameter, round to full __0 pixel to avoid the creation of a lot of odd thumbs
626 $prefWidth = isset( $fp['upright'] ) ?
627 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
628 $wgThumbLimits[$widthOption];
630 // Use width which is smaller: real image width or user preference width
631 // Unless image is scalable vector.
632 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
633 $prefWidth < $hp['width'] || $file->isVectorized() ) ) {
634 $hp['width'] = $prefWidth;
639 if ( isset( $fp['thumbnail'] ) || isset( $fp['manualthumb'] ) || isset( $fp['framed'] ) ) {
640 # Create a thumbnail. Alignment depends on the writing direction of
641 # the page content language (right-aligned for LTR languages,
642 # left-aligned for RTL languages)
644 # If a thumbnail width has not been provided, it is set
645 # to the default user option as specified in Language*.php
646 if ( $fp['align'] == '' ) {
647 if( $parser instanceof Parser ) {
648 $fp['align'] = $parser->getTargetLanguage()->alignEnd();
649 } else {
650 # backwards compatibility, remove with makeImageLink2()
651 global $wgContLang;
652 $fp['align'] = $wgContLang->alignEnd();
655 return $prefix . self::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
658 if ( $file && isset( $fp['frameless'] ) ) {
659 $srcWidth = $file->getWidth( $page );
660 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
661 # This is the same behavior as the "thumb" option does it already.
662 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
663 $hp['width'] = $srcWidth;
667 if ( $file && isset( $hp['width'] ) ) {
668 # Create a resized image, without the additional thumbnail features
669 $thumb = $file->transform( $hp );
670 } else {
671 $thumb = false;
674 if ( !$thumb ) {
675 $s = self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
676 } else {
677 self::processResponsiveImages( $file, $thumb, $hp );
678 $params = array(
679 'alt' => $fp['alt'],
680 'title' => $fp['title'],
681 'valign' => isset( $fp['valign'] ) ? $fp['valign'] : false,
682 'img-class' => $fp['class'] );
683 if ( isset( $fp['border'] ) ) {
684 // TODO: BUG? Both values are identical
685 $params['img-class'] .= ( $params['img-class'] !== '' ) ? ' thumbborder' : 'thumbborder';
687 $params = self::getImageLinkMTOParams( $fp, $query, $parser ) + $params;
689 $s = $thumb->toHtml( $params );
691 if ( $fp['align'] != '' ) {
692 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
694 return str_replace( "\n", ' ', $prefix . $s . $postfix );
698 * See makeImageLink()
699 * When this function is removed, remove if( $parser instanceof Parser ) check there too
700 * @deprecated since 1.20
702 public static function makeImageLink2( Title $title, $file, $frameParams = array(),
703 $handlerParams = array(), $time = false, $query = "", $widthOption = null ) {
704 return self::makeImageLink( null, $title, $file, $frameParams,
705 $handlerParams, $time, $query, $widthOption );
709 * Get the link parameters for MediaTransformOutput::toHtml() from given
710 * frame parameters supplied by the Parser.
711 * @param array $frameParams The frame parameters
712 * @param string $query An optional query string to add to description page links
713 * @return array
715 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
716 $mtoParams = array();
717 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
718 $mtoParams['custom-url-link'] = $frameParams['link-url'];
719 if ( isset( $frameParams['link-target'] ) ) {
720 $mtoParams['custom-target-link'] = $frameParams['link-target'];
722 if ( $parser ) {
723 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
724 foreach ( $extLinkAttrs as $name => $val ) {
725 // Currently could include 'rel' and 'target'
726 $mtoParams['parser-extlink-' . $name] = $val;
729 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
730 $mtoParams['custom-title-link'] = self::normaliseSpecialPage( $frameParams['link-title'] );
731 } elseif ( !empty( $frameParams['no-link'] ) ) {
732 // No link
733 } else {
734 $mtoParams['desc-link'] = true;
735 $mtoParams['desc-query'] = $query;
737 return $mtoParams;
741 * Make HTML for a thumbnail including image, border and caption
742 * @param $title Title object
743 * @param $file File object or false if it doesn't exist
744 * @param $label String
745 * @param $alt String
746 * @param $align String
747 * @param $params Array
748 * @param $framed Boolean
749 * @param $manualthumb String
750 * @return mixed
752 public static function makeThumbLinkObj( Title $title, $file, $label = '', $alt,
753 $align = 'right', $params = array(), $framed = false, $manualthumb = "" )
755 $frameParams = array(
756 'alt' => $alt,
757 'caption' => $label,
758 'align' => $align
760 if ( $framed ) {
761 $frameParams['framed'] = true;
763 if ( $manualthumb ) {
764 $frameParams['manualthumb'] = $manualthumb;
766 return self::makeThumbLink2( $title, $file, $frameParams, $params );
770 * @param $title Title
771 * @param $file File
772 * @param array $frameParams
773 * @param array $handlerParams
774 * @param bool $time
775 * @param string $query
776 * @return mixed
778 public static function makeThumbLink2( Title $title, $file, $frameParams = array(),
779 $handlerParams = array(), $time = false, $query = "" )
781 global $wgStylePath, $wgContLang;
782 $exists = $file && $file->exists();
784 # Shortcuts
785 $fp =& $frameParams;
786 $hp =& $handlerParams;
788 $page = isset( $hp['page'] ) ? $hp['page'] : false;
789 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
790 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
791 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
792 if ( !isset( $fp['caption'] ) ) $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;
801 if ( !$exists ) {
802 $outerWidth = $hp['width'] + 2;
803 } else {
804 if ( isset( $fp['manualthumb'] ) ) {
805 # Use manually specified thumbnail
806 $manual_title = Title::makeTitleSafe( NS_FILE, $fp['manualthumb'] );
807 if ( $manual_title ) {
808 $manual_img = wfFindFile( $manual_title );
809 if ( $manual_img ) {
810 $thumb = $manual_img->getUnscaledThumb( $hp );
811 } else {
812 $exists = false;
815 } elseif ( isset( $fp['framed'] ) ) {
816 // Use image dimensions, don't scale
817 $thumb = $file->getUnscaledThumb( $hp );
818 $noscale = true;
819 } else {
820 # Do not present an image bigger than the source, for bitmap-style images
821 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
822 $srcWidth = $file->getWidth( $page );
823 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
824 $hp['width'] = $srcWidth;
826 $thumb = $file->transform( $hp );
829 if ( $thumb ) {
830 $outerWidth = $thumb->getWidth() + 2;
831 } else {
832 $outerWidth = $hp['width'] + 2;
836 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
837 # So we don't need to pass it here in $query. However, the URL for the
838 # zoom icon still needs it, so we make a unique query for it. See bug 14771
839 $url = $title->getLocalURL( $query );
840 if ( $page ) {
841 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
844 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
845 if ( !$exists ) {
846 $s .= self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
847 $zoomIcon = '';
848 } elseif ( !$thumb ) {
849 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
850 $zoomIcon = '';
851 } else {
852 if ( !$noscale ) {
853 self::processResponsiveImages( $file, $thumb, $hp );
855 $params = array(
856 'alt' => $fp['alt'],
857 'title' => $fp['title'],
858 'img-class' => ( isset( $fp['class'] ) && $fp['class'] !== '' ) ? $fp['class'] . ' thumbimage' : 'thumbimage'
860 $params = self::getImageLinkMTOParams( $fp, $query ) + $params;
861 $s .= $thumb->toHtml( $params );
862 if ( isset( $fp['framed'] ) ) {
863 $zoomIcon = "";
864 } else {
865 $zoomIcon = Html::rawElement( 'div', array( 'class' => 'magnify' ),
866 Html::rawElement( 'a', array(
867 'href' => $url,
868 'class' => 'internal',
869 'title' => wfMessage( 'thumbnail-more' )->text() ),
870 Html::element( 'img', array(
871 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ? '-rtl' : '' ) . '.png',
872 'width' => 15,
873 'height' => 11,
874 'alt' => "" ) ) ) );
877 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
878 return str_replace( "\n", ' ', $s );
882 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
883 * applicable.
885 * @param File $file
886 * @param MediaOutput $thumb
887 * @param array $hp image parameters
889 protected static function processResponsiveImages( $file, $thumb, $hp ) {
890 global $wgResponsiveImages;
891 if ( $wgResponsiveImages ) {
892 $hp15 = $hp;
893 $hp15['width'] = round( $hp['width'] * 1.5 );
894 $hp20 = $hp;
895 $hp20['width'] = $hp['width'] * 2;
896 if ( isset( $hp['height'] ) ) {
897 $hp15['height'] = round( $hp['height'] * 1.5 );
898 $hp20['height'] = $hp['height'] * 2;
901 $thumb15 = $file->transform( $hp15 );
902 $thumb20 = $file->transform( $hp20 );
903 if ( $thumb15->url !== $thumb->url ) {
904 $thumb->responsiveUrls['1.5'] = $thumb15->url;
906 if ( $thumb20->url !== $thumb->url ) {
907 $thumb->responsiveUrls['2'] = $thumb20->url;
913 * Make a "broken" link to an image
915 * @param $title Title object
916 * @param string $label link label (plain text)
917 * @param string $query query string
918 * @param $unused1 Unused parameter kept for b/c
919 * @param $unused2 Unused parameter kept for b/c
920 * @param $time Boolean: a file of a certain timestamp was requested
921 * @return String
923 public static function makeBrokenImageLinkObj( $title, $label = '', $query = '', $unused1 = '', $unused2 = '', $time = false ) {
924 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
925 if ( ! $title instanceof Title ) {
926 return "<!-- ERROR -->" . htmlspecialchars( $label );
928 wfProfileIn( __METHOD__ );
929 if ( $label == '' ) {
930 $label = $title->getPrefixedText();
932 $encLabel = htmlspecialchars( $label );
933 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
935 if ( ( $wgUploadMissingFileUrl || $wgUploadNavigationUrl || $wgEnableUploads ) && !$currentExists ) {
936 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
938 if ( $redir ) {
939 wfProfileOut( __METHOD__ );
940 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
943 $href = self::getUploadUrl( $title, $query );
945 wfProfileOut( __METHOD__ );
946 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
947 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES ) . '">' .
948 $encLabel . '</a>';
951 wfProfileOut( __METHOD__ );
952 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
956 * Get the URL to upload a certain file
958 * @param $destFile Title object of the file to upload
959 * @param string $query urlencoded query string to prepend
960 * @return String: urlencoded URL
962 protected static function getUploadUrl( $destFile, $query = '' ) {
963 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
964 $q = 'wpDestFile=' . $destFile->getPartialURL();
965 if ( $query != '' )
966 $q .= '&' . $query;
968 if ( $wgUploadMissingFileUrl ) {
969 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
970 } elseif( $wgUploadNavigationUrl ) {
971 return wfAppendQuery( $wgUploadNavigationUrl, $q );
972 } else {
973 $upload = SpecialPage::getTitleFor( 'Upload' );
974 return $upload->getLocalURL( $q );
979 * Create a direct link to a given uploaded file.
981 * @param $title Title object.
982 * @param string $html pre-sanitized HTML
983 * @param string $time MW timestamp of file creation time
984 * @return String: HTML
986 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
987 $img = wfFindFile( $title, array( 'time' => $time ) );
988 return self::makeMediaLinkFile( $title, $img, $html );
992 * Create a direct link to a given uploaded file.
993 * This will make a broken link if $file is false.
995 * @param $title Title object.
996 * @param $file File|bool mixed File object or false
997 * @param string $html pre-sanitized HTML
998 * @return String: HTML
1000 * @todo Handle invalid or missing images better.
1002 public static function makeMediaLinkFile( Title $title, $file, $html = '' ) {
1003 if ( $file && $file->exists() ) {
1004 $url = $file->getURL();
1005 $class = 'internal';
1006 } else {
1007 $url = self::getUploadUrl( $title );
1008 $class = 'new';
1010 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES );
1011 if ( $html == '' ) {
1012 $html = $alt;
1014 $u = htmlspecialchars( $url );
1015 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$html}</a>";
1019 * Make a link to a special page given its name and, optionally,
1020 * a message key from the link text.
1021 * Usage example: Linker::specialLink( 'Recentchanges' )
1023 * @return string
1025 public static function specialLink( $name, $key = '' ) {
1026 if ( $key == '' ) {
1027 $key = strtolower( $name );
1030 return self::linkKnown( SpecialPage::getTitleFor( $name ), wfMessage( $key )->text() );
1034 * Make an external link
1035 * @param string $url URL to link to
1036 * @param string $text text of link
1037 * @param $escape Boolean: do we escape the link text?
1038 * @param string $linktype type of external link. Gets added to the classes
1039 * @param array $attribs of extra attributes to <a>
1040 * @param $title Title|null Title object used for title specific link attributes
1041 * @return string
1043 public static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array(), $title = null ) {
1044 global $wgTitle;
1045 $class = "external";
1046 if ( $linktype ) {
1047 $class .= " $linktype";
1049 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1050 $class .= " {$attribs['class']}";
1052 $attribs['class'] = $class;
1054 if ( $escape ) {
1055 $text = htmlspecialchars( $text );
1058 if ( !$title ) {
1059 $title = $wgTitle;
1061 $attribs['rel'] = Parser::getExternalLinkRel( $url, $title );
1062 $link = '';
1063 $success = wfRunHooks( 'LinkerMakeExternalLink',
1064 array( &$url, &$text, &$link, &$attribs, $linktype ) );
1065 if ( !$success ) {
1066 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
1067 return $link;
1069 $attribs['href'] = $url;
1070 return Html::rawElement( 'a', $attribs, $text );
1074 * Make user link (or user contributions for unregistered users)
1075 * @param $userId Integer: user id in database.
1076 * @param string $userName user name in database.
1077 * @param string $altUserName text to display instead of the user name (optional)
1078 * @return String: HTML fragment
1079 * @since 1.19 Method exists for a long time. $altUserName was added in 1.19.
1081 public static function userLink( $userId, $userName, $altUserName = false ) {
1082 if ( $userId == 0 ) {
1083 $page = SpecialPage::getTitleFor( 'Contributions', $userName );
1084 if ( $altUserName === false ) {
1085 $altUserName = IP::prettifyIP( $userName );
1087 } else {
1088 $page = Title::makeTitle( NS_USER, $userName );
1091 return self::link(
1092 $page,
1093 htmlspecialchars( $altUserName !== false ? $altUserName : $userName ),
1094 array( 'class' => 'mw-userlink' )
1099 * Generate standard user tool links (talk, contributions, block link, etc.)
1101 * @param $userId Integer: user identifier
1102 * @param string $userText user name or IP address
1103 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
1104 * red if the user has no edits?
1105 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK and Linker::TOOL_LINKS_EMAIL)
1106 * @param $edits Integer: user edit count (optional, for performance)
1107 * @return String: HTML fragment
1109 public static function userToolLinks(
1110 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1112 global $wgUser, $wgDisableAnonTalk, $wgLang;
1113 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1114 $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1115 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1117 $items = array();
1118 if ( $talkable ) {
1119 $items[] = self::userTalkLink( $userId, $userText );
1121 if ( $userId ) {
1122 // check if the user has an edit
1123 $attribs = array();
1124 if ( $redContribsWhenNoEdits ) {
1125 if ( intval( $edits ) === 0 && $edits !== 0 ) {
1126 $user = User::newFromId( $userId );
1127 $edits = $user->getEditCount();
1129 if ( $edits === 0 ) {
1130 $attribs['class'] = 'new';
1133 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1135 $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1137 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1138 $items[] = self::blockLink( $userId, $userText );
1141 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1142 $items[] = self::emailLink( $userId, $userText );
1145 wfRunHooks( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1147 if ( $items ) {
1148 return wfMessage( 'word-separator' )->plain()
1149 . '<span class="mw-usertoollinks">'
1150 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1151 . '</span>';
1152 } else {
1153 return '';
1158 * Alias for userToolLinks( $userId, $userText, true );
1159 * @param $userId Integer: user identifier
1160 * @param string $userText user name or IP address
1161 * @param $edits Integer: user edit count (optional, for performance)
1162 * @return String
1164 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1165 return self::userToolLinks( $userId, $userText, true, 0, $edits );
1169 * @param $userId Integer: user id in database.
1170 * @param string $userText user name in database.
1171 * @return String: HTML fragment with user talk link
1173 public static function userTalkLink( $userId, $userText ) {
1174 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1175 $userTalkLink = self::link( $userTalkPage, wfMessage( 'talkpagelinktext' )->escaped() );
1176 return $userTalkLink;
1180 * @param $userId Integer: userid
1181 * @param string $userText user name in database.
1182 * @return String: HTML fragment with block link
1184 public static function blockLink( $userId, $userText ) {
1185 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1186 $blockLink = self::link( $blockPage, wfMessage( 'blocklink' )->escaped() );
1187 return $blockLink;
1191 * @param $userId Integer: userid
1192 * @param string $userText user name in database.
1193 * @return String: HTML fragment with e-mail user link
1195 public static function emailLink( $userId, $userText ) {
1196 $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1197 $emailLink = self::link( $emailPage, wfMessage( 'emaillink' )->escaped() );
1198 return $emailLink;
1202 * Generate a user link if the current user is allowed to view it
1203 * @param $rev Revision object.
1204 * @param $isPublic Boolean: show only if all users can see it
1205 * @return String: HTML fragment
1207 public static function revUserLink( $rev, $isPublic = false ) {
1208 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1209 $link = wfMessage( 'rev-deleted-user' )->escaped();
1210 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1211 $link = self::userLink( $rev->getUser( Revision::FOR_THIS_USER ),
1212 $rev->getUserText( Revision::FOR_THIS_USER ) );
1213 } else {
1214 $link = wfMessage( 'rev-deleted-user' )->escaped();
1216 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1217 return '<span class="history-deleted">' . $link . '</span>';
1219 return $link;
1223 * Generate a user tool link cluster if the current user is allowed to view it
1224 * @param $rev Revision object.
1225 * @param $isPublic Boolean: show only if all users can see it
1226 * @return string HTML
1228 public static function revUserTools( $rev, $isPublic = false ) {
1229 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1230 $link = wfMessage( 'rev-deleted-user' )->escaped();
1231 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1232 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1233 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1234 $link = self::userLink( $userId, $userText )
1235 . wfMessage( 'word-separator' )->plain()
1236 . self::userToolLinks( $userId, $userText );
1237 } else {
1238 $link = wfMessage( 'rev-deleted-user' )->escaped();
1240 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1241 return ' <span class="history-deleted">' . $link . '</span>';
1243 return $link;
1247 * This function is called by all recent changes variants, by the page history,
1248 * and by the user contributions list. It is responsible for formatting edit
1249 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1250 * auto-generated comments (from section editing) and formats [[wikilinks]].
1252 * @author Erik Moeller <moeller@scireview.de>
1254 * Note: there's not always a title to pass to this function.
1255 * Since you can't set a default parameter for a reference, I've turned it
1256 * temporarily to a value pass. Should be adjusted further. --brion
1258 * @param $comment String
1259 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1260 * @param $local Boolean: whether section links should refer to local page
1261 * @return mixed|String
1263 public static function formatComment( $comment, $title = null, $local = false ) {
1264 wfProfileIn( __METHOD__ );
1266 # Sanitize text a bit:
1267 $comment = str_replace( "\n", " ", $comment );
1268 # Allow HTML entities (for bug 13815)
1269 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1271 # Render autocomments and make links:
1272 $comment = self::formatAutocomments( $comment, $title, $local );
1273 $comment = self::formatLinksInComment( $comment, $title, $local );
1275 wfProfileOut( __METHOD__ );
1276 return $comment;
1280 * @var Title
1282 static $autocommentTitle;
1283 static $autocommentLocal;
1286 * Converts autogenerated comments in edit summaries into section links.
1287 * The pattern for autogen comments is / * foo * /, which makes for
1288 * some nasty regex.
1289 * We look for all comments, match any text before and after the comment,
1290 * add a separator where needed and format the comment itself with CSS
1291 * Called by Linker::formatComment.
1293 * @param string $comment comment text
1294 * @param $title Title|null An optional title object used to links to sections
1295 * @param $local Boolean: whether section links should refer to local page
1296 * @return String: formatted comment
1298 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1299 // Bah!
1300 self::$autocommentTitle = $title;
1301 self::$autocommentLocal = $local;
1302 $comment = preg_replace_callback(
1303 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1304 array( 'Linker', 'formatAutocommentsCallback' ),
1305 $comment );
1306 self::$autocommentTitle = null;
1307 self::$autocommentLocal = null;
1308 return $comment;
1312 * Helper function for Linker::formatAutocomments
1313 * @param $match
1314 * @return string
1316 private static function formatAutocommentsCallback( $match ) {
1317 global $wgLang;
1318 $title = self::$autocommentTitle;
1319 $local = self::$autocommentLocal;
1321 $pre = $match[1];
1322 $auto = $match[2];
1323 $post = $match[3];
1324 $comment = null;
1325 wfRunHooks( 'FormatAutocomments', array( &$comment, $pre, $auto, $post, $title, $local ) );
1326 if ( $comment === null ) {
1327 $link = '';
1328 if ( $title ) {
1329 $section = $auto;
1331 # Remove links that a user may have manually put in the autosummary
1332 # This could be improved by copying as much of Parser::stripSectionName as desired.
1333 $section = str_replace( '[[:', '', $section );
1334 $section = str_replace( '[[', '', $section );
1335 $section = str_replace( ']]', '', $section );
1337 $section = Sanitizer::normalizeSectionNameWhitespace( $section ); # bug 22784
1338 if ( $local ) {
1339 $sectionTitle = Title::newFromText( '#' . $section );
1340 } else {
1341 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1342 $title->getDBkey(), $section );
1344 if ( $sectionTitle ) {
1345 $link = self::link( $sectionTitle,
1346 $wgLang->getArrow(), array(), array(),
1347 'noclasses' );
1348 } else {
1349 $link = '';
1352 if ( $pre ) {
1353 # written summary $presep autocomment (summary /* section */)
1354 $pre .= wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1356 if ( $post ) {
1357 # autocomment $postsep written summary (/* section */ summary)
1358 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1360 $auto = '<span class="autocomment">' . $auto . '</span>';
1361 $comment = $pre . $link . $wgLang->getDirMark() . '<span dir="auto">' . $auto . $post . '</span>';
1363 return $comment;
1367 * @var Title
1369 static $commentContextTitle;
1370 static $commentLocal;
1373 * Formats wiki links and media links in text; all other wiki formatting
1374 * is ignored
1376 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1377 * @param string $comment text to format links in
1378 * @param $title Title|null An optional title object used to links to sections
1379 * @param $local Boolean: whether section links should refer to local page
1380 * @return String
1382 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1383 self::$commentContextTitle = $title;
1384 self::$commentLocal = $local;
1385 $html = preg_replace_callback(
1387 \[\[
1388 :? # ignore optional leading colon
1389 ([^\]|]+) # 1. link target; page names cannot include ] or |
1390 (?:\|
1391 # 2. a pipe-separated substring; only the last is captured
1392 # Stop matching at | and ]] without relying on backtracking.
1393 ((?:]?[^\]|])*+)
1395 \]\]
1396 ([^[]*) # 3. link trail (the text up until the next link)
1397 /x',
1398 array( 'Linker', 'formatLinksInCommentCallback' ),
1399 $comment );
1400 self::$commentContextTitle = null;
1401 self::$commentLocal = null;
1402 return $html;
1406 * @param $match
1407 * @return mixed
1409 protected static function formatLinksInCommentCallback( $match ) {
1410 global $wgContLang;
1412 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1413 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1415 $comment = $match[0];
1417 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1418 if ( strpos( $match[1], '%' ) !== false ) {
1419 $match[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $match[1] ) );
1422 # Handle link renaming [[foo|text]] will show link as "text"
1423 if ( $match[2] != "" ) {
1424 $text = $match[2];
1425 } else {
1426 $text = $match[1];
1428 $submatch = array();
1429 $thelink = null;
1430 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1431 # Media link; trail not supported.
1432 $linkRegexp = '/\[\[(.*?)\]\]/';
1433 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1434 if ( $title ) {
1435 $thelink = self::makeMediaLinkObj( $title, $text );
1437 } else {
1438 # Other kind of link
1439 if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1440 $trail = $submatch[1];
1441 } else {
1442 $trail = "";
1444 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1445 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1446 $match[1] = substr( $match[1], 1 );
1447 list( $inside, $trail ) = self::splitTrail( $trail );
1449 $linkText = $text;
1450 $linkTarget = self::normalizeSubpageLink( self::$commentContextTitle,
1451 $match[1], $linkText );
1453 $target = Title::newFromText( $linkTarget );
1454 if ( $target ) {
1455 if ( $target->getText() == '' && $target->getInterwiki() === ''
1456 && !self::$commentLocal && self::$commentContextTitle )
1458 $newTarget = clone ( self::$commentContextTitle );
1459 $newTarget->setFragment( '#' . $target->getFragment() );
1460 $target = $newTarget;
1462 $thelink = self::link(
1463 $target,
1464 $linkText . $inside
1465 ) . $trail;
1468 if ( $thelink ) {
1469 // If the link is still valid, go ahead and replace it in!
1470 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1473 return $comment;
1477 * @param $contextTitle Title
1478 * @param $target
1479 * @param $text
1480 * @return string
1482 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1483 # Valid link forms:
1484 # Foobar -- normal
1485 # :Foobar -- override special treatment of prefix (images, language links)
1486 # /Foobar -- convert to CurrentPage/Foobar
1487 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1488 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1489 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1491 wfProfileIn( __METHOD__ );
1492 $ret = $target; # default return value is no change
1494 # Some namespaces don't allow subpages,
1495 # so only perform processing if subpages are allowed
1496 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1497 $hash = strpos( $target, '#' );
1498 if ( $hash !== false ) {
1499 $suffix = substr( $target, $hash );
1500 $target = substr( $target, 0, $hash );
1501 } else {
1502 $suffix = '';
1504 # bug 7425
1505 $target = trim( $target );
1506 # Look at the first character
1507 if ( $target != '' && $target[0] === '/' ) {
1508 # / at end means we don't want the slash to be shown
1509 $m = array();
1510 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1511 if ( $trailingSlashes ) {
1512 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1513 } else {
1514 $noslash = substr( $target, 1 );
1517 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1518 if ( $text === '' ) {
1519 $text = $target . $suffix;
1520 } # this might be changed for ugliness reasons
1521 } else {
1522 # check for .. subpage backlinks
1523 $dotdotcount = 0;
1524 $nodotdot = $target;
1525 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1526 ++$dotdotcount;
1527 $nodotdot = substr( $nodotdot, 3 );
1529 if ( $dotdotcount > 0 ) {
1530 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1531 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1532 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1533 # / at the end means don't show full path
1534 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1535 $nodotdot = substr( $nodotdot, 0, -1 );
1536 if ( $text === '' ) {
1537 $text = $nodotdot . $suffix;
1540 $nodotdot = trim( $nodotdot );
1541 if ( $nodotdot != '' ) {
1542 $ret .= '/' . $nodotdot;
1544 $ret .= $suffix;
1550 wfProfileOut( __METHOD__ );
1551 return $ret;
1555 * Wrap a comment in standard punctuation and formatting if
1556 * it's non-empty, otherwise return empty string.
1558 * @param $comment String
1559 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1560 * @param $local Boolean: whether section links should refer to local page
1562 * @return string
1564 public static function commentBlock( $comment, $title = null, $local = false ) {
1565 // '*' used to be the comment inserted by the software way back
1566 // in antiquity in case none was provided, here for backwards
1567 // compatibility, acc. to brion -ævar
1568 if ( $comment == '' || $comment == '*' ) {
1569 return '';
1570 } else {
1571 $formatted = self::formatComment( $comment, $title, $local );
1572 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1573 return " <span class=\"comment\">$formatted</span>";
1578 * Wrap and format the given revision's comment block, if the current
1579 * user is allowed to view it.
1581 * @param $rev Revision object
1582 * @param $local Boolean: whether section links should refer to local page
1583 * @param $isPublic Boolean: show only if all users can see it
1584 * @return String: HTML fragment
1586 public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1587 if ( $rev->getRawComment() == "" ) {
1588 return "";
1590 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1591 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1592 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1593 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1594 $rev->getTitle(), $local );
1595 } else {
1596 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1598 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1599 return " <span class=\"history-deleted\">$block</span>";
1601 return $block;
1605 * @param $size
1606 * @return string
1608 public static function formatRevisionSize( $size ) {
1609 if ( $size == 0 ) {
1610 $stxt = wfMessage( 'historyempty' )->escaped();
1611 } else {
1612 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1613 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1615 return "<span class=\"history-size\">$stxt</span>";
1619 * Add another level to the Table of Contents
1621 * @return string
1623 public static function tocIndent() {
1624 return "\n<ul>";
1628 * Finish one or more sublevels on the Table of Contents
1630 * @return string
1632 public static function tocUnindent( $level ) {
1633 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1637 * parameter level defines if we are on an indentation level
1639 * @return string
1641 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1642 $classes = "toclevel-$level";
1643 if ( $sectionIndex !== false ) {
1644 $classes .= " tocsection-$sectionIndex";
1646 return "\n<li class=\"$classes\"><a href=\"#" .
1647 $anchor . '"><span class="tocnumber">' .
1648 $tocnumber . '</span> <span class="toctext">' .
1649 $tocline . '</span></a>';
1653 * End a Table Of Contents line.
1654 * tocUnindent() will be used instead if we're ending a line below
1655 * the new level.
1656 * @return string
1658 public static function tocLineEnd() {
1659 return "</li>\n";
1663 * Wraps the TOC in a table and provides the hide/collapse javascript.
1665 * @param string $toc html of the Table Of Contents
1666 * @param $lang String|Language|false: Language for the toc title, defaults to user language
1667 * @return String: full html of the TOC
1669 public static function tocList( $toc, $lang = false ) {
1670 $lang = wfGetLangObj( $lang );
1671 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1673 return '<table id="toc" class="toc"><tr><td>'
1674 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1675 . $toc
1676 . "</ul>\n</td></tr></table>\n";
1680 * Generate a table of contents from a section tree
1681 * Currently unused.
1683 * @param array $tree Return value of ParserOutput::getSections()
1684 * @return String: HTML fragment
1686 public static function generateTOC( $tree ) {
1687 $toc = '';
1688 $lastLevel = 0;
1689 foreach ( $tree as $section ) {
1690 if ( $section['toclevel'] > $lastLevel )
1691 $toc .= self::tocIndent();
1692 elseif ( $section['toclevel'] < $lastLevel )
1693 $toc .= self::tocUnindent(
1694 $lastLevel - $section['toclevel'] );
1695 else
1696 $toc .= self::tocLineEnd();
1698 $toc .= self::tocLine( $section['anchor'],
1699 $section['line'], $section['number'],
1700 $section['toclevel'], $section['index'] );
1701 $lastLevel = $section['toclevel'];
1703 $toc .= self::tocLineEnd();
1704 return self::tocList( $toc );
1708 * Create a headline for content
1710 * @param $level Integer: the level of the headline (1-6)
1711 * @param string $attribs any attributes for the headline, starting with
1712 * a space and ending with '>'
1713 * This *must* be at least '>' for no attribs
1714 * @param string $anchor the anchor to give the headline (the bit after the #)
1715 * @param string $html html for the text of the header
1716 * @param string $link HTML to add for the section edit link
1717 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1718 * backward compatibility (false to omit)
1720 * @return String: HTML headline
1722 public static function makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor = false ) {
1723 $ret = "<h$level$attribs"
1724 . $link
1725 . " <span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1726 . "</h$level>";
1727 if ( $legacyAnchor !== false ) {
1728 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1730 return $ret;
1734 * Split a link trail, return the "inside" portion and the remainder of the trail
1735 * as a two-element array
1736 * @return array
1738 static function splitTrail( $trail ) {
1739 global $wgContLang;
1740 $regex = $wgContLang->linkTrail();
1741 $inside = '';
1742 if ( $trail !== '' ) {
1743 $m = array();
1744 if ( preg_match( $regex, $trail, $m ) ) {
1745 $inside = $m[1];
1746 $trail = $m[2];
1749 return array( $inside, $trail );
1753 * Generate a rollback link for a given revision. Currently it's the
1754 * caller's responsibility to ensure that the revision is the top one. If
1755 * it's not, of course, the user will get an error message.
1757 * If the calling page is called with the parameter &bot=1, all rollback
1758 * links also get that parameter. It causes the edit itself and the rollback
1759 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1760 * changes, so this allows sysops to combat a busy vandal without bothering
1761 * other users.
1763 * If the option verify is set this function will return the link only in case the
1764 * revision can be reverted. Please note that due to performance limitations
1765 * it might be assumed that a user isn't the only contributor of a page while
1766 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1767 * work if $wgShowRollbackEditCount is disabled, so this can only function
1768 * as an additional check.
1770 * If the option noBrackets is set the rollback link wont be enclosed in []
1772 * @param $rev Revision object
1773 * @param $context IContextSource context to use or null for the main context.
1774 * @param $options array
1775 * @return string
1777 public static function generateRollback( $rev, IContextSource $context = null, $options = array( 'verify' ) ) {
1778 if ( $context === null ) {
1779 $context = RequestContext::getMain();
1781 $editCount = false;
1782 if ( in_array( 'verify', $options ) ) {
1783 $editCount = self::getRollbackEditCount( $rev, true );
1784 if ( $editCount === false ) {
1785 return '';
1789 $inner = self::buildRollbackLink( $rev, $context, $editCount );
1791 if ( !in_array( 'noBrackets', $options ) ) {
1792 $inner = $context->msg( 'brackets' )->rawParams( $inner )->plain();
1795 return '<span class="mw-rollback-link">' . $inner . '</span>';
1799 * This function will return the number of revisions which a rollback
1800 * would revert and, if $verify is set it will verify that a revision
1801 * can be reverted (that the user isn't the only contributor and the
1802 * revision we might rollback to isn't deleted). These checks can only
1803 * function as an additional check as this function only checks against
1804 * the last $wgShowRollbackEditCount edits.
1806 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1807 * is set and the user is the only contributor of the page.
1809 * @param $rev Revision object
1810 * @param bool $verify Try to verify that this revision can really be rolled back
1811 * @return integer|bool|null
1813 public static function getRollbackEditCount( $rev, $verify ) {
1814 global $wgShowRollbackEditCount;
1815 if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
1816 // Nothing has happened, indicate this by returning 'null'
1817 return null;
1820 $dbr = wfGetDB( DB_SLAVE );
1822 // Up to the value of $wgShowRollbackEditCount revisions are counted
1823 $res = $dbr->select(
1824 'revision',
1825 array( 'rev_user_text', 'rev_deleted' ),
1826 // $rev->getPage() returns null sometimes
1827 array( 'rev_page' => $rev->getTitle()->getArticleID() ),
1828 __METHOD__,
1829 array(
1830 'USE INDEX' => array( 'revision' => 'page_timestamp' ),
1831 'ORDER BY' => 'rev_timestamp DESC',
1832 'LIMIT' => $wgShowRollbackEditCount + 1
1836 $editCount = 0;
1837 $moreRevs = false;
1838 foreach ( $res as $row ) {
1839 if ( $rev->getRawUserText() != $row->rev_user_text ) {
1840 if ( $verify && ( $row->rev_deleted & Revision::DELETED_TEXT || $row->rev_deleted & Revision::DELETED_USER ) ) {
1841 // If the user or the text of the revision we might rollback to is deleted in some way we can't rollback
1842 // Similar to the sanity checks in WikiPage::commitRollback
1843 return false;
1845 $moreRevs = true;
1846 break;
1848 $editCount++;
1851 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1852 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1853 // and there weren't any other revisions. That means that the current user is the only
1854 // editor, so we can't rollback
1855 return false;
1857 return $editCount;
1861 * Build a raw rollback link, useful for collections of "tool" links
1863 * @param $rev Revision object
1864 * @param $context IContextSource context to use or null for the main context.
1865 * @param $editCount integer Number of edits that would be reverted
1866 * @return String: HTML fragment
1868 public static function buildRollbackLink( $rev, IContextSource $context = null, $editCount = false ) {
1869 global $wgShowRollbackEditCount, $wgMiserMode;
1871 // To config which pages are effected by miser mode
1872 $disableRollbackEditCountSpecialPage = array( 'Recentchanges', 'Watchlist' );
1874 if ( $context === null ) {
1875 $context = RequestContext::getMain();
1878 $title = $rev->getTitle();
1879 $query = array(
1880 'action' => 'rollback',
1881 'from' => $rev->getUserText(),
1882 'token' => $context->getUser()->getEditToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1884 if ( $context->getRequest()->getBool( 'bot' ) ) {
1885 $query['bot'] = '1';
1886 $query['hidediff'] = '1'; // bug 15999
1889 $disableRollbackEditCount = false;
1890 if( $wgMiserMode ) {
1891 foreach( $disableRollbackEditCountSpecialPage as $specialPage ) {
1892 if( $context->getTitle()->isSpecial( $specialPage ) ) {
1893 $disableRollbackEditCount = true;
1894 break;
1899 if( !$disableRollbackEditCount && is_int( $wgShowRollbackEditCount ) && $wgShowRollbackEditCount > 0 ) {
1900 if ( !is_numeric( $editCount ) ) {
1901 $editCount = self::getRollbackEditCount( $rev, false );
1904 if( $editCount > $wgShowRollbackEditCount ) {
1905 $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )->numParams( $wgShowRollbackEditCount )->parse();
1906 } else {
1907 $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1910 return self::link(
1911 $title,
1912 $editCount_output,
1913 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1914 $query,
1915 array( 'known', 'noclasses' )
1917 } else {
1918 return self::link(
1919 $title,
1920 $context->msg( 'rollbacklink' )->escaped(),
1921 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1922 $query,
1923 array( 'known', 'noclasses' )
1929 * Returns HTML for the "templates used on this page" list.
1931 * Make an HTML list of templates, and then add a "More..." link at
1932 * the bottom. If $more is null, do not add a "More..." link. If $more
1933 * is a Title, make a link to that title and use it. If $more is a string,
1934 * directly paste it in as the link (escaping needs to be done manually).
1935 * Finally, if $more is a Message, call toString().
1937 * @param array $templates Array of templates from Article::getUsedTemplate or similar
1938 * @param bool $preview Whether this is for a preview
1939 * @param bool $section Whether this is for a section edit
1940 * @param Title|Message|string|null $more An escaped link for "More..." of the templates
1941 * @return String: HTML output
1943 public static function formatTemplates( $templates, $preview = false, $section = false, $more = null ) {
1944 wfProfileIn( __METHOD__ );
1946 $outText = '';
1947 if ( count( $templates ) > 0 ) {
1948 # Do a batch existence check
1949 $batch = new LinkBatch;
1950 foreach ( $templates as $title ) {
1951 $batch->addObj( $title );
1953 $batch->execute();
1955 # Construct the HTML
1956 $outText = '<div class="mw-templatesUsedExplanation">';
1957 if ( $preview ) {
1958 $outText .= wfMessage( 'templatesusedpreview' )->numParams( count( $templates ) )
1959 ->parseAsBlock();
1960 } elseif ( $section ) {
1961 $outText .= wfMessage( 'templatesusedsection' )->numParams( count( $templates ) )
1962 ->parseAsBlock();
1963 } else {
1964 $outText .= wfMessage( 'templatesused' )->numParams( count( $templates ) )
1965 ->parseAsBlock();
1967 $outText .= "</div><ul>\n";
1969 usort( $templates, 'Title::compare' );
1970 foreach ( $templates as $titleObj ) {
1971 $r = $titleObj->getRestrictions( 'edit' );
1972 if ( in_array( 'sysop', $r ) ) {
1973 $protected = wfMessage( 'template-protected' )->parse();
1974 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1975 $protected = wfMessage( 'template-semiprotected' )->parse();
1976 } else {
1977 $protected = '';
1979 if ( $titleObj->quickUserCan( 'edit' ) ) {
1980 $editLink = self::link(
1981 $titleObj,
1982 wfMessage( 'editlink' )->text(),
1983 array(),
1984 array( 'action' => 'edit' )
1986 } else {
1987 $editLink = self::link(
1988 $titleObj,
1989 wfMessage( 'viewsourcelink' )->text(),
1990 array(),
1991 array( 'action' => 'edit' )
1994 $outText .= '<li>' . self::link( $titleObj )
1995 . wfMessage( 'word-separator' )->escaped()
1996 . wfMessage( 'parentheses' )->rawParams( $editLink )->escaped()
1997 . wfMessage( 'word-separator' )->escaped()
1998 . $protected . '</li>';
2001 if ( $more instanceof Title ) {
2002 $outText .= '<li>' . self::link( $more, wfMessage( 'moredotdotdot' ) ) . '</li>';
2003 } elseif ( $more ) {
2004 $outText .= "<li>$more</li>";
2007 $outText .= '</ul>';
2009 wfProfileOut( __METHOD__ );
2010 return $outText;
2014 * Returns HTML for the "hidden categories on this page" list.
2016 * @param array $hiddencats of hidden categories from Article::getHiddenCategories
2017 * or similar
2018 * @return String: HTML output
2020 public static function formatHiddenCategories( $hiddencats ) {
2021 wfProfileIn( __METHOD__ );
2023 $outText = '';
2024 if ( count( $hiddencats ) > 0 ) {
2025 # Construct the HTML
2026 $outText = '<div class="mw-hiddenCategoriesExplanation">';
2027 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
2028 $outText .= "</div><ul>\n";
2030 foreach ( $hiddencats as $titleObj ) {
2031 $outText .= '<li>' . self::link( $titleObj, null, array(), array(), 'known' ) . "</li>\n"; # If it's hidden, it must exist - no need to check with a LinkBatch
2033 $outText .= '</ul>';
2035 wfProfileOut( __METHOD__ );
2036 return $outText;
2040 * Format a size in bytes for output, using an appropriate
2041 * unit (B, KB, MB or GB) according to the magnitude in question
2043 * @param int $size Size to format
2044 * @return String
2046 public static function formatSize( $size ) {
2047 global $wgLang;
2048 return htmlspecialchars( $wgLang->formatSize( $size ) );
2052 * Given the id of an interface element, constructs the appropriate title
2053 * attribute from the system messages. (Note, this is usually the id but
2054 * isn't always, because sometimes the accesskey needs to go on a different
2055 * element than the id, for reverse-compatibility, etc.)
2057 * @param string $name id of the element, minus prefixes.
2058 * @param $options Mixed: null or the string 'withaccess' to add an access-
2059 * key hint
2060 * @return String: contents of the title attribute (which you must HTML-
2061 * escape), or false for no title attribute
2063 public static function titleAttrib( $name, $options = null ) {
2064 wfProfileIn( __METHOD__ );
2066 $message = wfMessage( "tooltip-$name" );
2068 if ( !$message->exists() ) {
2069 $tooltip = false;
2070 } else {
2071 $tooltip = $message->text();
2072 # Compatibility: formerly some tooltips had [alt-.] hardcoded
2073 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2074 # Message equal to '-' means suppress it.
2075 if ( $tooltip == '-' ) {
2076 $tooltip = false;
2080 if ( $options == 'withaccess' ) {
2081 $accesskey = self::accesskey( $name );
2082 if ( $accesskey !== false ) {
2083 if ( $tooltip === false || $tooltip === '' ) {
2084 $tooltip = "[$accesskey]";
2085 } else {
2086 $tooltip .= " [$accesskey]";
2091 wfProfileOut( __METHOD__ );
2092 return $tooltip;
2095 static $accesskeycache;
2098 * Given the id of an interface element, constructs the appropriate
2099 * accesskey attribute from the system messages. (Note, this is usually
2100 * the id but isn't always, because sometimes the accesskey needs to go on
2101 * a different element than the id, for reverse-compatibility, etc.)
2103 * @param string $name id of the element, minus prefixes.
2104 * @return String: contents of the accesskey attribute (which you must HTML-
2105 * escape), or false for no accesskey attribute
2107 public static function accesskey( $name ) {
2108 if ( isset( self::$accesskeycache[$name] ) ) {
2109 return self::$accesskeycache[$name];
2111 wfProfileIn( __METHOD__ );
2113 $message = wfMessage( "accesskey-$name" );
2115 if ( !$message->exists() ) {
2116 $accesskey = false;
2117 } else {
2118 $accesskey = $message->plain();
2119 if ( $accesskey === '' || $accesskey === '-' ) {
2120 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2121 # attribute, but this is broken for accesskey: that might be a useful
2122 # value.
2123 $accesskey = false;
2127 wfProfileOut( __METHOD__ );
2128 return self::$accesskeycache[$name] = $accesskey;
2132 * Get a revision-deletion link, or disabled link, or nothing, depending
2133 * on user permissions & the settings on the revision.
2135 * Will use forward-compatible revision ID in the Special:RevDelete link
2136 * if possible, otherwise the timestamp-based ID which may break after
2137 * undeletion.
2139 * @param User $user
2140 * @param Revision $rev
2141 * @param Revision $title
2142 * @return string HTML fragment
2144 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
2145 $canHide = $user->isAllowed( 'deleterevision' );
2146 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2147 return '';
2150 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
2151 return Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2152 } else {
2153 if ( $rev->getId() ) {
2154 // RevDelete links using revision ID are stable across
2155 // page deletion and undeletion; use when possible.
2156 $query = array(
2157 'type' => 'revision',
2158 'target' => $title->getPrefixedDBkey(),
2159 'ids' => $rev->getId()
2161 } else {
2162 // Older deleted entries didn't save a revision ID.
2163 // We have to refer to these by timestamp, ick!
2164 $query = array(
2165 'type' => 'archive',
2166 'target' => $title->getPrefixedDBkey(),
2167 'ids' => $rev->getTimestamp()
2170 return Linker::revDeleteLink( $query,
2171 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2176 * Creates a (show/hide) link for deleting revisions/log entries
2178 * @param array $query query parameters to be passed to link()
2179 * @param $restricted Boolean: set to true to use a "<strong>" instead of a "<span>"
2180 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2182 * @return String: HTML "<a>" link to Special:Revisiondelete, wrapped in a
2183 * span to allow for customization of appearance with CSS
2185 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
2186 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2187 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2188 $html = wfMessage( $msgKey )->escaped();
2189 $tag = $restricted ? 'strong' : 'span';
2190 $link = self::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
2191 return Xml::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $link )->escaped() );
2195 * Creates a dead (show/hide) link for deleting revisions/log entries
2197 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2199 * @return string HTML text wrapped in a span to allow for customization
2200 * of appearance with CSS
2202 public static function revDeleteLinkDisabled( $delete = true ) {
2203 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2204 $html = wfMessage( $msgKey )->escaped();
2205 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2206 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), $htmlParentheses );
2209 /* Deprecated methods */
2212 * @deprecated since 1.16 Use link()
2214 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
2215 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
2217 * @param string $title The text of the title
2218 * @param string $text Link text
2219 * @param string $query Optional query part
2220 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
2221 * be included in the link text. Other characters will be appended after
2222 * the end of the link.
2223 * @return string
2225 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
2226 wfDeprecated( __METHOD__, '1.16' );
2228 $nt = Title::newFromText( $title );
2229 if ( $nt instanceof Title ) {
2230 return self::makeBrokenLinkObj( $nt, $text, $query, $trail );
2231 } else {
2232 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
2233 return $text == '' ? $title : $text;
2238 * @deprecated since 1.16 Use link(); warnings since 1.21
2240 * Make a link for a title which may or may not be in the database. If you need to
2241 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
2242 * call to this will result in a DB query.
2244 * @param $nt Title: the title object to make the link from, e.g. from
2245 * Title::newFromText.
2246 * @param $text String: link text
2247 * @param string $query optional query part
2248 * @param string $trail optional trail. Alphabetic characters at the start of this string will
2249 * be included in the link text. Other characters will be appended after
2250 * the end of the link.
2251 * @param string $prefix optional prefix. As trail, only before instead of after.
2252 * @return string
2254 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
2255 wfDeprecated( __METHOD__, '1.21' );
2257 wfProfileIn( __METHOD__ );
2258 $query = wfCgiToArray( $query );
2259 list( $inside, $trail ) = self::splitTrail( $trail );
2260 if ( $text === '' ) {
2261 $text = self::linkText( $nt );
2264 $ret = self::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
2266 wfProfileOut( __METHOD__ );
2267 return $ret;
2271 * @deprecated since 1.16 Use link(); warnings since 1.21
2273 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
2274 * it doesn't have to do a database query. It's also valid for interwiki titles and special
2275 * pages.
2277 * @param $title Title object of target page
2278 * @param $text String: text to replace the title
2279 * @param $query String: link target
2280 * @param $trail String: text after link
2281 * @param string $prefix text before link text
2282 * @param string $aprops extra attributes to the a-element
2283 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
2284 * @return string the a-element
2286 static function makeKnownLinkObj(
2287 $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = '', $style = ''
2289 wfDeprecated( __METHOD__, '1.21' );
2291 wfProfileIn( __METHOD__ );
2293 if ( $text == '' ) {
2294 $text = self::linkText( $title );
2296 $attribs = Sanitizer::mergeAttributes(
2297 Sanitizer::decodeTagAttributes( $aprops ),
2298 Sanitizer::decodeTagAttributes( $style )
2300 $query = wfCgiToArray( $query );
2301 list( $inside, $trail ) = self::splitTrail( $trail );
2303 $ret = self::link( $title, "$prefix$text$inside", $attribs, $query,
2304 array( 'known', 'noclasses' ) ) . $trail;
2306 wfProfileOut( __METHOD__ );
2307 return $ret;
2311 * @deprecated since 1.16 Use link()
2313 * Make a red link to the edit page of a given title.
2315 * @param $title Title object of the target page
2316 * @param $text String: Link text
2317 * @param string $query Optional query part
2318 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
2319 * be included in the link text. Other characters will be appended after
2320 * the end of the link.
2321 * @param string $prefix Optional prefix
2322 * @return string
2324 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
2325 wfDeprecated( __METHOD__, '1.16' );
2327 wfProfileIn( __METHOD__ );
2329 list( $inside, $trail ) = self::splitTrail( $trail );
2330 if ( $text === '' ) {
2331 $text = self::linkText( $title );
2334 $ret = self::link( $title, "$prefix$text$inside", array(),
2335 wfCgiToArray( $query ), 'broken' ) . $trail;
2337 wfProfileOut( __METHOD__ );
2338 return $ret;
2342 * @deprecated since 1.16 Use link()
2344 * Make a coloured link.
2346 * @param $nt Title object of the target page
2347 * @param $colour Integer: colour of the link
2348 * @param $text String: link text
2349 * @param $query String: optional query part
2350 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2351 * be included in the link text. Other characters will be appended after
2352 * the end of the link.
2353 * @param string $prefix Optional prefix
2354 * @return string
2356 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2357 wfDeprecated( __METHOD__, '1.16' );
2359 if ( $colour != '' ) {
2360 $style = self::getInternalLinkAttributesObj( $nt, $text, $colour );
2361 } else {
2362 $style = '';
2364 return self::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2368 * Returns the attributes for the tooltip and access key.
2369 * @return array
2371 public static function tooltipAndAccesskeyAttribs( $name ) {
2372 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2373 # no attribute" instead of "output '' as value for attribute", this
2374 # would be three lines.
2375 $attribs = array(
2376 'title' => self::titleAttrib( $name, 'withaccess' ),
2377 'accesskey' => self::accesskey( $name )
2379 if ( $attribs['title'] === false ) {
2380 unset( $attribs['title'] );
2382 if ( $attribs['accesskey'] === false ) {
2383 unset( $attribs['accesskey'] );
2385 return $attribs;
2389 * Returns raw bits of HTML, use titleAttrib()
2390 * @return null|string
2392 public static function tooltip( $name, $options = null ) {
2393 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2394 # no attribute" instead of "output '' as value for attribute", this
2395 # would be two lines.
2396 $tooltip = self::titleAttrib( $name, $options );
2397 if ( $tooltip === false ) {
2398 return '';
2400 return Xml::expandAttributes( array(
2401 'title' => $tooltip
2402 ) );
2407 * @since 1.18
2409 class DummyLinker {
2412 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2413 * into static calls to the new Linker for backwards compatibility.
2415 * @param string $fname Name of called method
2416 * @param array $args Arguments to the method
2417 * @return mixed
2419 public function __call( $fname, $args ) {
2420 return call_user_func_array( array( 'Linker', $fname ), $args );