Fixed spacing in actions/cache/filebackend/filerepo/job folder
[mediawiki.git] / includes / Linker.php
blob3e8a3c9f8c1922f4f401ff859af2408de1b32717
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'], $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['manualthumb'] ) || 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;
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']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
853 if ( !$exists ) {
854 $s .= self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
855 $zoomIcon = '';
856 } elseif ( !$thumb ) {
857 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
858 $zoomIcon = '';
859 } else {
860 if ( !$noscale && !$manualthumb ) {
861 self::processResponsiveImages( $file, $thumb, $hp );
863 $params = array(
864 'alt' => $fp['alt'],
865 'title' => $fp['title'],
866 'img-class' => ( isset( $fp['class'] ) && $fp['class'] !== '' ) ? $fp['class'] . ' thumbimage' : 'thumbimage'
868 $params = self::getImageLinkMTOParams( $fp, $query ) + $params;
869 $s .= $thumb->toHtml( $params );
870 if ( isset( $fp['framed'] ) ) {
871 $zoomIcon = "";
872 } else {
873 $zoomIcon = Html::rawElement( 'div', array( 'class' => 'magnify' ),
874 Html::rawElement( 'a', array(
875 'href' => $url,
876 'class' => 'internal',
877 'title' => wfMessage( 'thumbnail-more' )->text() ),
878 Html::element( 'img', array(
879 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ? '-rtl' : '' ) . '.png',
880 'width' => 15,
881 'height' => 11,
882 'alt' => "" ) ) ) );
885 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
886 return str_replace( "\n", ' ', $s );
890 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
891 * applicable.
893 * @param File $file
894 * @param MediaOutput $thumb
895 * @param array $hp image parameters
897 protected static function processResponsiveImages( $file, $thumb, $hp ) {
898 global $wgResponsiveImages;
899 if ( $wgResponsiveImages ) {
900 $hp15 = $hp;
901 $hp15['width'] = round( $hp['width'] * 1.5 );
902 $hp20 = $hp;
903 $hp20['width'] = $hp['width'] * 2;
904 if ( isset( $hp['height'] ) ) {
905 $hp15['height'] = round( $hp['height'] * 1.5 );
906 $hp20['height'] = $hp['height'] * 2;
909 $thumb15 = $file->transform( $hp15 );
910 $thumb20 = $file->transform( $hp20 );
911 if ( $thumb15->url !== $thumb->url ) {
912 $thumb->responsiveUrls['1.5'] = $thumb15->url;
914 if ( $thumb20->url !== $thumb->url ) {
915 $thumb->responsiveUrls['2'] = $thumb20->url;
921 * Make a "broken" link to an image
923 * @param $title Title object
924 * @param string $label link label (plain text)
925 * @param string $query query string
926 * @param $unused1 Unused parameter kept for b/c
927 * @param $unused2 Unused parameter kept for b/c
928 * @param $time Boolean: a file of a certain timestamp was requested
929 * @return String
931 public static function makeBrokenImageLinkObj( $title, $label = '', $query = '', $unused1 = '', $unused2 = '', $time = false ) {
932 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
933 if ( ! $title instanceof Title ) {
934 return "<!-- ERROR -->" . htmlspecialchars( $label );
936 wfProfileIn( __METHOD__ );
937 if ( $label == '' ) {
938 $label = $title->getPrefixedText();
940 $encLabel = htmlspecialchars( $label );
941 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
943 if ( ( $wgUploadMissingFileUrl || $wgUploadNavigationUrl || $wgEnableUploads ) && !$currentExists ) {
944 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
946 if ( $redir ) {
947 wfProfileOut( __METHOD__ );
948 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
951 $href = self::getUploadUrl( $title, $query );
953 wfProfileOut( __METHOD__ );
954 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
955 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES ) . '">' .
956 $encLabel . '</a>';
959 wfProfileOut( __METHOD__ );
960 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
964 * Get the URL to upload a certain file
966 * @param $destFile Title object of the file to upload
967 * @param string $query urlencoded query string to prepend
968 * @return String: urlencoded URL
970 protected static function getUploadUrl( $destFile, $query = '' ) {
971 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
972 $q = 'wpDestFile=' . $destFile->getPartialURL();
973 if ( $query != '' )
974 $q .= '&' . $query;
976 if ( $wgUploadMissingFileUrl ) {
977 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
978 } elseif( $wgUploadNavigationUrl ) {
979 return wfAppendQuery( $wgUploadNavigationUrl, $q );
980 } else {
981 $upload = SpecialPage::getTitleFor( 'Upload' );
982 return $upload->getLocalURL( $q );
987 * Create a direct link to a given uploaded file.
989 * @param $title Title object.
990 * @param string $html pre-sanitized HTML
991 * @param string $time MW timestamp of file creation time
992 * @return String: HTML
994 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
995 $img = wfFindFile( $title, array( 'time' => $time ) );
996 return self::makeMediaLinkFile( $title, $img, $html );
1000 * Create a direct link to a given uploaded file.
1001 * This will make a broken link if $file is false.
1003 * @param $title Title object.
1004 * @param $file File|bool mixed File object or false
1005 * @param string $html pre-sanitized HTML
1006 * @return String: HTML
1008 * @todo Handle invalid or missing images better.
1010 public static function makeMediaLinkFile( Title $title, $file, $html = '' ) {
1011 if ( $file && $file->exists() ) {
1012 $url = $file->getURL();
1013 $class = 'internal';
1014 } else {
1015 $url = self::getUploadUrl( $title );
1016 $class = 'new';
1018 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES );
1019 if ( $html == '' ) {
1020 $html = $alt;
1022 $u = htmlspecialchars( $url );
1023 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$html}</a>";
1027 * Make a link to a special page given its name and, optionally,
1028 * a message key from the link text.
1029 * Usage example: Linker::specialLink( 'Recentchanges' )
1031 * @return string
1033 public static function specialLink( $name, $key = '' ) {
1034 if ( $key == '' ) {
1035 $key = strtolower( $name );
1038 return self::linkKnown( SpecialPage::getTitleFor( $name ), wfMessage( $key )->text() );
1042 * Make an external link
1043 * @param string $url URL to link to
1044 * @param string $text text of link
1045 * @param $escape Boolean: do we escape the link text?
1046 * @param string $linktype type of external link. Gets added to the classes
1047 * @param array $attribs of extra attributes to <a>
1048 * @param $title Title|null Title object used for title specific link attributes
1049 * @return string
1051 public static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array(), $title = null ) {
1052 global $wgTitle;
1053 $class = "external";
1054 if ( $linktype ) {
1055 $class .= " $linktype";
1057 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1058 $class .= " {$attribs['class']}";
1060 $attribs['class'] = $class;
1062 if ( $escape ) {
1063 $text = htmlspecialchars( $text );
1066 if ( !$title ) {
1067 $title = $wgTitle;
1069 $attribs['rel'] = Parser::getExternalLinkRel( $url, $title );
1070 $link = '';
1071 $success = wfRunHooks( 'LinkerMakeExternalLink',
1072 array( &$url, &$text, &$link, &$attribs, $linktype ) );
1073 if ( !$success ) {
1074 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
1075 return $link;
1077 $attribs['href'] = $url;
1078 return Html::rawElement( 'a', $attribs, $text );
1082 * Make user link (or user contributions for unregistered users)
1083 * @param $userId Integer: user id in database.
1084 * @param string $userName user name in database.
1085 * @param string $altUserName text to display instead of the user name (optional)
1086 * @return String: HTML fragment
1087 * @since 1.19 Method exists for a long time. $altUserName was added in 1.19.
1089 public static function userLink( $userId, $userName, $altUserName = false ) {
1090 if ( $userId == 0 ) {
1091 $page = SpecialPage::getTitleFor( 'Contributions', $userName );
1092 if ( $altUserName === false ) {
1093 $altUserName = IP::prettifyIP( $userName );
1095 } else {
1096 $page = Title::makeTitle( NS_USER, $userName );
1099 return self::link(
1100 $page,
1101 htmlspecialchars( $altUserName !== false ? $altUserName : $userName ),
1102 array( 'class' => 'mw-userlink' )
1107 * Generate standard user tool links (talk, contributions, block link, etc.)
1109 * @param $userId Integer: user identifier
1110 * @param string $userText user name or IP address
1111 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
1112 * red if the user has no edits?
1113 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK and Linker::TOOL_LINKS_EMAIL)
1114 * @param $edits Integer: user edit count (optional, for performance)
1115 * @return String: HTML fragment
1117 public static function userToolLinks(
1118 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1120 global $wgUser, $wgDisableAnonTalk, $wgLang;
1121 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1122 $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1123 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1125 $items = array();
1126 if ( $talkable ) {
1127 $items[] = self::userTalkLink( $userId, $userText );
1129 if ( $userId ) {
1130 // check if the user has an edit
1131 $attribs = array();
1132 if ( $redContribsWhenNoEdits ) {
1133 if ( intval( $edits ) === 0 && $edits !== 0 ) {
1134 $user = User::newFromId( $userId );
1135 $edits = $user->getEditCount();
1137 if ( $edits === 0 ) {
1138 $attribs['class'] = 'new';
1141 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1143 $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1145 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1146 $items[] = self::blockLink( $userId, $userText );
1149 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1150 $items[] = self::emailLink( $userId, $userText );
1153 wfRunHooks( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1155 if ( $items ) {
1156 return wfMessage( 'word-separator' )->plain()
1157 . '<span class="mw-usertoollinks">'
1158 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1159 . '</span>';
1160 } else {
1161 return '';
1166 * Alias for userToolLinks( $userId, $userText, true );
1167 * @param $userId Integer: user identifier
1168 * @param string $userText user name or IP address
1169 * @param $edits Integer: user edit count (optional, for performance)
1170 * @return String
1172 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1173 return self::userToolLinks( $userId, $userText, true, 0, $edits );
1177 * @param $userId Integer: user id in database.
1178 * @param string $userText user name in database.
1179 * @return String: HTML fragment with user talk link
1181 public static function userTalkLink( $userId, $userText ) {
1182 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1183 $userTalkLink = self::link( $userTalkPage, wfMessage( 'talkpagelinktext' )->escaped() );
1184 return $userTalkLink;
1188 * @param $userId Integer: userid
1189 * @param string $userText user name in database.
1190 * @return String: HTML fragment with block link
1192 public static function blockLink( $userId, $userText ) {
1193 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1194 $blockLink = self::link( $blockPage, wfMessage( 'blocklink' )->escaped() );
1195 return $blockLink;
1199 * @param $userId Integer: userid
1200 * @param string $userText user name in database.
1201 * @return String: HTML fragment with e-mail user link
1203 public static function emailLink( $userId, $userText ) {
1204 $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1205 $emailLink = self::link( $emailPage, wfMessage( 'emaillink' )->escaped() );
1206 return $emailLink;
1210 * Generate a user link if the current user is allowed to view it
1211 * @param $rev Revision object.
1212 * @param $isPublic Boolean: show only if all users can see it
1213 * @return String: HTML fragment
1215 public static function revUserLink( $rev, $isPublic = false ) {
1216 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1217 $link = wfMessage( 'rev-deleted-user' )->escaped();
1218 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1219 $link = self::userLink( $rev->getUser( Revision::FOR_THIS_USER ),
1220 $rev->getUserText( Revision::FOR_THIS_USER ) );
1221 } else {
1222 $link = wfMessage( 'rev-deleted-user' )->escaped();
1224 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1225 return '<span class="history-deleted">' . $link . '</span>';
1227 return $link;
1231 * Generate a user tool link cluster if the current user is allowed to view it
1232 * @param $rev Revision object.
1233 * @param $isPublic Boolean: show only if all users can see it
1234 * @return string HTML
1236 public static function revUserTools( $rev, $isPublic = false ) {
1237 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1238 $link = wfMessage( 'rev-deleted-user' )->escaped();
1239 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1240 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1241 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1242 $link = self::userLink( $userId, $userText )
1243 . wfMessage( 'word-separator' )->plain()
1244 . self::userToolLinks( $userId, $userText );
1245 } else {
1246 $link = wfMessage( 'rev-deleted-user' )->escaped();
1248 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1249 return ' <span class="history-deleted">' . $link . '</span>';
1251 return $link;
1255 * This function is called by all recent changes variants, by the page history,
1256 * and by the user contributions list. It is responsible for formatting edit
1257 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1258 * auto-generated comments (from section editing) and formats [[wikilinks]].
1260 * @author Erik Moeller <moeller@scireview.de>
1262 * Note: there's not always a title to pass to this function.
1263 * Since you can't set a default parameter for a reference, I've turned it
1264 * temporarily to a value pass. Should be adjusted further. --brion
1266 * @param $comment String
1267 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1268 * @param $local Boolean: whether section links should refer to local page
1269 * @return mixed|String
1271 public static function formatComment( $comment, $title = null, $local = false ) {
1272 wfProfileIn( __METHOD__ );
1274 # Sanitize text a bit:
1275 $comment = str_replace( "\n", " ", $comment );
1276 # Allow HTML entities (for bug 13815)
1277 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1279 # Render autocomments and make links:
1280 $comment = self::formatAutocomments( $comment, $title, $local );
1281 $comment = self::formatLinksInComment( $comment, $title, $local );
1283 wfProfileOut( __METHOD__ );
1284 return $comment;
1288 * @var Title
1290 static $autocommentTitle;
1291 static $autocommentLocal;
1294 * Converts autogenerated comments in edit summaries into section links.
1295 * The pattern for autogen comments is / * foo * /, which makes for
1296 * some nasty regex.
1297 * We look for all comments, match any text before and after the comment,
1298 * add a separator where needed and format the comment itself with CSS
1299 * Called by Linker::formatComment.
1301 * @param string $comment comment text
1302 * @param $title Title|null An optional title object used to links to sections
1303 * @param $local Boolean: whether section links should refer to local page
1304 * @return String: formatted comment
1306 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1307 // Bah!
1308 self::$autocommentTitle = $title;
1309 self::$autocommentLocal = $local;
1310 $comment = preg_replace_callback(
1311 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1312 array( 'Linker', 'formatAutocommentsCallback' ),
1313 $comment );
1314 self::$autocommentTitle = null;
1315 self::$autocommentLocal = null;
1316 return $comment;
1320 * Helper function for Linker::formatAutocomments
1321 * @param $match
1322 * @return string
1324 private static function formatAutocommentsCallback( $match ) {
1325 global $wgLang;
1326 $title = self::$autocommentTitle;
1327 $local = self::$autocommentLocal;
1329 $pre = $match[1];
1330 $auto = $match[2];
1331 $post = $match[3];
1332 $comment = null;
1333 wfRunHooks( 'FormatAutocomments', array( &$comment, $pre, $auto, $post, $title, $local ) );
1334 if ( $comment === null ) {
1335 $link = '';
1336 if ( $title ) {
1337 $section = $auto;
1339 # Remove links that a user may have manually put in the autosummary
1340 # This could be improved by copying as much of Parser::stripSectionName as desired.
1341 $section = str_replace( '[[:', '', $section );
1342 $section = str_replace( '[[', '', $section );
1343 $section = str_replace( ']]', '', $section );
1345 $section = Sanitizer::normalizeSectionNameWhitespace( $section ); # bug 22784
1346 if ( $local ) {
1347 $sectionTitle = Title::newFromText( '#' . $section );
1348 } else {
1349 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1350 $title->getDBkey(), $section );
1352 if ( $sectionTitle ) {
1353 $link = self::link( $sectionTitle,
1354 $wgLang->getArrow(), array(), array(),
1355 'noclasses' );
1356 } else {
1357 $link = '';
1360 if ( $pre ) {
1361 # written summary $presep autocomment (summary /* section */)
1362 $pre .= wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1364 if ( $post ) {
1365 # autocomment $postsep written summary (/* section */ summary)
1366 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1368 $auto = '<span class="autocomment">' . $auto . '</span>';
1369 $comment = $pre . $link . $wgLang->getDirMark() . '<span dir="auto">' . $auto . $post . '</span>';
1371 return $comment;
1375 * @var Title
1377 static $commentContextTitle;
1378 static $commentLocal;
1381 * Formats wiki links and media links in text; all other wiki formatting
1382 * is ignored
1384 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1385 * @param string $comment text to format links in
1386 * @param $title Title|null An optional title object used to links to sections
1387 * @param $local Boolean: whether section links should refer to local page
1388 * @return String
1390 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1391 self::$commentContextTitle = $title;
1392 self::$commentLocal = $local;
1393 $html = preg_replace_callback(
1395 \[\[
1396 :? # ignore optional leading colon
1397 ([^\]|]+) # 1. link target; page names cannot include ] or |
1398 (?:\|
1399 # 2. a pipe-separated substring; only the last is captured
1400 # Stop matching at | and ]] without relying on backtracking.
1401 ((?:]?[^\]|])*+)
1403 \]\]
1404 ([^[]*) # 3. link trail (the text up until the next link)
1405 /x',
1406 array( 'Linker', 'formatLinksInCommentCallback' ),
1407 $comment );
1408 self::$commentContextTitle = null;
1409 self::$commentLocal = null;
1410 return $html;
1414 * @param $match
1415 * @return mixed
1417 protected static function formatLinksInCommentCallback( $match ) {
1418 global $wgContLang;
1420 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1421 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1423 $comment = $match[0];
1425 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1426 if ( strpos( $match[1], '%' ) !== false ) {
1427 $match[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $match[1] ) );
1430 # Handle link renaming [[foo|text]] will show link as "text"
1431 if ( $match[2] != "" ) {
1432 $text = $match[2];
1433 } else {
1434 $text = $match[1];
1436 $submatch = array();
1437 $thelink = null;
1438 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1439 # Media link; trail not supported.
1440 $linkRegexp = '/\[\[(.*?)\]\]/';
1441 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1442 if ( $title ) {
1443 $thelink = self::makeMediaLinkObj( $title, $text );
1445 } else {
1446 # Other kind of link
1447 if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1448 $trail = $submatch[1];
1449 } else {
1450 $trail = "";
1452 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1453 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1454 $match[1] = substr( $match[1], 1 );
1455 list( $inside, $trail ) = self::splitTrail( $trail );
1457 $linkText = $text;
1458 $linkTarget = self::normalizeSubpageLink( self::$commentContextTitle,
1459 $match[1], $linkText );
1461 $target = Title::newFromText( $linkTarget );
1462 if ( $target ) {
1463 if ( $target->getText() == '' && $target->getInterwiki() === ''
1464 && !self::$commentLocal && self::$commentContextTitle )
1466 $newTarget = clone ( self::$commentContextTitle );
1467 $newTarget->setFragment( '#' . $target->getFragment() );
1468 $target = $newTarget;
1470 $thelink = self::link(
1471 $target,
1472 $linkText . $inside
1473 ) . $trail;
1476 if ( $thelink ) {
1477 // If the link is still valid, go ahead and replace it in!
1478 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1481 return $comment;
1485 * @param $contextTitle Title
1486 * @param $target
1487 * @param $text
1488 * @return string
1490 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1491 # Valid link forms:
1492 # Foobar -- normal
1493 # :Foobar -- override special treatment of prefix (images, language links)
1494 # /Foobar -- convert to CurrentPage/Foobar
1495 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1496 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1497 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1499 wfProfileIn( __METHOD__ );
1500 $ret = $target; # default return value is no change
1502 # Some namespaces don't allow subpages,
1503 # so only perform processing if subpages are allowed
1504 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1505 $hash = strpos( $target, '#' );
1506 if ( $hash !== false ) {
1507 $suffix = substr( $target, $hash );
1508 $target = substr( $target, 0, $hash );
1509 } else {
1510 $suffix = '';
1512 # bug 7425
1513 $target = trim( $target );
1514 # Look at the first character
1515 if ( $target != '' && $target[0] === '/' ) {
1516 # / at end means we don't want the slash to be shown
1517 $m = array();
1518 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1519 if ( $trailingSlashes ) {
1520 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1521 } else {
1522 $noslash = substr( $target, 1 );
1525 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1526 if ( $text === '' ) {
1527 $text = $target . $suffix;
1528 } # this might be changed for ugliness reasons
1529 } else {
1530 # check for .. subpage backlinks
1531 $dotdotcount = 0;
1532 $nodotdot = $target;
1533 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1534 ++$dotdotcount;
1535 $nodotdot = substr( $nodotdot, 3 );
1537 if ( $dotdotcount > 0 ) {
1538 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1539 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1540 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1541 # / at the end means don't show full path
1542 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1543 $nodotdot = substr( $nodotdot, 0, -1 );
1544 if ( $text === '' ) {
1545 $text = $nodotdot . $suffix;
1548 $nodotdot = trim( $nodotdot );
1549 if ( $nodotdot != '' ) {
1550 $ret .= '/' . $nodotdot;
1552 $ret .= $suffix;
1558 wfProfileOut( __METHOD__ );
1559 return $ret;
1563 * Wrap a comment in standard punctuation and formatting if
1564 * it's non-empty, otherwise return empty string.
1566 * @param $comment String
1567 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1568 * @param $local Boolean: whether section links should refer to local page
1570 * @return string
1572 public static function commentBlock( $comment, $title = null, $local = false ) {
1573 // '*' used to be the comment inserted by the software way back
1574 // in antiquity in case none was provided, here for backwards
1575 // compatibility, acc. to brion -ævar
1576 if ( $comment == '' || $comment == '*' ) {
1577 return '';
1578 } else {
1579 $formatted = self::formatComment( $comment, $title, $local );
1580 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1581 return " <span class=\"comment\">$formatted</span>";
1586 * Wrap and format the given revision's comment block, if the current
1587 * user is allowed to view it.
1589 * @param $rev Revision object
1590 * @param $local Boolean: whether section links should refer to local page
1591 * @param $isPublic Boolean: show only if all users can see it
1592 * @return String: HTML fragment
1594 public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1595 if ( $rev->getRawComment() == "" ) {
1596 return "";
1598 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1599 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1600 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1601 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1602 $rev->getTitle(), $local );
1603 } else {
1604 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1606 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1607 return " <span class=\"history-deleted\">$block</span>";
1609 return $block;
1613 * @param $size
1614 * @return string
1616 public static function formatRevisionSize( $size ) {
1617 if ( $size == 0 ) {
1618 $stxt = wfMessage( 'historyempty' )->escaped();
1619 } else {
1620 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1621 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1623 return "<span class=\"history-size\">$stxt</span>";
1627 * Add another level to the Table of Contents
1629 * @return string
1631 public static function tocIndent() {
1632 return "\n<ul>";
1636 * Finish one or more sublevels on the Table of Contents
1638 * @return string
1640 public static function tocUnindent( $level ) {
1641 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1645 * parameter level defines if we are on an indentation level
1647 * @return string
1649 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1650 $classes = "toclevel-$level";
1651 if ( $sectionIndex !== false ) {
1652 $classes .= " tocsection-$sectionIndex";
1654 return "\n<li class=\"$classes\"><a href=\"#" .
1655 $anchor . '"><span class="tocnumber">' .
1656 $tocnumber . '</span> <span class="toctext">' .
1657 $tocline . '</span></a>';
1661 * End a Table Of Contents line.
1662 * tocUnindent() will be used instead if we're ending a line below
1663 * the new level.
1664 * @return string
1666 public static function tocLineEnd() {
1667 return "</li>\n";
1671 * Wraps the TOC in a table and provides the hide/collapse javascript.
1673 * @param string $toc html of the Table Of Contents
1674 * @param $lang String|Language|false: Language for the toc title, defaults to user language
1675 * @return String: full html of the TOC
1677 public static function tocList( $toc, $lang = false ) {
1678 $lang = wfGetLangObj( $lang );
1679 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1681 return '<table id="toc" class="toc"><tr><td>'
1682 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1683 . $toc
1684 . "</ul>\n</td></tr></table>\n";
1688 * Generate a table of contents from a section tree
1689 * Currently unused.
1691 * @param array $tree Return value of ParserOutput::getSections()
1692 * @return String: HTML fragment
1694 public static function generateTOC( $tree ) {
1695 $toc = '';
1696 $lastLevel = 0;
1697 foreach ( $tree as $section ) {
1698 if ( $section['toclevel'] > $lastLevel )
1699 $toc .= self::tocIndent();
1700 elseif ( $section['toclevel'] < $lastLevel )
1701 $toc .= self::tocUnindent(
1702 $lastLevel - $section['toclevel'] );
1703 else
1704 $toc .= self::tocLineEnd();
1706 $toc .= self::tocLine( $section['anchor'],
1707 $section['line'], $section['number'],
1708 $section['toclevel'], $section['index'] );
1709 $lastLevel = $section['toclevel'];
1711 $toc .= self::tocLineEnd();
1712 return self::tocList( $toc );
1716 * Create a headline for content
1718 * @param $level Integer: the level of the headline (1-6)
1719 * @param string $attribs any attributes for the headline, starting with
1720 * a space and ending with '>'
1721 * This *must* be at least '>' for no attribs
1722 * @param string $anchor the anchor to give the headline (the bit after the #)
1723 * @param string $html html for the text of the header
1724 * @param string $link HTML to add for the section edit link
1725 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1726 * backward compatibility (false to omit)
1728 * @return String: HTML headline
1730 public static function makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor = false ) {
1731 $ret = "<h$level$attribs"
1732 . $link
1733 . " <span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1734 . "</h$level>";
1735 if ( $legacyAnchor !== false ) {
1736 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1738 return $ret;
1742 * Split a link trail, return the "inside" portion and the remainder of the trail
1743 * as a two-element array
1744 * @return array
1746 static function splitTrail( $trail ) {
1747 global $wgContLang;
1748 $regex = $wgContLang->linkTrail();
1749 $inside = '';
1750 if ( $trail !== '' ) {
1751 $m = array();
1752 if ( preg_match( $regex, $trail, $m ) ) {
1753 $inside = $m[1];
1754 $trail = $m[2];
1757 return array( $inside, $trail );
1761 * Generate a rollback link for a given revision. Currently it's the
1762 * caller's responsibility to ensure that the revision is the top one. If
1763 * it's not, of course, the user will get an error message.
1765 * If the calling page is called with the parameter &bot=1, all rollback
1766 * links also get that parameter. It causes the edit itself and the rollback
1767 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1768 * changes, so this allows sysops to combat a busy vandal without bothering
1769 * other users.
1771 * If the option verify is set this function will return the link only in case the
1772 * revision can be reverted. Please note that due to performance limitations
1773 * it might be assumed that a user isn't the only contributor of a page while
1774 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1775 * work if $wgShowRollbackEditCount is disabled, so this can only function
1776 * as an additional check.
1778 * If the option noBrackets is set the rollback link wont be enclosed in []
1780 * @param $rev Revision object
1781 * @param $context IContextSource context to use or null for the main context.
1782 * @param $options array
1783 * @return string
1785 public static function generateRollback( $rev, IContextSource $context = null, $options = array( 'verify' ) ) {
1786 if ( $context === null ) {
1787 $context = RequestContext::getMain();
1789 $editCount = false;
1790 if ( in_array( 'verify', $options ) ) {
1791 $editCount = self::getRollbackEditCount( $rev, true );
1792 if ( $editCount === false ) {
1793 return '';
1797 $inner = self::buildRollbackLink( $rev, $context, $editCount );
1799 if ( !in_array( 'noBrackets', $options ) ) {
1800 $inner = $context->msg( 'brackets' )->rawParams( $inner )->plain();
1803 return '<span class="mw-rollback-link">' . $inner . '</span>';
1807 * This function will return the number of revisions which a rollback
1808 * would revert and, if $verify is set it will verify that a revision
1809 * can be reverted (that the user isn't the only contributor and the
1810 * revision we might rollback to isn't deleted). These checks can only
1811 * function as an additional check as this function only checks against
1812 * the last $wgShowRollbackEditCount edits.
1814 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1815 * is set and the user is the only contributor of the page.
1817 * @param $rev Revision object
1818 * @param bool $verify Try to verify that this revision can really be rolled back
1819 * @return integer|bool|null
1821 public static function getRollbackEditCount( $rev, $verify ) {
1822 global $wgShowRollbackEditCount;
1823 if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
1824 // Nothing has happened, indicate this by returning 'null'
1825 return null;
1828 $dbr = wfGetDB( DB_SLAVE );
1830 // Up to the value of $wgShowRollbackEditCount revisions are counted
1831 $res = $dbr->select(
1832 'revision',
1833 array( 'rev_user_text', 'rev_deleted' ),
1834 // $rev->getPage() returns null sometimes
1835 array( 'rev_page' => $rev->getTitle()->getArticleID() ),
1836 __METHOD__,
1837 array(
1838 'USE INDEX' => array( 'revision' => 'page_timestamp' ),
1839 'ORDER BY' => 'rev_timestamp DESC',
1840 'LIMIT' => $wgShowRollbackEditCount + 1
1844 $editCount = 0;
1845 $moreRevs = false;
1846 foreach ( $res as $row ) {
1847 if ( $rev->getRawUserText() != $row->rev_user_text ) {
1848 if ( $verify && ( $row->rev_deleted & Revision::DELETED_TEXT || $row->rev_deleted & Revision::DELETED_USER ) ) {
1849 // If the user or the text of the revision we might rollback to is deleted in some way we can't rollback
1850 // Similar to the sanity checks in WikiPage::commitRollback
1851 return false;
1853 $moreRevs = true;
1854 break;
1856 $editCount++;
1859 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1860 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1861 // and there weren't any other revisions. That means that the current user is the only
1862 // editor, so we can't rollback
1863 return false;
1865 return $editCount;
1869 * Build a raw rollback link, useful for collections of "tool" links
1871 * @param $rev Revision object
1872 * @param $context IContextSource context to use or null for the main context.
1873 * @param $editCount integer Number of edits that would be reverted
1874 * @return String: HTML fragment
1876 public static function buildRollbackLink( $rev, IContextSource $context = null, $editCount = false ) {
1877 global $wgShowRollbackEditCount, $wgMiserMode;
1879 // To config which pages are effected by miser mode
1880 $disableRollbackEditCountSpecialPage = array( 'Recentchanges', 'Watchlist' );
1882 if ( $context === null ) {
1883 $context = RequestContext::getMain();
1886 $title = $rev->getTitle();
1887 $query = array(
1888 'action' => 'rollback',
1889 'from' => $rev->getUserText(),
1890 'token' => $context->getUser()->getEditToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1892 if ( $context->getRequest()->getBool( 'bot' ) ) {
1893 $query['bot'] = '1';
1894 $query['hidediff'] = '1'; // bug 15999
1897 $disableRollbackEditCount = false;
1898 if( $wgMiserMode ) {
1899 foreach( $disableRollbackEditCountSpecialPage as $specialPage ) {
1900 if( $context->getTitle()->isSpecial( $specialPage ) ) {
1901 $disableRollbackEditCount = true;
1902 break;
1907 if( !$disableRollbackEditCount && is_int( $wgShowRollbackEditCount ) && $wgShowRollbackEditCount > 0 ) {
1908 if ( !is_numeric( $editCount ) ) {
1909 $editCount = self::getRollbackEditCount( $rev, false );
1912 if( $editCount > $wgShowRollbackEditCount ) {
1913 $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )->numParams( $wgShowRollbackEditCount )->parse();
1914 } else {
1915 $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1918 return self::link(
1919 $title,
1920 $editCount_output,
1921 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1922 $query,
1923 array( 'known', 'noclasses' )
1925 } else {
1926 return self::link(
1927 $title,
1928 $context->msg( 'rollbacklink' )->escaped(),
1929 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1930 $query,
1931 array( 'known', 'noclasses' )
1937 * Returns HTML for the "templates used on this page" list.
1939 * Make an HTML list of templates, and then add a "More..." link at
1940 * the bottom. If $more is null, do not add a "More..." link. If $more
1941 * is a Title, make a link to that title and use it. If $more is a string,
1942 * directly paste it in as the link (escaping needs to be done manually).
1943 * Finally, if $more is a Message, call toString().
1945 * @param array $templates Array of templates from Article::getUsedTemplate or similar
1946 * @param bool $preview Whether this is for a preview
1947 * @param bool $section Whether this is for a section edit
1948 * @param Title|Message|string|null $more An escaped link for "More..." of the templates
1949 * @return String: HTML output
1951 public static function formatTemplates( $templates, $preview = false, $section = false, $more = null ) {
1952 wfProfileIn( __METHOD__ );
1954 $outText = '';
1955 if ( count( $templates ) > 0 ) {
1956 # Do a batch existence check
1957 $batch = new LinkBatch;
1958 foreach ( $templates as $title ) {
1959 $batch->addObj( $title );
1961 $batch->execute();
1963 # Construct the HTML
1964 $outText = '<div class="mw-templatesUsedExplanation">';
1965 if ( $preview ) {
1966 $outText .= wfMessage( 'templatesusedpreview' )->numParams( count( $templates ) )
1967 ->parseAsBlock();
1968 } elseif ( $section ) {
1969 $outText .= wfMessage( 'templatesusedsection' )->numParams( count( $templates ) )
1970 ->parseAsBlock();
1971 } else {
1972 $outText .= wfMessage( 'templatesused' )->numParams( count( $templates ) )
1973 ->parseAsBlock();
1975 $outText .= "</div><ul>\n";
1977 usort( $templates, 'Title::compare' );
1978 foreach ( $templates as $titleObj ) {
1979 $r = $titleObj->getRestrictions( 'edit' );
1980 if ( in_array( 'sysop', $r ) ) {
1981 $protected = wfMessage( 'template-protected' )->parse();
1982 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1983 $protected = wfMessage( 'template-semiprotected' )->parse();
1984 } else {
1985 $protected = '';
1987 if ( $titleObj->quickUserCan( 'edit' ) ) {
1988 $editLink = self::link(
1989 $titleObj,
1990 wfMessage( 'editlink' )->text(),
1991 array(),
1992 array( 'action' => 'edit' )
1994 } else {
1995 $editLink = self::link(
1996 $titleObj,
1997 wfMessage( 'viewsourcelink' )->text(),
1998 array(),
1999 array( 'action' => 'edit' )
2002 $outText .= '<li>' . self::link( $titleObj )
2003 . wfMessage( 'word-separator' )->escaped()
2004 . wfMessage( 'parentheses' )->rawParams( $editLink )->escaped()
2005 . wfMessage( 'word-separator' )->escaped()
2006 . $protected . '</li>';
2009 if ( $more instanceof Title ) {
2010 $outText .= '<li>' . self::link( $more, wfMessage( 'moredotdotdot' ) ) . '</li>';
2011 } elseif ( $more ) {
2012 $outText .= "<li>$more</li>";
2015 $outText .= '</ul>';
2017 wfProfileOut( __METHOD__ );
2018 return $outText;
2022 * Returns HTML for the "hidden categories on this page" list.
2024 * @param array $hiddencats of hidden categories from Article::getHiddenCategories
2025 * or similar
2026 * @return String: HTML output
2028 public static function formatHiddenCategories( $hiddencats ) {
2029 wfProfileIn( __METHOD__ );
2031 $outText = '';
2032 if ( count( $hiddencats ) > 0 ) {
2033 # Construct the HTML
2034 $outText = '<div class="mw-hiddenCategoriesExplanation">';
2035 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
2036 $outText .= "</div><ul>\n";
2038 foreach ( $hiddencats as $titleObj ) {
2039 $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
2041 $outText .= '</ul>';
2043 wfProfileOut( __METHOD__ );
2044 return $outText;
2048 * Format a size in bytes for output, using an appropriate
2049 * unit (B, KB, MB or GB) according to the magnitude in question
2051 * @param int $size Size to format
2052 * @return String
2054 public static function formatSize( $size ) {
2055 global $wgLang;
2056 return htmlspecialchars( $wgLang->formatSize( $size ) );
2060 * Given the id of an interface element, constructs the appropriate title
2061 * attribute from the system messages. (Note, this is usually the id but
2062 * isn't always, because sometimes the accesskey needs to go on a different
2063 * element than the id, for reverse-compatibility, etc.)
2065 * @param string $name id of the element, minus prefixes.
2066 * @param $options Mixed: null or the string 'withaccess' to add an access-
2067 * key hint
2068 * @return String: contents of the title attribute (which you must HTML-
2069 * escape), or false for no title attribute
2071 public static function titleAttrib( $name, $options = null ) {
2072 wfProfileIn( __METHOD__ );
2074 $message = wfMessage( "tooltip-$name" );
2076 if ( !$message->exists() ) {
2077 $tooltip = false;
2078 } else {
2079 $tooltip = $message->text();
2080 # Compatibility: formerly some tooltips had [alt-.] hardcoded
2081 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2082 # Message equal to '-' means suppress it.
2083 if ( $tooltip == '-' ) {
2084 $tooltip = false;
2088 if ( $options == 'withaccess' ) {
2089 $accesskey = self::accesskey( $name );
2090 if ( $accesskey !== false ) {
2091 if ( $tooltip === false || $tooltip === '' ) {
2092 $tooltip = "[$accesskey]";
2093 } else {
2094 $tooltip .= " [$accesskey]";
2099 wfProfileOut( __METHOD__ );
2100 return $tooltip;
2103 static $accesskeycache;
2106 * Given the id of an interface element, constructs the appropriate
2107 * accesskey attribute from the system messages. (Note, this is usually
2108 * the id but isn't always, because sometimes the accesskey needs to go on
2109 * a different element than the id, for reverse-compatibility, etc.)
2111 * @param string $name id of the element, minus prefixes.
2112 * @return String: contents of the accesskey attribute (which you must HTML-
2113 * escape), or false for no accesskey attribute
2115 public static function accesskey( $name ) {
2116 if ( isset( self::$accesskeycache[$name] ) ) {
2117 return self::$accesskeycache[$name];
2119 wfProfileIn( __METHOD__ );
2121 $message = wfMessage( "accesskey-$name" );
2123 if ( !$message->exists() ) {
2124 $accesskey = false;
2125 } else {
2126 $accesskey = $message->plain();
2127 if ( $accesskey === '' || $accesskey === '-' ) {
2128 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2129 # attribute, but this is broken for accesskey: that might be a useful
2130 # value.
2131 $accesskey = false;
2135 wfProfileOut( __METHOD__ );
2136 return self::$accesskeycache[$name] = $accesskey;
2140 * Get a revision-deletion link, or disabled link, or nothing, depending
2141 * on user permissions & the settings on the revision.
2143 * Will use forward-compatible revision ID in the Special:RevDelete link
2144 * if possible, otherwise the timestamp-based ID which may break after
2145 * undeletion.
2147 * @param User $user
2148 * @param Revision $rev
2149 * @param Revision $title
2150 * @return string HTML fragment
2152 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
2153 $canHide = $user->isAllowed( 'deleterevision' );
2154 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2155 return '';
2158 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
2159 return Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2160 } else {
2161 if ( $rev->getId() ) {
2162 // RevDelete links using revision ID are stable across
2163 // page deletion and undeletion; use when possible.
2164 $query = array(
2165 'type' => 'revision',
2166 'target' => $title->getPrefixedDBkey(),
2167 'ids' => $rev->getId()
2169 } else {
2170 // Older deleted entries didn't save a revision ID.
2171 // We have to refer to these by timestamp, ick!
2172 $query = array(
2173 'type' => 'archive',
2174 'target' => $title->getPrefixedDBkey(),
2175 'ids' => $rev->getTimestamp()
2178 return Linker::revDeleteLink( $query,
2179 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2184 * Creates a (show/hide) link for deleting revisions/log entries
2186 * @param array $query query parameters to be passed to link()
2187 * @param $restricted Boolean: set to true to use a "<strong>" instead of a "<span>"
2188 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2190 * @return String: HTML "<a>" link to Special:Revisiondelete, wrapped in a
2191 * span to allow for customization of appearance with CSS
2193 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
2194 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2195 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2196 $html = wfMessage( $msgKey )->escaped();
2197 $tag = $restricted ? 'strong' : 'span';
2198 $link = self::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
2199 return Xml::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $link )->escaped() );
2203 * Creates a dead (show/hide) link for deleting revisions/log entries
2205 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2207 * @return string HTML text wrapped in a span to allow for customization
2208 * of appearance with CSS
2210 public static function revDeleteLinkDisabled( $delete = true ) {
2211 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2212 $html = wfMessage( $msgKey )->escaped();
2213 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2214 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), $htmlParentheses );
2217 /* Deprecated methods */
2220 * @deprecated since 1.16 Use link()
2222 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
2223 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
2225 * @param string $title The text of the title
2226 * @param string $text Link text
2227 * @param string $query Optional query part
2228 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
2229 * be included in the link text. Other characters will be appended after
2230 * the end of the link.
2231 * @return string
2233 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
2234 wfDeprecated( __METHOD__, '1.16' );
2236 $nt = Title::newFromText( $title );
2237 if ( $nt instanceof Title ) {
2238 return self::makeBrokenLinkObj( $nt, $text, $query, $trail );
2239 } else {
2240 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
2241 return $text == '' ? $title : $text;
2246 * @deprecated since 1.16 Use link(); warnings since 1.21
2248 * Make a link for a title which may or may not be in the database. If you need to
2249 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
2250 * call to this will result in a DB query.
2252 * @param $nt Title: the title object to make the link from, e.g. from
2253 * Title::newFromText.
2254 * @param $text String: link text
2255 * @param string $query optional query part
2256 * @param string $trail optional trail. Alphabetic characters at the start of this string will
2257 * be included in the link text. Other characters will be appended after
2258 * the end of the link.
2259 * @param string $prefix optional prefix. As trail, only before instead of after.
2260 * @return string
2262 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
2263 wfDeprecated( __METHOD__, '1.21' );
2265 wfProfileIn( __METHOD__ );
2266 $query = wfCgiToArray( $query );
2267 list( $inside, $trail ) = self::splitTrail( $trail );
2268 if ( $text === '' ) {
2269 $text = self::linkText( $nt );
2272 $ret = self::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
2274 wfProfileOut( __METHOD__ );
2275 return $ret;
2279 * @deprecated since 1.16 Use link(); warnings since 1.21
2281 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
2282 * it doesn't have to do a database query. It's also valid for interwiki titles and special
2283 * pages.
2285 * @param $title Title object of target page
2286 * @param $text String: text to replace the title
2287 * @param $query String: link target
2288 * @param $trail String: text after link
2289 * @param string $prefix text before link text
2290 * @param string $aprops extra attributes to the a-element
2291 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
2292 * @return string the a-element
2294 static function makeKnownLinkObj(
2295 $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = '', $style = ''
2297 wfDeprecated( __METHOD__, '1.21' );
2299 wfProfileIn( __METHOD__ );
2301 if ( $text == '' ) {
2302 $text = self::linkText( $title );
2304 $attribs = Sanitizer::mergeAttributes(
2305 Sanitizer::decodeTagAttributes( $aprops ),
2306 Sanitizer::decodeTagAttributes( $style )
2308 $query = wfCgiToArray( $query );
2309 list( $inside, $trail ) = self::splitTrail( $trail );
2311 $ret = self::link( $title, "$prefix$text$inside", $attribs, $query,
2312 array( 'known', 'noclasses' ) ) . $trail;
2314 wfProfileOut( __METHOD__ );
2315 return $ret;
2319 * @deprecated since 1.16 Use link()
2321 * Make a red link to the edit page of a given title.
2323 * @param $title Title object of the target page
2324 * @param $text String: Link text
2325 * @param string $query Optional query part
2326 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
2327 * be included in the link text. Other characters will be appended after
2328 * the end of the link.
2329 * @param string $prefix Optional prefix
2330 * @return string
2332 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
2333 wfDeprecated( __METHOD__, '1.16' );
2335 wfProfileIn( __METHOD__ );
2337 list( $inside, $trail ) = self::splitTrail( $trail );
2338 if ( $text === '' ) {
2339 $text = self::linkText( $title );
2342 $ret = self::link( $title, "$prefix$text$inside", array(),
2343 wfCgiToArray( $query ), 'broken' ) . $trail;
2345 wfProfileOut( __METHOD__ );
2346 return $ret;
2350 * @deprecated since 1.16 Use link()
2352 * Make a coloured link.
2354 * @param $nt Title object of the target page
2355 * @param $colour Integer: colour of the link
2356 * @param $text String: link text
2357 * @param $query String: optional query part
2358 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2359 * be included in the link text. Other characters will be appended after
2360 * the end of the link.
2361 * @param string $prefix Optional prefix
2362 * @return string
2364 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2365 wfDeprecated( __METHOD__, '1.16' );
2367 if ( $colour != '' ) {
2368 $style = self::getInternalLinkAttributesObj( $nt, $text, $colour );
2369 } else {
2370 $style = '';
2372 return self::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2376 * Returns the attributes for the tooltip and access key.
2377 * @return array
2379 public static function tooltipAndAccesskeyAttribs( $name ) {
2380 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2381 # no attribute" instead of "output '' as value for attribute", this
2382 # would be three lines.
2383 $attribs = array(
2384 'title' => self::titleAttrib( $name, 'withaccess' ),
2385 'accesskey' => self::accesskey( $name )
2387 if ( $attribs['title'] === false ) {
2388 unset( $attribs['title'] );
2390 if ( $attribs['accesskey'] === false ) {
2391 unset( $attribs['accesskey'] );
2393 return $attribs;
2397 * Returns raw bits of HTML, use titleAttrib()
2398 * @return null|string
2400 public static function tooltip( $name, $options = null ) {
2401 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2402 # no attribute" instead of "output '' as value for attribute", this
2403 # would be two lines.
2404 $tooltip = self::titleAttrib( $name, $options );
2405 if ( $tooltip === false ) {
2406 return '';
2408 return Xml::expandAttributes( array(
2409 'title' => $tooltip
2410 ) );
2415 * @since 1.18
2417 class DummyLinker {
2420 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2421 * into static calls to the new Linker for backwards compatibility.
2423 * @param string $fname Name of called method
2424 * @param array $args Arguments to the method
2425 * @return mixed
2427 public function __call( $fname, $args ) {
2428 return call_user_func_array( array( 'Linker', $fname ), $args );