Customise linktrail for Gujarati (gu)
[mediawiki.git] / includes / Linker.php
blob5bb92308ff3af2284708d1b3d58c442adea10ffe
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'] ) ) {
790 $fp['align'] = 'right';
792 if ( !isset( $fp['alt'] ) ) {
793 $fp['alt'] = '';
795 if ( !isset( $fp['title'] ) ) {
796 $fp['title'] = '';
798 if ( !isset( $fp['caption'] ) ) {
799 $fp['caption'] = '';
802 if ( empty( $hp['width'] ) ) {
803 // Reduce width for upright images when parameter 'upright' is used
804 $hp['width'] = isset( $fp['upright'] ) ? 130 : 180;
806 $thumb = false;
807 $noscale = false;
808 $manualthumb = false;
810 if ( !$exists ) {
811 $outerWidth = $hp['width'] + 2;
812 } else {
813 if ( isset( $fp['manualthumb'] ) ) {
814 # Use manually specified thumbnail
815 $manual_title = Title::makeTitleSafe( NS_FILE, $fp['manualthumb'] );
816 if ( $manual_title ) {
817 $manual_img = wfFindFile( $manual_title );
818 if ( $manual_img ) {
819 $thumb = $manual_img->getUnscaledThumb( $hp );
820 $manualthumb = true;
821 } else {
822 $exists = false;
825 } elseif ( isset( $fp['framed'] ) ) {
826 // Use image dimensions, don't scale
827 $thumb = $file->getUnscaledThumb( $hp );
828 $noscale = true;
829 } else {
830 # Do not present an image bigger than the source, for bitmap-style images
831 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
832 $srcWidth = $file->getWidth( $page );
833 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
834 $hp['width'] = $srcWidth;
836 $thumb = $file->transform( $hp );
839 if ( $thumb ) {
840 $outerWidth = $thumb->getWidth() + 2;
841 } else {
842 $outerWidth = $hp['width'] + 2;
846 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
847 # So we don't need to pass it here in $query. However, the URL for the
848 # zoom icon still needs it, so we make a unique query for it. See bug 14771
849 $url = $title->getLocalURL( $query );
850 if ( $page ) {
851 $url = wfAppendQuery( $url, array( 'page' => $page ) );
853 if ( $manualthumb &&
854 !isset( $fp['link-title'] ) &&
855 !isset( $fp['link-url'] ) &&
856 !isset( $fp['no-link'] ) ) {
857 $fp['link-url'] = $url;
860 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
861 if ( !$exists ) {
862 $s .= self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
863 $zoomIcon = '';
864 } elseif ( !$thumb ) {
865 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
866 $zoomIcon = '';
867 } else {
868 if ( !$noscale && !$manualthumb ) {
869 self::processResponsiveImages( $file, $thumb, $hp );
871 $params = array(
872 'alt' => $fp['alt'],
873 'title' => $fp['title'],
874 'img-class' => ( isset( $fp['class'] ) && $fp['class'] !== '' ) ? $fp['class'] . ' thumbimage' : 'thumbimage'
876 $params = self::getImageLinkMTOParams( $fp, $query ) + $params;
877 $s .= $thumb->toHtml( $params );
878 if ( isset( $fp['framed'] ) ) {
879 $zoomIcon = "";
880 } else {
881 $zoomIcon = Html::rawElement( 'div', array( 'class' => 'magnify' ),
882 Html::rawElement( 'a', array(
883 'href' => $url,
884 'class' => 'internal',
885 'title' => wfMessage( 'thumbnail-more' )->text() ),
886 Html::element( 'img', array(
887 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ? '-rtl' : '' ) . '.png',
888 'width' => 15,
889 'height' => 11,
890 'alt' => "" ) ) ) );
893 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
894 return str_replace( "\n", ' ', $s );
898 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
899 * applicable.
901 * @param File $file
902 * @param MediaOutput $thumb
903 * @param array $hp image parameters
905 protected static function processResponsiveImages( $file, $thumb, $hp ) {
906 global $wgResponsiveImages;
907 if ( $wgResponsiveImages ) {
908 $hp15 = $hp;
909 $hp15['width'] = round( $hp['width'] * 1.5 );
910 $hp20 = $hp;
911 $hp20['width'] = $hp['width'] * 2;
912 if ( isset( $hp['height'] ) ) {
913 $hp15['height'] = round( $hp['height'] * 1.5 );
914 $hp20['height'] = $hp['height'] * 2;
917 $thumb15 = $file->transform( $hp15 );
918 $thumb20 = $file->transform( $hp20 );
919 if ( $thumb15->url !== $thumb->url ) {
920 $thumb->responsiveUrls['1.5'] = $thumb15->url;
922 if ( $thumb20->url !== $thumb->url ) {
923 $thumb->responsiveUrls['2'] = $thumb20->url;
929 * Make a "broken" link to an image
931 * @param $title Title object
932 * @param string $label link label (plain text)
933 * @param string $query query string
934 * @param $unused1 Unused parameter kept for b/c
935 * @param $unused2 Unused parameter kept for b/c
936 * @param $time Boolean: a file of a certain timestamp was requested
937 * @return String
939 public static function makeBrokenImageLinkObj( $title, $label = '', $query = '', $unused1 = '', $unused2 = '', $time = false ) {
940 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
941 if ( ! $title instanceof Title ) {
942 return "<!-- ERROR -->" . htmlspecialchars( $label );
944 wfProfileIn( __METHOD__ );
945 if ( $label == '' ) {
946 $label = $title->getPrefixedText();
948 $encLabel = htmlspecialchars( $label );
949 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
951 if ( ( $wgUploadMissingFileUrl || $wgUploadNavigationUrl || $wgEnableUploads ) && !$currentExists ) {
952 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
954 if ( $redir ) {
955 wfProfileOut( __METHOD__ );
956 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
959 $href = self::getUploadUrl( $title, $query );
961 wfProfileOut( __METHOD__ );
962 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
963 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES ) . '">' .
964 $encLabel . '</a>';
967 wfProfileOut( __METHOD__ );
968 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
972 * Get the URL to upload a certain file
974 * @param $destFile Title object of the file to upload
975 * @param string $query urlencoded query string to prepend
976 * @return String: urlencoded URL
978 protected static function getUploadUrl( $destFile, $query = '' ) {
979 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
980 $q = 'wpDestFile=' . $destFile->getPartialURL();
981 if ( $query != '' ) {
982 $q .= '&' . $query;
985 if ( $wgUploadMissingFileUrl ) {
986 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
987 } elseif ( $wgUploadNavigationUrl ) {
988 return wfAppendQuery( $wgUploadNavigationUrl, $q );
989 } else {
990 $upload = SpecialPage::getTitleFor( 'Upload' );
991 return $upload->getLocalURL( $q );
996 * Create a direct link to a given uploaded file.
998 * @param $title Title object.
999 * @param string $html pre-sanitized HTML
1000 * @param string $time MW timestamp of file creation time
1001 * @return String: HTML
1003 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
1004 $img = wfFindFile( $title, array( 'time' => $time ) );
1005 return self::makeMediaLinkFile( $title, $img, $html );
1009 * Create a direct link to a given uploaded file.
1010 * This will make a broken link if $file is false.
1012 * @param $title Title object.
1013 * @param $file File|bool mixed File object or false
1014 * @param string $html pre-sanitized HTML
1015 * @return String: HTML
1017 * @todo Handle invalid or missing images better.
1019 public static function makeMediaLinkFile( Title $title, $file, $html = '' ) {
1020 if ( $file && $file->exists() ) {
1021 $url = $file->getURL();
1022 $class = 'internal';
1023 } else {
1024 $url = self::getUploadUrl( $title );
1025 $class = 'new';
1027 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES );
1028 if ( $html == '' ) {
1029 $html = $alt;
1031 $u = htmlspecialchars( $url );
1032 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$html}</a>";
1036 * Make a link to a special page given its name and, optionally,
1037 * a message key from the link text.
1038 * Usage example: Linker::specialLink( 'Recentchanges' )
1040 * @return string
1042 public static function specialLink( $name, $key = '' ) {
1043 if ( $key == '' ) {
1044 $key = strtolower( $name );
1047 return self::linkKnown( SpecialPage::getTitleFor( $name ), wfMessage( $key )->text() );
1051 * Make an external link
1052 * @param string $url URL to link to
1053 * @param string $text text of link
1054 * @param $escape Boolean: do we escape the link text?
1055 * @param string $linktype type of external link. Gets added to the classes
1056 * @param array $attribs of extra attributes to <a>
1057 * @param $title Title|null Title object used for title specific link attributes
1058 * @return string
1060 public static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array(), $title = null ) {
1061 global $wgTitle;
1062 $class = "external";
1063 if ( $linktype ) {
1064 $class .= " $linktype";
1066 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1067 $class .= " {$attribs['class']}";
1069 $attribs['class'] = $class;
1071 if ( $escape ) {
1072 $text = htmlspecialchars( $text );
1075 if ( !$title ) {
1076 $title = $wgTitle;
1078 $attribs['rel'] = Parser::getExternalLinkRel( $url, $title );
1079 $link = '';
1080 $success = wfRunHooks( 'LinkerMakeExternalLink',
1081 array( &$url, &$text, &$link, &$attribs, $linktype ) );
1082 if ( !$success ) {
1083 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
1084 return $link;
1086 $attribs['href'] = $url;
1087 return Html::rawElement( 'a', $attribs, $text );
1091 * Make user link (or user contributions for unregistered users)
1092 * @param $userId Integer: user id in database.
1093 * @param string $userName user name in database.
1094 * @param string $altUserName text to display instead of the user name (optional)
1095 * @return String: HTML fragment
1096 * @since 1.19 Method exists for a long time. $altUserName was added in 1.19.
1098 public static function userLink( $userId, $userName, $altUserName = false ) {
1099 if ( $userId == 0 ) {
1100 $page = SpecialPage::getTitleFor( 'Contributions', $userName );
1101 if ( $altUserName === false ) {
1102 $altUserName = IP::prettifyIP( $userName );
1104 } else {
1105 $page = Title::makeTitle( NS_USER, $userName );
1108 return self::link(
1109 $page,
1110 htmlspecialchars( $altUserName !== false ? $altUserName : $userName ),
1111 array( 'class' => 'mw-userlink' )
1116 * Generate standard user tool links (talk, contributions, block link, etc.)
1118 * @param $userId Integer: user identifier
1119 * @param string $userText user name or IP address
1120 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
1121 * red if the user has no edits?
1122 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK and Linker::TOOL_LINKS_EMAIL)
1123 * @param $edits Integer: user edit count (optional, for performance)
1124 * @return String: HTML fragment
1126 public static function userToolLinks(
1127 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1129 global $wgUser, $wgDisableAnonTalk, $wgLang;
1130 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1131 $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1132 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1134 $items = array();
1135 if ( $talkable ) {
1136 $items[] = self::userTalkLink( $userId, $userText );
1138 if ( $userId ) {
1139 // check if the user has an edit
1140 $attribs = array();
1141 if ( $redContribsWhenNoEdits ) {
1142 if ( intval( $edits ) === 0 && $edits !== 0 ) {
1143 $user = User::newFromId( $userId );
1144 $edits = $user->getEditCount();
1146 if ( $edits === 0 ) {
1147 $attribs['class'] = 'new';
1150 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1152 $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1154 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1155 $items[] = self::blockLink( $userId, $userText );
1158 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1159 $items[] = self::emailLink( $userId, $userText );
1162 wfRunHooks( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1164 if ( $items ) {
1165 return wfMessage( 'word-separator' )->plain()
1166 . '<span class="mw-usertoollinks">'
1167 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1168 . '</span>';
1169 } else {
1170 return '';
1175 * Alias for userToolLinks( $userId, $userText, true );
1176 * @param $userId Integer: user identifier
1177 * @param string $userText user name or IP address
1178 * @param $edits Integer: user edit count (optional, for performance)
1179 * @return String
1181 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1182 return self::userToolLinks( $userId, $userText, true, 0, $edits );
1186 * @param $userId Integer: user id in database.
1187 * @param string $userText user name in database.
1188 * @return String: HTML fragment with user talk link
1190 public static function userTalkLink( $userId, $userText ) {
1191 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1192 $userTalkLink = self::link( $userTalkPage, wfMessage( 'talkpagelinktext' )->escaped() );
1193 return $userTalkLink;
1197 * @param $userId Integer: userid
1198 * @param string $userText user name in database.
1199 * @return String: HTML fragment with block link
1201 public static function blockLink( $userId, $userText ) {
1202 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1203 $blockLink = self::link( $blockPage, wfMessage( 'blocklink' )->escaped() );
1204 return $blockLink;
1208 * @param $userId Integer: userid
1209 * @param string $userText user name in database.
1210 * @return String: HTML fragment with e-mail user link
1212 public static function emailLink( $userId, $userText ) {
1213 $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1214 $emailLink = self::link( $emailPage, wfMessage( 'emaillink' )->escaped() );
1215 return $emailLink;
1219 * Generate a user link if the current user is allowed to view it
1220 * @param $rev Revision object.
1221 * @param $isPublic Boolean: show only if all users can see it
1222 * @return String: HTML fragment
1224 public static function revUserLink( $rev, $isPublic = false ) {
1225 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1226 $link = wfMessage( 'rev-deleted-user' )->escaped();
1227 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1228 $link = self::userLink( $rev->getUser( Revision::FOR_THIS_USER ),
1229 $rev->getUserText( Revision::FOR_THIS_USER ) );
1230 } else {
1231 $link = wfMessage( 'rev-deleted-user' )->escaped();
1233 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1234 return '<span class="history-deleted">' . $link . '</span>';
1236 return $link;
1240 * Generate a user tool link cluster if the current user is allowed to view it
1241 * @param $rev Revision object.
1242 * @param $isPublic Boolean: show only if all users can see it
1243 * @return string HTML
1245 public static function revUserTools( $rev, $isPublic = false ) {
1246 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1247 $link = wfMessage( 'rev-deleted-user' )->escaped();
1248 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1249 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1250 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1251 $link = self::userLink( $userId, $userText )
1252 . wfMessage( 'word-separator' )->plain()
1253 . self::userToolLinks( $userId, $userText );
1254 } else {
1255 $link = wfMessage( 'rev-deleted-user' )->escaped();
1257 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1258 return ' <span class="history-deleted">' . $link . '</span>';
1260 return $link;
1264 * This function is called by all recent changes variants, by the page history,
1265 * and by the user contributions list. It is responsible for formatting edit
1266 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1267 * auto-generated comments (from section editing) and formats [[wikilinks]].
1269 * @author Erik Moeller <moeller@scireview.de>
1271 * Note: there's not always a title to pass to this function.
1272 * Since you can't set a default parameter for a reference, I've turned it
1273 * temporarily to a value pass. Should be adjusted further. --brion
1275 * @param $comment String
1276 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1277 * @param $local Boolean: whether section links should refer to local page
1278 * @return mixed|String
1280 public static function formatComment( $comment, $title = null, $local = false ) {
1281 wfProfileIn( __METHOD__ );
1283 # Sanitize text a bit:
1284 $comment = str_replace( "\n", " ", $comment );
1285 # Allow HTML entities (for bug 13815)
1286 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1288 # Render autocomments and make links:
1289 $comment = self::formatAutocomments( $comment, $title, $local );
1290 $comment = self::formatLinksInComment( $comment, $title, $local );
1292 wfProfileOut( __METHOD__ );
1293 return $comment;
1297 * @var Title
1299 static $autocommentTitle;
1300 static $autocommentLocal;
1303 * Converts autogenerated comments in edit summaries into section links.
1304 * The pattern for autogen comments is / * foo * /, which makes for
1305 * some nasty regex.
1306 * We look for all comments, match any text before and after the comment,
1307 * add a separator where needed and format the comment itself with CSS
1308 * Called by Linker::formatComment.
1310 * @param string $comment comment text
1311 * @param $title Title|null An optional title object used to links to sections
1312 * @param $local Boolean: whether section links should refer to local page
1313 * @return String: formatted comment
1315 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1316 // Bah!
1317 self::$autocommentTitle = $title;
1318 self::$autocommentLocal = $local;
1319 $comment = preg_replace_callback(
1320 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1321 array( 'Linker', 'formatAutocommentsCallback' ),
1322 $comment );
1323 self::$autocommentTitle = null;
1324 self::$autocommentLocal = null;
1325 return $comment;
1329 * Helper function for Linker::formatAutocomments
1330 * @param $match
1331 * @return string
1333 private static function formatAutocommentsCallback( $match ) {
1334 global $wgLang;
1335 $title = self::$autocommentTitle;
1336 $local = self::$autocommentLocal;
1338 $pre = $match[1];
1339 $auto = $match[2];
1340 $post = $match[3];
1341 $comment = null;
1342 wfRunHooks( 'FormatAutocomments', array( &$comment, $pre, $auto, $post, $title, $local ) );
1343 if ( $comment === null ) {
1344 $link = '';
1345 if ( $title ) {
1346 $section = $auto;
1348 # Remove links that a user may have manually put in the autosummary
1349 # This could be improved by copying as much of Parser::stripSectionName as desired.
1350 $section = str_replace( '[[:', '', $section );
1351 $section = str_replace( '[[', '', $section );
1352 $section = str_replace( ']]', '', $section );
1354 $section = Sanitizer::normalizeSectionNameWhitespace( $section ); # bug 22784
1355 if ( $local ) {
1356 $sectionTitle = Title::newFromText( '#' . $section );
1357 } else {
1358 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1359 $title->getDBkey(), $section );
1361 if ( $sectionTitle ) {
1362 $link = self::link( $sectionTitle,
1363 $wgLang->getArrow(), array(), array(),
1364 'noclasses' );
1365 } else {
1366 $link = '';
1369 if ( $pre ) {
1370 # written summary $presep autocomment (summary /* section */)
1371 $pre .= wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1373 if ( $post ) {
1374 # autocomment $postsep written summary (/* section */ summary)
1375 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1377 $auto = '<span class="autocomment">' . $auto . '</span>';
1378 $comment = $pre . $link . $wgLang->getDirMark() . '<span dir="auto">' . $auto . $post . '</span>';
1380 return $comment;
1384 * @var Title
1386 static $commentContextTitle;
1387 static $commentLocal;
1390 * Formats wiki links and media links in text; all other wiki formatting
1391 * is ignored
1393 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1394 * @param string $comment text to format links in
1395 * @param $title Title|null An optional title object used to links to sections
1396 * @param $local Boolean: whether section links should refer to local page
1397 * @return String
1399 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1400 self::$commentContextTitle = $title;
1401 self::$commentLocal = $local;
1402 $html = preg_replace_callback(
1404 \[\[
1405 :? # ignore optional leading colon
1406 ([^\]|]+) # 1. link target; page names cannot include ] or |
1407 (?:\|
1408 # 2. a pipe-separated substring; only the last is captured
1409 # Stop matching at | and ]] without relying on backtracking.
1410 ((?:]?[^\]|])*+)
1412 \]\]
1413 ([^[]*) # 3. link trail (the text up until the next link)
1414 /x',
1415 array( 'Linker', 'formatLinksInCommentCallback' ),
1416 $comment );
1417 self::$commentContextTitle = null;
1418 self::$commentLocal = null;
1419 return $html;
1423 * @param $match
1424 * @return mixed
1426 protected static function formatLinksInCommentCallback( $match ) {
1427 global $wgContLang;
1429 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1430 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1432 $comment = $match[0];
1434 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1435 if ( strpos( $match[1], '%' ) !== false ) {
1436 $match[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $match[1] ) );
1439 # Handle link renaming [[foo|text]] will show link as "text"
1440 if ( $match[2] != "" ) {
1441 $text = $match[2];
1442 } else {
1443 $text = $match[1];
1445 $submatch = array();
1446 $thelink = null;
1447 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1448 # Media link; trail not supported.
1449 $linkRegexp = '/\[\[(.*?)\]\]/';
1450 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1451 if ( $title ) {
1452 $thelink = self::makeMediaLinkObj( $title, $text );
1454 } else {
1455 # Other kind of link
1456 if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1457 $trail = $submatch[1];
1458 } else {
1459 $trail = "";
1461 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1462 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1463 $match[1] = substr( $match[1], 1 );
1465 list( $inside, $trail ) = self::splitTrail( $trail );
1467 $linkText = $text;
1468 $linkTarget = self::normalizeSubpageLink( self::$commentContextTitle,
1469 $match[1], $linkText );
1471 $target = Title::newFromText( $linkTarget );
1472 if ( $target ) {
1473 if ( $target->getText() == '' && $target->getInterwiki() === ''
1474 && !self::$commentLocal && self::$commentContextTitle )
1476 $newTarget = clone ( self::$commentContextTitle );
1477 $newTarget->setFragment( '#' . $target->getFragment() );
1478 $target = $newTarget;
1480 $thelink = self::link(
1481 $target,
1482 $linkText . $inside
1483 ) . $trail;
1486 if ( $thelink ) {
1487 // If the link is still valid, go ahead and replace it in!
1488 $comment = preg_replace( $linkRegexp, StringUtils::escapeRegexReplacement( $thelink ), $comment, 1 );
1491 return $comment;
1495 * @param $contextTitle Title
1496 * @param $target
1497 * @param $text
1498 * @return string
1500 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1501 # Valid link forms:
1502 # Foobar -- normal
1503 # :Foobar -- override special treatment of prefix (images, language links)
1504 # /Foobar -- convert to CurrentPage/Foobar
1505 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1506 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1507 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1509 wfProfileIn( __METHOD__ );
1510 $ret = $target; # default return value is no change
1512 # Some namespaces don't allow subpages,
1513 # so only perform processing if subpages are allowed
1514 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1515 $hash = strpos( $target, '#' );
1516 if ( $hash !== false ) {
1517 $suffix = substr( $target, $hash );
1518 $target = substr( $target, 0, $hash );
1519 } else {
1520 $suffix = '';
1522 # bug 7425
1523 $target = trim( $target );
1524 # Look at the first character
1525 if ( $target != '' && $target[0] === '/' ) {
1526 # / at end means we don't want the slash to be shown
1527 $m = array();
1528 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1529 if ( $trailingSlashes ) {
1530 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1531 } else {
1532 $noslash = substr( $target, 1 );
1535 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1536 if ( $text === '' ) {
1537 $text = $target . $suffix;
1538 } # this might be changed for ugliness reasons
1539 } else {
1540 # check for .. subpage backlinks
1541 $dotdotcount = 0;
1542 $nodotdot = $target;
1543 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1544 ++$dotdotcount;
1545 $nodotdot = substr( $nodotdot, 3 );
1547 if ( $dotdotcount > 0 ) {
1548 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1549 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1550 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1551 # / at the end means don't show full path
1552 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1553 $nodotdot = substr( $nodotdot, 0, -1 );
1554 if ( $text === '' ) {
1555 $text = $nodotdot . $suffix;
1558 $nodotdot = trim( $nodotdot );
1559 if ( $nodotdot != '' ) {
1560 $ret .= '/' . $nodotdot;
1562 $ret .= $suffix;
1568 wfProfileOut( __METHOD__ );
1569 return $ret;
1573 * Wrap a comment in standard punctuation and formatting if
1574 * it's non-empty, otherwise return empty string.
1576 * @param $comment String
1577 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1578 * @param $local Boolean: whether section links should refer to local page
1580 * @return string
1582 public static function commentBlock( $comment, $title = null, $local = false ) {
1583 // '*' used to be the comment inserted by the software way back
1584 // in antiquity in case none was provided, here for backwards
1585 // compatibility, acc. to brion -ævar
1586 if ( $comment == '' || $comment == '*' ) {
1587 return '';
1588 } else {
1589 $formatted = self::formatComment( $comment, $title, $local );
1590 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1591 return " <span class=\"comment\">$formatted</span>";
1596 * Wrap and format the given revision's comment block, if the current
1597 * user is allowed to view it.
1599 * @param $rev Revision object
1600 * @param $local Boolean: whether section links should refer to local page
1601 * @param $isPublic Boolean: show only if all users can see it
1602 * @return String: HTML fragment
1604 public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1605 if ( $rev->getRawComment() == "" ) {
1606 return "";
1608 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1609 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1610 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1611 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1612 $rev->getTitle(), $local );
1613 } else {
1614 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1616 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1617 return " <span class=\"history-deleted\">$block</span>";
1619 return $block;
1623 * @param $size
1624 * @return string
1626 public static function formatRevisionSize( $size ) {
1627 if ( $size == 0 ) {
1628 $stxt = wfMessage( 'historyempty' )->escaped();
1629 } else {
1630 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1631 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1633 return "<span class=\"history-size\">$stxt</span>";
1637 * Add another level to the Table of Contents
1639 * @return string
1641 public static function tocIndent() {
1642 return "\n<ul>";
1646 * Finish one or more sublevels on the Table of Contents
1648 * @return string
1650 public static function tocUnindent( $level ) {
1651 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1655 * parameter level defines if we are on an indentation level
1657 * @return string
1659 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1660 $classes = "toclevel-$level";
1661 if ( $sectionIndex !== false ) {
1662 $classes .= " tocsection-$sectionIndex";
1664 return "\n<li class=\"$classes\"><a href=\"#" .
1665 $anchor . '"><span class="tocnumber">' .
1666 $tocnumber . '</span> <span class="toctext">' .
1667 $tocline . '</span></a>';
1671 * End a Table Of Contents line.
1672 * tocUnindent() will be used instead if we're ending a line below
1673 * the new level.
1674 * @return string
1676 public static function tocLineEnd() {
1677 return "</li>\n";
1681 * Wraps the TOC in a table and provides the hide/collapse javascript.
1683 * @param string $toc html of the Table Of Contents
1684 * @param $lang String|Language|false: Language for the toc title, defaults to user language
1685 * @return String: full html of the TOC
1687 public static function tocList( $toc, $lang = false ) {
1688 $lang = wfGetLangObj( $lang );
1689 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1691 return '<div id="toc" class="toc">'
1692 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1693 . $toc
1694 . "</ul>\n</div>\n";
1698 * Generate a table of contents from a section tree
1699 * Currently unused.
1701 * @param array $tree Return value of ParserOutput::getSections()
1702 * @return String: HTML fragment
1704 public static function generateTOC( $tree ) {
1705 $toc = '';
1706 $lastLevel = 0;
1707 foreach ( $tree as $section ) {
1708 if ( $section['toclevel'] > $lastLevel ) {
1709 $toc .= self::tocIndent();
1710 } elseif ( $section['toclevel'] < $lastLevel ) {
1711 $toc .= self::tocUnindent(
1712 $lastLevel - $section['toclevel'] );
1713 } else {
1714 $toc .= self::tocLineEnd();
1717 $toc .= self::tocLine( $section['anchor'],
1718 $section['line'], $section['number'],
1719 $section['toclevel'], $section['index'] );
1720 $lastLevel = $section['toclevel'];
1722 $toc .= self::tocLineEnd();
1723 return self::tocList( $toc );
1727 * Create a headline for content
1729 * @param $level Integer: the level of the headline (1-6)
1730 * @param string $attribs any attributes for the headline, starting with
1731 * a space and ending with '>'
1732 * This *must* be at least '>' for no attribs
1733 * @param string $anchor the anchor to give the headline (the bit after the #)
1734 * @param string $html html for the text of the header
1735 * @param string $link HTML to add for the section edit link
1736 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1737 * backward compatibility (false to omit)
1739 * @return String: HTML headline
1741 public static function makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor = false ) {
1742 $ret = "<h$level$attribs"
1743 . "<span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1744 . $link
1745 . "</h$level>";
1746 if ( $legacyAnchor !== false ) {
1747 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1749 return $ret;
1753 * Split a link trail, return the "inside" portion and the remainder of the trail
1754 * as a two-element array
1755 * @return array
1757 static function splitTrail( $trail ) {
1758 global $wgContLang;
1759 $regex = $wgContLang->linkTrail();
1760 $inside = '';
1761 if ( $trail !== '' ) {
1762 $m = array();
1763 if ( preg_match( $regex, $trail, $m ) ) {
1764 $inside = $m[1];
1765 $trail = $m[2];
1768 return array( $inside, $trail );
1772 * Generate a rollback link for a given revision. Currently it's the
1773 * caller's responsibility to ensure that the revision is the top one. If
1774 * it's not, of course, the user will get an error message.
1776 * If the calling page is called with the parameter &bot=1, all rollback
1777 * links also get that parameter. It causes the edit itself and the rollback
1778 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1779 * changes, so this allows sysops to combat a busy vandal without bothering
1780 * other users.
1782 * If the option verify is set this function will return the link only in case the
1783 * revision can be reverted. Please note that due to performance limitations
1784 * it might be assumed that a user isn't the only contributor of a page while
1785 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1786 * work if $wgShowRollbackEditCount is disabled, so this can only function
1787 * as an additional check.
1789 * If the option noBrackets is set the rollback link wont be enclosed in []
1791 * @param $rev Revision object
1792 * @param $context IContextSource context to use or null for the main context.
1793 * @param $options array
1794 * @return string
1796 public static function generateRollback( $rev, IContextSource $context = null, $options = array( 'verify' ) ) {
1797 if ( $context === null ) {
1798 $context = RequestContext::getMain();
1800 $editCount = false;
1801 if ( in_array( 'verify', $options ) ) {
1802 $editCount = self::getRollbackEditCount( $rev, true );
1803 if ( $editCount === false ) {
1804 return '';
1808 $inner = self::buildRollbackLink( $rev, $context, $editCount );
1810 if ( !in_array( 'noBrackets', $options ) ) {
1811 $inner = $context->msg( 'brackets' )->rawParams( $inner )->plain();
1814 return '<span class="mw-rollback-link">' . $inner . '</span>';
1818 * This function will return the number of revisions which a rollback
1819 * would revert and, if $verify is set it will verify that a revision
1820 * can be reverted (that the user isn't the only contributor and the
1821 * revision we might rollback to isn't deleted). These checks can only
1822 * function as an additional check as this function only checks against
1823 * the last $wgShowRollbackEditCount edits.
1825 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1826 * is set and the user is the only contributor of the page.
1828 * @param $rev Revision object
1829 * @param bool $verify Try to verify that this revision can really be rolled back
1830 * @return integer|bool|null
1832 public static function getRollbackEditCount( $rev, $verify ) {
1833 global $wgShowRollbackEditCount;
1834 if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
1835 // Nothing has happened, indicate this by returning 'null'
1836 return null;
1839 $dbr = wfGetDB( DB_SLAVE );
1841 // Up to the value of $wgShowRollbackEditCount revisions are counted
1842 $res = $dbr->select(
1843 'revision',
1844 array( 'rev_user_text', 'rev_deleted' ),
1845 // $rev->getPage() returns null sometimes
1846 array( 'rev_page' => $rev->getTitle()->getArticleID() ),
1847 __METHOD__,
1848 array(
1849 'USE INDEX' => array( 'revision' => 'page_timestamp' ),
1850 'ORDER BY' => 'rev_timestamp DESC',
1851 'LIMIT' => $wgShowRollbackEditCount + 1
1855 $editCount = 0;
1856 $moreRevs = false;
1857 foreach ( $res as $row ) {
1858 if ( $rev->getRawUserText() != $row->rev_user_text ) {
1859 if ( $verify && ( $row->rev_deleted & Revision::DELETED_TEXT || $row->rev_deleted & Revision::DELETED_USER ) ) {
1860 // If the user or the text of the revision we might rollback to is deleted in some way we can't rollback
1861 // Similar to the sanity checks in WikiPage::commitRollback
1862 return false;
1864 $moreRevs = true;
1865 break;
1867 $editCount++;
1870 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1871 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1872 // and there weren't any other revisions. That means that the current user is the only
1873 // editor, so we can't rollback
1874 return false;
1876 return $editCount;
1880 * Build a raw rollback link, useful for collections of "tool" links
1882 * @param $rev Revision object
1883 * @param $context IContextSource context to use or null for the main context.
1884 * @param $editCount integer Number of edits that would be reverted
1885 * @return String: HTML fragment
1887 public static function buildRollbackLink( $rev, IContextSource $context = null, $editCount = false ) {
1888 global $wgShowRollbackEditCount, $wgMiserMode;
1890 // To config which pages are effected by miser mode
1891 $disableRollbackEditCountSpecialPage = array( 'Recentchanges', 'Watchlist' );
1893 if ( $context === null ) {
1894 $context = RequestContext::getMain();
1897 $title = $rev->getTitle();
1898 $query = array(
1899 'action' => 'rollback',
1900 'from' => $rev->getUserText(),
1901 'token' => $context->getUser()->getEditToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1903 if ( $context->getRequest()->getBool( 'bot' ) ) {
1904 $query['bot'] = '1';
1905 $query['hidediff'] = '1'; // bug 15999
1908 $disableRollbackEditCount = false;
1909 if ( $wgMiserMode ) {
1910 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1911 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1912 $disableRollbackEditCount = true;
1913 break;
1918 if ( !$disableRollbackEditCount && is_int( $wgShowRollbackEditCount ) && $wgShowRollbackEditCount > 0 ) {
1919 if ( !is_numeric( $editCount ) ) {
1920 $editCount = self::getRollbackEditCount( $rev, false );
1923 if ( $editCount > $wgShowRollbackEditCount ) {
1924 $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )->numParams( $wgShowRollbackEditCount )->parse();
1925 } else {
1926 $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1929 return self::link(
1930 $title,
1931 $editCount_output,
1932 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1933 $query,
1934 array( 'known', 'noclasses' )
1936 } else {
1937 return self::link(
1938 $title,
1939 $context->msg( 'rollbacklink' )->escaped(),
1940 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1941 $query,
1942 array( 'known', 'noclasses' )
1948 * Returns HTML for the "templates used on this page" list.
1950 * Make an HTML list of templates, and then add a "More..." link at
1951 * the bottom. If $more is null, do not add a "More..." link. If $more
1952 * is a Title, make a link to that title and use it. If $more is a string,
1953 * directly paste it in as the link (escaping needs to be done manually).
1954 * Finally, if $more is a Message, call toString().
1956 * @param array $templates Array of templates from Article::getUsedTemplate or similar
1957 * @param bool $preview Whether this is for a preview
1958 * @param bool $section Whether this is for a section edit
1959 * @param Title|Message|string|null $more An escaped link for "More..." of the templates
1960 * @return String: HTML output
1962 public static function formatTemplates( $templates, $preview = false, $section = false, $more = null ) {
1963 wfProfileIn( __METHOD__ );
1965 $outText = '';
1966 if ( count( $templates ) > 0 ) {
1967 # Do a batch existence check
1968 $batch = new LinkBatch;
1969 foreach ( $templates as $title ) {
1970 $batch->addObj( $title );
1972 $batch->execute();
1974 # Construct the HTML
1975 $outText = '<div class="mw-templatesUsedExplanation">';
1976 if ( $preview ) {
1977 $outText .= wfMessage( 'templatesusedpreview' )->numParams( count( $templates ) )
1978 ->parseAsBlock();
1979 } elseif ( $section ) {
1980 $outText .= wfMessage( 'templatesusedsection' )->numParams( count( $templates ) )
1981 ->parseAsBlock();
1982 } else {
1983 $outText .= wfMessage( 'templatesused' )->numParams( count( $templates ) )
1984 ->parseAsBlock();
1986 $outText .= "</div><ul>\n";
1988 usort( $templates, 'Title::compare' );
1989 foreach ( $templates as $titleObj ) {
1990 $r = $titleObj->getRestrictions( 'edit' );
1991 if ( in_array( 'sysop', $r ) ) {
1992 $protected = wfMessage( 'template-protected' )->parse();
1993 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1994 $protected = wfMessage( 'template-semiprotected' )->parse();
1995 } else {
1996 $protected = '';
1998 if ( $titleObj->quickUserCan( 'edit' ) ) {
1999 $editLink = self::link(
2000 $titleObj,
2001 wfMessage( 'editlink' )->text(),
2002 array(),
2003 array( 'action' => 'edit' )
2005 } else {
2006 $editLink = self::link(
2007 $titleObj,
2008 wfMessage( 'viewsourcelink' )->text(),
2009 array(),
2010 array( 'action' => 'edit' )
2013 $outText .= '<li>' . self::link( $titleObj )
2014 . wfMessage( 'word-separator' )->escaped()
2015 . wfMessage( 'parentheses' )->rawParams( $editLink )->escaped()
2016 . wfMessage( 'word-separator' )->escaped()
2017 . $protected . '</li>';
2020 if ( $more instanceof Title ) {
2021 $outText .= '<li>' . self::link( $more, wfMessage( 'moredotdotdot' ) ) . '</li>';
2022 } elseif ( $more ) {
2023 $outText .= "<li>$more</li>";
2026 $outText .= '</ul>';
2028 wfProfileOut( __METHOD__ );
2029 return $outText;
2033 * Returns HTML for the "hidden categories on this page" list.
2035 * @param array $hiddencats of hidden categories from Article::getHiddenCategories
2036 * or similar
2037 * @return String: HTML output
2039 public static function formatHiddenCategories( $hiddencats ) {
2040 wfProfileIn( __METHOD__ );
2042 $outText = '';
2043 if ( count( $hiddencats ) > 0 ) {
2044 # Construct the HTML
2045 $outText = '<div class="mw-hiddenCategoriesExplanation">';
2046 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
2047 $outText .= "</div><ul>\n";
2049 foreach ( $hiddencats as $titleObj ) {
2050 $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
2052 $outText .= '</ul>';
2054 wfProfileOut( __METHOD__ );
2055 return $outText;
2059 * Format a size in bytes for output, using an appropriate
2060 * unit (B, KB, MB or GB) according to the magnitude in question
2062 * @param int $size Size to format
2063 * @return String
2065 public static function formatSize( $size ) {
2066 global $wgLang;
2067 return htmlspecialchars( $wgLang->formatSize( $size ) );
2071 * Given the id of an interface element, constructs the appropriate title
2072 * attribute from the system messages. (Note, this is usually the id but
2073 * isn't always, because sometimes the accesskey needs to go on a different
2074 * element than the id, for reverse-compatibility, etc.)
2076 * @param string $name id of the element, minus prefixes.
2077 * @param $options Mixed: null or the string 'withaccess' to add an access-
2078 * key hint
2079 * @return String: contents of the title attribute (which you must HTML-
2080 * escape), or false for no title attribute
2082 public static function titleAttrib( $name, $options = null ) {
2083 wfProfileIn( __METHOD__ );
2085 $message = wfMessage( "tooltip-$name" );
2087 if ( !$message->exists() ) {
2088 $tooltip = false;
2089 } else {
2090 $tooltip = $message->text();
2091 # Compatibility: formerly some tooltips had [alt-.] hardcoded
2092 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2093 # Message equal to '-' means suppress it.
2094 if ( $tooltip == '-' ) {
2095 $tooltip = false;
2099 if ( $options == 'withaccess' ) {
2100 $accesskey = self::accesskey( $name );
2101 if ( $accesskey !== false ) {
2102 if ( $tooltip === false || $tooltip === '' ) {
2103 $tooltip = "[$accesskey]";
2104 } else {
2105 $tooltip .= " [$accesskey]";
2110 wfProfileOut( __METHOD__ );
2111 return $tooltip;
2114 static $accesskeycache;
2117 * Given the id of an interface element, constructs the appropriate
2118 * accesskey attribute from the system messages. (Note, this is usually
2119 * the id but isn't always, because sometimes the accesskey needs to go on
2120 * a different element than the id, for reverse-compatibility, etc.)
2122 * @param string $name id of the element, minus prefixes.
2123 * @return String: contents of the accesskey attribute (which you must HTML-
2124 * escape), or false for no accesskey attribute
2126 public static function accesskey( $name ) {
2127 if ( isset( self::$accesskeycache[$name] ) ) {
2128 return self::$accesskeycache[$name];
2130 wfProfileIn( __METHOD__ );
2132 $message = wfMessage( "accesskey-$name" );
2134 if ( !$message->exists() ) {
2135 $accesskey = false;
2136 } else {
2137 $accesskey = $message->plain();
2138 if ( $accesskey === '' || $accesskey === '-' ) {
2139 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2140 # attribute, but this is broken for accesskey: that might be a useful
2141 # value.
2142 $accesskey = false;
2146 wfProfileOut( __METHOD__ );
2147 return self::$accesskeycache[$name] = $accesskey;
2151 * Get a revision-deletion link, or disabled link, or nothing, depending
2152 * on user permissions & the settings on the revision.
2154 * Will use forward-compatible revision ID in the Special:RevDelete link
2155 * if possible, otherwise the timestamp-based ID which may break after
2156 * undeletion.
2158 * @param User $user
2159 * @param Revision $rev
2160 * @param Revision $title
2161 * @return string HTML fragment
2163 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
2164 $canHide = $user->isAllowed( 'deleterevision' );
2165 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2166 return '';
2169 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
2170 return Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2171 } else {
2172 if ( $rev->getId() ) {
2173 // RevDelete links using revision ID are stable across
2174 // page deletion and undeletion; use when possible.
2175 $query = array(
2176 'type' => 'revision',
2177 'target' => $title->getPrefixedDBkey(),
2178 'ids' => $rev->getId()
2180 } else {
2181 // Older deleted entries didn't save a revision ID.
2182 // We have to refer to these by timestamp, ick!
2183 $query = array(
2184 'type' => 'archive',
2185 'target' => $title->getPrefixedDBkey(),
2186 'ids' => $rev->getTimestamp()
2189 return Linker::revDeleteLink( $query,
2190 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2195 * Creates a (show/hide) link for deleting revisions/log entries
2197 * @param array $query query parameters to be passed to link()
2198 * @param $restricted Boolean: set to true to use a "<strong>" instead of a "<span>"
2199 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2201 * @return String: HTML "<a>" link to Special:Revisiondelete, wrapped in a
2202 * span to allow for customization of appearance with CSS
2204 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
2205 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2206 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2207 $html = wfMessage( $msgKey )->escaped();
2208 $tag = $restricted ? 'strong' : 'span';
2209 $link = self::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
2210 return Xml::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $link )->escaped() );
2214 * Creates a dead (show/hide) link for deleting revisions/log entries
2216 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2218 * @return string HTML text wrapped in a span to allow for customization
2219 * of appearance with CSS
2221 public static function revDeleteLinkDisabled( $delete = true ) {
2222 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2223 $html = wfMessage( $msgKey )->escaped();
2224 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2225 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), $htmlParentheses );
2228 /* Deprecated methods */
2231 * @deprecated since 1.16 Use link()
2233 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
2234 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
2236 * @param string $title The text of the title
2237 * @param string $text Link text
2238 * @param string $query Optional query part
2239 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
2240 * be included in the link text. Other characters will be appended after
2241 * the end of the link.
2242 * @return string
2244 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
2245 wfDeprecated( __METHOD__, '1.16' );
2247 $nt = Title::newFromText( $title );
2248 if ( $nt instanceof Title ) {
2249 return self::makeBrokenLinkObj( $nt, $text, $query, $trail );
2250 } else {
2251 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
2252 return $text == '' ? $title : $text;
2257 * @deprecated since 1.16 Use link(); warnings since 1.21
2259 * Make a link for a title which may or may not be in the database. If you need to
2260 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
2261 * call to this will result in a DB query.
2263 * @param $nt Title: the title object to make the link from, e.g. from
2264 * Title::newFromText.
2265 * @param $text String: link text
2266 * @param string $query optional query part
2267 * @param string $trail optional trail. Alphabetic characters at the start of this string will
2268 * be included in the link text. Other characters will be appended after
2269 * the end of the link.
2270 * @param string $prefix optional prefix. As trail, only before instead of after.
2271 * @return string
2273 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
2274 wfDeprecated( __METHOD__, '1.21' );
2276 wfProfileIn( __METHOD__ );
2277 $query = wfCgiToArray( $query );
2278 list( $inside, $trail ) = self::splitTrail( $trail );
2279 if ( $text === '' ) {
2280 $text = self::linkText( $nt );
2283 $ret = self::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
2285 wfProfileOut( __METHOD__ );
2286 return $ret;
2290 * @deprecated since 1.16 Use link(); warnings since 1.21
2292 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
2293 * it doesn't have to do a database query. It's also valid for interwiki titles and special
2294 * pages.
2296 * @param $title Title object of target page
2297 * @param $text String: text to replace the title
2298 * @param $query String: link target
2299 * @param $trail String: text after link
2300 * @param string $prefix text before link text
2301 * @param string $aprops extra attributes to the a-element
2302 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
2303 * @return string the a-element
2305 static function makeKnownLinkObj(
2306 $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = '', $style = ''
2308 wfDeprecated( __METHOD__, '1.21' );
2310 wfProfileIn( __METHOD__ );
2312 if ( $text == '' ) {
2313 $text = self::linkText( $title );
2315 $attribs = Sanitizer::mergeAttributes(
2316 Sanitizer::decodeTagAttributes( $aprops ),
2317 Sanitizer::decodeTagAttributes( $style )
2319 $query = wfCgiToArray( $query );
2320 list( $inside, $trail ) = self::splitTrail( $trail );
2322 $ret = self::link( $title, "$prefix$text$inside", $attribs, $query,
2323 array( 'known', 'noclasses' ) ) . $trail;
2325 wfProfileOut( __METHOD__ );
2326 return $ret;
2330 * @deprecated since 1.16 Use link()
2332 * Make a red link to the edit page of a given title.
2334 * @param $title Title object of the target page
2335 * @param $text String: Link text
2336 * @param string $query Optional query part
2337 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
2338 * be included in the link text. Other characters will be appended after
2339 * the end of the link.
2340 * @param string $prefix Optional prefix
2341 * @return string
2343 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
2344 wfDeprecated( __METHOD__, '1.16' );
2346 wfProfileIn( __METHOD__ );
2348 list( $inside, $trail ) = self::splitTrail( $trail );
2349 if ( $text === '' ) {
2350 $text = self::linkText( $title );
2353 $ret = self::link( $title, "$prefix$text$inside", array(),
2354 wfCgiToArray( $query ), 'broken' ) . $trail;
2356 wfProfileOut( __METHOD__ );
2357 return $ret;
2361 * @deprecated since 1.16 Use link()
2363 * Make a coloured link.
2365 * @param $nt Title object of the target page
2366 * @param $colour Integer: colour of the link
2367 * @param $text String: link text
2368 * @param $query String: optional query part
2369 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2370 * be included in the link text. Other characters will be appended after
2371 * the end of the link.
2372 * @param string $prefix Optional prefix
2373 * @return string
2375 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2376 wfDeprecated( __METHOD__, '1.16' );
2378 if ( $colour != '' ) {
2379 $style = self::getInternalLinkAttributesObj( $nt, $text, $colour );
2380 } else {
2381 $style = '';
2383 return self::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2387 * Returns the attributes for the tooltip and access key.
2388 * @return array
2390 public static function tooltipAndAccesskeyAttribs( $name ) {
2391 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2392 # no attribute" instead of "output '' as value for attribute", this
2393 # would be three lines.
2394 $attribs = array(
2395 'title' => self::titleAttrib( $name, 'withaccess' ),
2396 'accesskey' => self::accesskey( $name )
2398 if ( $attribs['title'] === false ) {
2399 unset( $attribs['title'] );
2401 if ( $attribs['accesskey'] === false ) {
2402 unset( $attribs['accesskey'] );
2404 return $attribs;
2408 * Returns raw bits of HTML, use titleAttrib()
2409 * @return null|string
2411 public static function tooltip( $name, $options = null ) {
2412 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2413 # no attribute" instead of "output '' as value for attribute", this
2414 # would be two lines.
2415 $tooltip = self::titleAttrib( $name, $options );
2416 if ( $tooltip === false ) {
2417 return '';
2419 return Xml::expandAttributes( array(
2420 'title' => $tooltip
2421 ) );
2426 * @since 1.18
2428 class DummyLinker {
2431 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2432 * into static calls to the new Linker for backwards compatibility.
2434 * @param string $fname Name of called method
2435 * @param array $args Arguments to the method
2436 * @return mixed
2438 public function __call( $fname, $args ) {
2439 return call_user_func_array( array( 'Linker', $fname ), $args );