Make phpcs-strict pass on includes/ (7/7)
[mediawiki.git] / includes / Linker.php
blobd0759edd966a179046fc9244e165acad78d2e4f3
1 <?php
2 /**
3 * Methods to make links and related items.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 /**
24 * Some internal bits split of from Skin.php. These functions are used
25 * for primarily page content: links, embedded images, table of contents. Links
26 * are also used in the skin.
28 * @todo: turn this into a legacy interface for HtmlPageLinkRenderer and similar services.
30 * @ingroup Skins
32 class Linker {
33 /**
34 * Flags for userToolLinks()
36 const TOOL_LINKS_NOBLOCK = 1;
37 const TOOL_LINKS_EMAIL = 2;
39 /**
40 * Get the appropriate HTML attributes to add to the "a" element of an
41 * external link, as created by [wikisyntax].
43 * @param string $class The contents of the class attribute; if an empty
44 * string is passed, which is the default value, defaults to 'external'.
45 * @return string
46 * @deprecated since 1.18 Just pass the external class directly to something
47 * using Html::expandAttributes.
49 static function getExternalLinkAttributes( $class = 'external' ) {
50 wfDeprecated( __METHOD__, '1.18' );
51 return self::getLinkAttributesInternal( '', $class );
54 /**
55 * Get the appropriate HTML attributes to add to the "a" element of an interwiki link.
57 * @param string $title The title text for the link, URL-encoded (???) but
58 * not HTML-escaped
59 * @param string $unused Unused
60 * @param string $class The contents of the class attribute; if an empty
61 * string is passed, which is the default value, defaults to 'external'.
62 * @return string
64 static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
65 global $wgContLang;
67 # @todo FIXME: We have a whole bunch of handling here that doesn't happen in
68 # getExternalLinkAttributes, why?
69 $title = urldecode( $title );
70 $title = $wgContLang->checkTitleEncoding( $title );
71 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
73 return self::getLinkAttributesInternal( $title, $class );
76 /**
77 * Get the appropriate HTML attributes to add to the "a" element of an internal link.
79 * @param string $title The title text for the link, URL-encoded (???) but
80 * not HTML-escaped
81 * @param string $unused Unused
82 * @param string $class The contents of the class attribute, default none
83 * @return string
85 static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
86 $title = urldecode( $title );
87 $title = str_replace( '_', ' ', $title );
88 return self::getLinkAttributesInternal( $title, $class );
91 /**
92 * Get the appropriate HTML attributes to add to the "a" element of an internal
93 * link, given the Title object for the page we want to link to.
95 * @param Title $nt
96 * @param string $unused Unused
97 * @param string $class The contents of the class attribute, default none
98 * @param string|bool $title Optional (unescaped) string to use in the title
99 * attribute; if false, default to the name of the page we're linking to
100 * @return string
102 static function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
103 if ( $title === false ) {
104 $title = $nt->getPrefixedText();
106 return self::getLinkAttributesInternal( $title, $class );
110 * Common code for getLinkAttributesX functions
112 * @param string $title
113 * @param string $class
115 * @return string
117 private static function getLinkAttributesInternal( $title, $class ) {
118 $title = htmlspecialchars( $title );
119 $class = htmlspecialchars( $class );
120 $r = '';
121 if ( $class != '' ) {
122 $r .= " class=\"$class\"";
124 if ( $title != '' ) {
125 $r .= " title=\"$title\"";
127 return $r;
131 * Return the CSS colour of a known link
133 * @param Title $t
134 * @param int $threshold User defined threshold
135 * @return string CSS class
137 public static function getLinkColour( $t, $threshold ) {
138 $colour = '';
139 if ( $t->isRedirect() ) {
140 # Page is a redirect
141 $colour = 'mw-redirect';
142 } elseif ( $threshold > 0 && $t->isContentPage() &&
143 $t->exists() && $t->getLength() < $threshold
145 # Page is a stub
146 $colour = 'stub';
148 return $colour;
152 * This function returns an HTML link to the given target. It serves a few
153 * purposes:
154 * 1) If $target is a Title, the correct URL to link to will be figured
155 * out automatically.
156 * 2) It automatically adds the usual classes for various types of link
157 * targets: "new" for red links, "stub" for short articles, etc.
158 * 3) It escapes all attribute values safely so there's no risk of XSS.
159 * 4) It provides a default tooltip if the target is a Title (the page
160 * name of the target).
161 * link() replaces the old functions in the makeLink() family.
163 * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
165 * @param Title $target Can currently only be a Title, but this may
166 * change to support Images, literal URLs, etc.
167 * @param string $html The HTML contents of the <a> element, i.e.,
168 * the link text. This is raw HTML and will not be escaped. If null,
169 * defaults to the prefixed text of the Title; or if the Title is just a
170 * fragment, the contents of the fragment.
171 * @param array $customAttribs A key => value array of extra HTML attributes,
172 * such as title and class. (href is ignored.) Classes will be
173 * merged with the default classes, while other attributes will replace
174 * default attributes. All passed attribute values will be HTML-escaped.
175 * A false attribute value means to suppress that attribute.
176 * @param array $query The query string to append to the URL
177 * you're linking to, in key => value array form. Query keys and values
178 * will be URL-encoded.
179 * @param string|array $options String or array of strings:
180 * 'known': Page is known to exist, so don't check if it does.
181 * 'broken': Page is known not to exist, so don't check if it does.
182 * 'noclasses': Don't add any classes automatically (includes "new",
183 * "stub", "mw-redirect", "extiw"). Only use the class attribute
184 * provided, if any, so you get a simple blue link with no funny i-
185 * cons.
186 * 'forcearticlepath': Use the article path always, even with a querystring.
187 * Has compatibility issues on some setups, so avoid wherever possible.
188 * 'http': Force a full URL with http:// as the scheme.
189 * 'https': Force a full URL with https:// as the scheme.
190 * @return string HTML <a> attribute
192 public static function link(
193 $target, $html = null, $customAttribs = array(), $query = array(), $options = array()
195 wfProfileIn( __METHOD__ );
196 if ( !$target instanceof Title ) {
197 wfProfileOut( __METHOD__ );
198 return "<!-- ERROR -->$html";
201 if ( is_string( $query ) ) {
202 // some functions withing core using this still hand over query strings
203 wfDeprecated( __METHOD__ . ' with parameter $query as string (should be array)', '1.20' );
204 $query = wfCgiToArray( $query );
206 $options = (array)$options;
208 $dummy = new DummyLinker; // dummy linker instance for bc on the hooks
210 $ret = null;
211 if ( !wfRunHooks( 'LinkBegin', array( $dummy, $target, &$html,
212 &$customAttribs, &$query, &$options, &$ret ) ) ) {
213 wfProfileOut( __METHOD__ );
214 return $ret;
217 # Normalize the Title if it's a special page
218 $target = self::normaliseSpecialPage( $target );
220 # If we don't know whether the page exists, let's find out.
221 wfProfileIn( __METHOD__ . '-checkPageExistence' );
222 if ( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
223 if ( $target->isKnown() ) {
224 $options[] = 'known';
225 } else {
226 $options[] = 'broken';
229 wfProfileOut( __METHOD__ . '-checkPageExistence' );
231 $oldquery = array();
232 if ( in_array( "forcearticlepath", $options ) && $query ) {
233 $oldquery = $query;
234 $query = array();
237 # Note: we want the href attribute first, for prettiness.
238 $attribs = array( 'href' => self::linkUrl( $target, $query, $options ) );
239 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
240 $attribs['href'] = wfAppendQuery( $attribs['href'], $oldquery );
243 $attribs = array_merge(
244 $attribs,
245 self::linkAttribs( $target, $customAttribs, $options )
247 if ( is_null( $html ) ) {
248 $html = self::linkText( $target );
251 $ret = null;
252 if ( wfRunHooks( 'LinkEnd', array( $dummy, $target, $options, &$html, &$attribs, &$ret ) ) ) {
253 $ret = Html::rawElement( 'a', $attribs, $html );
256 wfProfileOut( __METHOD__ );
257 return $ret;
261 * Identical to link(), except $options defaults to 'known'.
262 * @return string
264 public static function linkKnown(
265 $target, $html = null, $customAttribs = array(),
266 $query = array(), $options = array( 'known', 'noclasses' )
268 return self::link( $target, $html, $customAttribs, $query, $options );
272 * Returns the Url used to link to a Title
274 * @param Title $target
275 * @param array $query query parameters
276 * @param array $options
277 * @return string
279 private static function linkUrl( $target, $query, $options ) {
280 wfProfileIn( __METHOD__ );
281 # We don't want to include fragments for broken links, because they
282 # generally make no sense.
283 if ( in_array( 'broken', $options ) && $target->hasFragment() ) {
284 $target = clone $target;
285 $target->setFragment( '' );
288 # If it's a broken link, add the appropriate query pieces, unless
289 # there's already an action specified, or unless 'edit' makes no sense
290 # (i.e., for a nonexistent special page).
291 if ( in_array( 'broken', $options ) && empty( $query['action'] )
292 && !$target->isSpecialPage() ) {
293 $query['action'] = 'edit';
294 $query['redlink'] = '1';
297 if ( in_array( 'http', $options ) ) {
298 $proto = PROTO_HTTP;
299 } elseif ( in_array( 'https', $options ) ) {
300 $proto = PROTO_HTTPS;
301 } else {
302 $proto = PROTO_RELATIVE;
305 $ret = $target->getLinkURL( $query, false, $proto );
306 wfProfileOut( __METHOD__ );
307 return $ret;
311 * Returns the array of attributes used when linking to the Title $target
313 * @param Title $target
314 * @param array $attribs
315 * @param array $options
317 * @return array
319 private static function linkAttribs( $target, $attribs, $options ) {
320 wfProfileIn( __METHOD__ );
321 global $wgUser;
322 $defaults = array();
324 if ( !in_array( 'noclasses', $options ) ) {
325 wfProfileIn( __METHOD__ . '-getClasses' );
326 # Now build the classes.
327 $classes = array();
329 if ( in_array( 'broken', $options ) ) {
330 $classes[] = 'new';
333 if ( $target->isExternal() ) {
334 $classes[] = 'extiw';
337 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
338 $colour = self::getLinkColour( $target, $wgUser->getStubThreshold() );
339 if ( $colour !== '' ) {
340 $classes[] = $colour; # mw-redirect or stub
343 if ( $classes != array() ) {
344 $defaults['class'] = implode( ' ', $classes );
346 wfProfileOut( __METHOD__ . '-getClasses' );
349 # Get a default title attribute.
350 if ( $target->getPrefixedText() == '' ) {
351 # A link like [[#Foo]]. This used to mean an empty title
352 # attribute, but that's silly. Just don't output a title.
353 } elseif ( in_array( 'known', $options ) ) {
354 $defaults['title'] = $target->getPrefixedText();
355 } else {
356 $defaults['title'] = wfMessage( 'red-link-title', $target->getPrefixedText() )->text();
359 # Finally, merge the custom attribs with the default ones, and iterate
360 # over that, deleting all "false" attributes.
361 $ret = array();
362 $merged = Sanitizer::mergeAttributes( $defaults, $attribs );
363 foreach ( $merged as $key => $val ) {
364 # A false value suppresses the attribute, and we don't want the
365 # href attribute to be overridden.
366 if ( $key != 'href' and $val !== false ) {
367 $ret[$key] = $val;
370 wfProfileOut( __METHOD__ );
371 return $ret;
375 * Default text of the links to the Title $target
377 * @param Title $target
379 * @return string
381 private static function linkText( $target ) {
382 // We might be passed a non-Title by make*LinkObj(). Fail gracefully.
383 if ( !$target instanceof Title ) {
384 return '';
387 // If the target is just a fragment, with no title, we return the fragment
388 // text. Otherwise, we return the title text itself.
389 if ( $target->getPrefixedText() === '' && $target->hasFragment() ) {
390 return htmlspecialchars( $target->getFragment() );
393 return htmlspecialchars( $target->getPrefixedText() );
397 * Make appropriate markup for a link to the current article. This is
398 * currently rendered as the bold link text. The calling sequence is the
399 * same as the other make*LinkObj static functions, despite $query not
400 * being used.
402 * @param Title $nt
403 * @param string $html [optional]
404 * @param string $query [optional]
405 * @param string $trail [optional]
406 * @param string $prefix [optional]
408 * @return string
410 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
411 if ( $html == '' ) {
412 $html = htmlspecialchars( $nt->getPrefixedText() );
414 list( $inside, $trail ) = self::splitTrail( $trail );
415 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
419 * Get a message saying that an invalid title was encountered.
420 * This should be called after a method like Title::makeTitleSafe() returned
421 * a value indicating that the title object is invalid.
423 * @param IContextSource $context Context to use to get the messages
424 * @param int $namespace Namespace number
425 * @param string $title Text of the title, without the namespace part
426 * @return string
428 public static function getInvalidTitleDescription( IContextSource $context, $namespace, $title ) {
429 global $wgContLang;
431 // First we check whether the namespace exists or not.
432 if ( MWNamespace::exists( $namespace ) ) {
433 if ( $namespace == NS_MAIN ) {
434 $name = $context->msg( 'blanknamespace' )->text();
435 } else {
436 $name = $wgContLang->getFormattedNsText( $namespace );
438 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
439 } else {
440 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
445 * @param Title $title
446 * @return Title
448 static function normaliseSpecialPage( Title $title ) {
449 if ( $title->isSpecialPage() ) {
450 list( $name, $subpage ) = SpecialPageFactory::resolveAlias( $title->getDBkey() );
451 if ( !$name ) {
452 return $title;
454 $ret = SpecialPage::getTitleFor( $name, $subpage, $title->getFragment() );
455 return $ret;
456 } else {
457 return $title;
462 * Returns the filename part of an url.
463 * Used as alternative text for external images.
465 * @param string $url
467 * @return string
469 private static function fnamePart( $url ) {
470 $basename = strrchr( $url, '/' );
471 if ( false === $basename ) {
472 $basename = $url;
473 } else {
474 $basename = substr( $basename, 1 );
476 return $basename;
480 * Return the code for images which were added via external links,
481 * via Parser::maybeMakeExternalImage().
483 * @param string $url
484 * @param string $alt
486 * @return string
488 public static function makeExternalImage( $url, $alt = '' ) {
489 if ( $alt == '' ) {
490 $alt = self::fnamePart( $url );
492 $img = '';
493 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
494 if ( !$success ) {
495 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
496 . "with url {$url} and alt text {$alt} to {$img}\n", true );
497 return $img;
499 return Html::element( 'img',
500 array(
501 'src' => $url,
502 'alt' => $alt ) );
506 * Given parameters derived from [[Image:Foo|options...]], generate the
507 * HTML that that syntax inserts in the page.
509 * @param Parser $parser
510 * @param Title $title Title object of the file (not the currently viewed page)
511 * @param File $file File object, or false if it doesn't exist
512 * @param array $frameParams Associative array of parameters external to the media handler.
513 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
514 * will often be false.
515 * thumbnail If present, downscale and frame
516 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
517 * framed Shows image in original size in a frame
518 * frameless Downscale but don't frame
519 * upright If present, tweak default sizes for portrait orientation
520 * upright_factor Fudge factor for "upright" tweak (default 0.75)
521 * border If present, show a border around the image
522 * align Horizontal alignment (left, right, center, none)
523 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
524 * bottom, text-bottom)
525 * alt Alternate text for image (i.e. alt attribute). Plain text.
526 * class HTML for image classes. Plain text.
527 * caption HTML for image caption.
528 * link-url URL to link to
529 * link-title Title object to link to
530 * link-target Value for the target attribute, only with link-url
531 * no-link Boolean, suppress description link
533 * @param array $handlerParams Associative array of media handler parameters, to be passed
534 * to transform(). Typical keys are "width" and "page".
535 * @param string|bool $time Timestamp of the file, set as false for current
536 * @param string $query Query params for desc url
537 * @param int|null $widthOption Used by the parser to remember the user preference thumbnailsize
538 * @since 1.20
539 * @return string HTML for an image, with links, wrappers, etc.
541 public static function makeImageLink( /*Parser*/ $parser, Title $title,
542 $file, $frameParams = array(), $handlerParams = array(), $time = false,
543 $query = "", $widthOption = null
545 $res = null;
546 $dummy = new DummyLinker;
547 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
548 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
549 return $res;
552 if ( $file && !$file->allowInlineDisplay() ) {
553 wfDebug( __METHOD__ . ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
554 return self::link( $title );
557 // Shortcuts
558 $fp =& $frameParams;
559 $hp =& $handlerParams;
561 // Clean up parameters
562 $page = isset( $hp['page'] ) ? $hp['page'] : false;
563 if ( !isset( $fp['align'] ) ) {
564 $fp['align'] = '';
566 if ( !isset( $fp['alt'] ) ) {
567 $fp['alt'] = '';
569 if ( !isset( $fp['title'] ) ) {
570 $fp['title'] = '';
572 if ( !isset( $fp['class'] ) ) {
573 $fp['class'] = '';
576 $prefix = $postfix = '';
578 if ( 'center' == $fp['align'] ) {
579 $prefix = '<div class="center">';
580 $postfix = '</div>';
581 $fp['align'] = 'none';
583 if ( $file && !isset( $hp['width'] ) ) {
584 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
585 // If its a vector image, and user only specifies height
586 // we don't want it to be limited by its "normal" width.
587 global $wgSVGMaxSize;
588 $hp['width'] = $wgSVGMaxSize;
589 } else {
590 $hp['width'] = $file->getWidth( $page );
593 if ( isset( $fp['thumbnail'] )
594 || isset( $fp['manualthumb'] )
595 || isset( $fp['framed'] )
596 || isset( $fp['frameless'] )
597 || !$hp['width']
599 global $wgThumbLimits, $wgThumbUpright;
601 if ( $widthOption === null || !isset( $wgThumbLimits[$widthOption] ) ) {
602 $widthOption = User::getDefaultOption( 'thumbsize' );
605 // Reduce width for upright images when parameter 'upright' is used
606 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
607 $fp['upright'] = $wgThumbUpright;
610 // For caching health: If width scaled down due to upright
611 // parameter, round to full __0 pixel to avoid the creation of a
612 // lot of odd thumbs.
613 $prefWidth = isset( $fp['upright'] ) ?
614 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
615 $wgThumbLimits[$widthOption];
617 // Use width which is smaller: real image width or user preference width
618 // Unless image is scalable vector.
619 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
620 $prefWidth < $hp['width'] || $file->isVectorized() ) ) {
621 $hp['width'] = $prefWidth;
626 if ( isset( $fp['thumbnail'] ) || isset( $fp['manualthumb'] ) || isset( $fp['framed'] ) ) {
627 # Create a thumbnail. Alignment depends on the writing direction of
628 # the page content language (right-aligned for LTR languages,
629 # left-aligned for RTL languages)
631 # If a thumbnail width has not been provided, it is set
632 # to the default user option as specified in Language*.php
633 if ( $fp['align'] == '' ) {
634 if ( $parser instanceof Parser ) {
635 $fp['align'] = $parser->getTargetLanguage()->alignEnd();
636 } else {
637 # backwards compatibility, remove with makeImageLink2()
638 global $wgContLang;
639 $fp['align'] = $wgContLang->alignEnd();
642 return $prefix . self::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
645 if ( $file && isset( $fp['frameless'] ) ) {
646 $srcWidth = $file->getWidth( $page );
647 # For "frameless" option: do not present an image bigger than the
648 # source (for bitmap-style images). This is the same behavior as the
649 # "thumb" option does it already.
650 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
651 $hp['width'] = $srcWidth;
655 if ( $file && isset( $hp['width'] ) ) {
656 # Create a resized image, without the additional thumbnail features
657 $thumb = $file->transform( $hp );
658 } else {
659 $thumb = false;
662 if ( !$thumb ) {
663 $s = self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
664 } else {
665 self::processResponsiveImages( $file, $thumb, $hp );
666 $params = array(
667 'alt' => $fp['alt'],
668 'title' => $fp['title'],
669 'valign' => isset( $fp['valign'] ) ? $fp['valign'] : false,
670 'img-class' => $fp['class'] );
671 if ( isset( $fp['border'] ) ) {
672 $params['img-class'] .= ( $params['img-class'] !== '' ? ' ' : '' ) . 'thumbborder';
674 $params = self::getImageLinkMTOParams( $fp, $query, $parser ) + $params;
676 $s = $thumb->toHtml( $params );
678 if ( $fp['align'] != '' ) {
679 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
681 return str_replace( "\n", ' ', $prefix . $s . $postfix );
685 * See makeImageLink()
686 * When this function is removed, remove if( $parser instanceof Parser ) check there too
687 * @deprecated since 1.20
689 public static function makeImageLink2( Title $title, $file, $frameParams = array(),
690 $handlerParams = array(), $time = false, $query = "", $widthOption = null ) {
691 return self::makeImageLink( null, $title, $file, $frameParams,
692 $handlerParams, $time, $query, $widthOption );
696 * Get the link parameters for MediaTransformOutput::toHtml() from given
697 * frame parameters supplied by the Parser.
698 * @param array $frameParams The frame parameters
699 * @param string $query An optional query string to add to description page links
700 * @return array
702 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
703 $mtoParams = array();
704 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
705 $mtoParams['custom-url-link'] = $frameParams['link-url'];
706 if ( isset( $frameParams['link-target'] ) ) {
707 $mtoParams['custom-target-link'] = $frameParams['link-target'];
709 if ( $parser ) {
710 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
711 foreach ( $extLinkAttrs as $name => $val ) {
712 // Currently could include 'rel' and 'target'
713 $mtoParams['parser-extlink-' . $name] = $val;
716 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
717 $mtoParams['custom-title-link'] = self::normaliseSpecialPage( $frameParams['link-title'] );
718 } elseif ( !empty( $frameParams['no-link'] ) ) {
719 // No link
720 } else {
721 $mtoParams['desc-link'] = true;
722 $mtoParams['desc-query'] = $query;
724 return $mtoParams;
728 * Make HTML for a thumbnail including image, border and caption
729 * @param Title $title
730 * @param File|bool $file File object or false if it doesn't exist
731 * @param string $label
732 * @param string $alt
733 * @param string $align
734 * @param array $params
735 * @param bool $framed
736 * @param string $manualthumb
737 * @return string
739 public static function makeThumbLinkObj( Title $title, $file, $label = '', $alt,
740 $align = 'right', $params = array(), $framed = false, $manualthumb = ""
742 $frameParams = array(
743 'alt' => $alt,
744 'caption' => $label,
745 'align' => $align
747 if ( $framed ) {
748 $frameParams['framed'] = true;
750 if ( $manualthumb ) {
751 $frameParams['manualthumb'] = $manualthumb;
753 return self::makeThumbLink2( $title, $file, $frameParams, $params );
757 * @param Title $title
758 * @param File $file
759 * @param array $frameParams
760 * @param array $handlerParams
761 * @param bool $time
762 * @param string $query
763 * @return string
765 public static function makeThumbLink2( Title $title, $file, $frameParams = array(),
766 $handlerParams = array(), $time = false, $query = ""
768 global $wgStylePath, $wgContLang;
769 $exists = $file && $file->exists();
771 # Shortcuts
772 $fp =& $frameParams;
773 $hp =& $handlerParams;
775 $page = isset( $hp['page'] ) ? $hp['page'] : false;
776 if ( !isset( $fp['align'] ) ) {
777 $fp['align'] = 'right';
779 if ( !isset( $fp['alt'] ) ) {
780 $fp['alt'] = '';
782 if ( !isset( $fp['title'] ) ) {
783 $fp['title'] = '';
785 if ( !isset( $fp['caption'] ) ) {
786 $fp['caption'] = '';
789 if ( empty( $hp['width'] ) ) {
790 // Reduce width for upright images when parameter 'upright' is used
791 $hp['width'] = isset( $fp['upright'] ) ? 130 : 180;
793 $thumb = false;
794 $noscale = false;
795 $manualthumb = false;
797 if ( !$exists ) {
798 $outerWidth = $hp['width'] + 2;
799 } else {
800 if ( isset( $fp['manualthumb'] ) ) {
801 # Use manually specified thumbnail
802 $manual_title = Title::makeTitleSafe( NS_FILE, $fp['manualthumb'] );
803 if ( $manual_title ) {
804 $manual_img = wfFindFile( $manual_title );
805 if ( $manual_img ) {
806 $thumb = $manual_img->getUnscaledThumb( $hp );
807 $manualthumb = true;
808 } else {
809 $exists = false;
812 } elseif ( isset( $fp['framed'] ) ) {
813 // Use image dimensions, don't scale
814 $thumb = $file->getUnscaledThumb( $hp );
815 $noscale = true;
816 } else {
817 # Do not present an image bigger than the source, for bitmap-style images
818 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
819 $srcWidth = $file->getWidth( $page );
820 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
821 $hp['width'] = $srcWidth;
823 $thumb = $file->transform( $hp );
826 if ( $thumb ) {
827 $outerWidth = $thumb->getWidth() + 2;
828 } else {
829 $outerWidth = $hp['width'] + 2;
833 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
834 # So we don't need to pass it here in $query. However, the URL for the
835 # zoom icon still needs it, so we make a unique query for it. See bug 14771
836 $url = $title->getLocalURL( $query );
837 if ( $page ) {
838 $url = wfAppendQuery( $url, array( 'page' => $page ) );
840 if ( $manualthumb
841 && !isset( $fp['link-title'] )
842 && !isset( $fp['link-url'] )
843 && !isset( $fp['no-link'] ) ) {
844 $fp['link-url'] = $url;
847 $s = "<div class=\"thumb t{$fp['align']}\">"
848 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
850 if ( !$exists ) {
851 $s .= self::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
852 $zoomIcon = '';
853 } elseif ( !$thumb ) {
854 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
855 $zoomIcon = '';
856 } else {
857 if ( !$noscale && !$manualthumb ) {
858 self::processResponsiveImages( $file, $thumb, $hp );
860 $params = array(
861 'alt' => $fp['alt'],
862 'title' => $fp['title'],
863 'img-class' => ( isset( $fp['class'] ) && $fp['class'] !== ''
864 ? $fp['class'] . ' '
865 : '' ) . 'thumbimage'
867 $params = self::getImageLinkMTOParams( $fp, $query ) + $params;
868 $s .= $thumb->toHtml( $params );
869 if ( isset( $fp['framed'] ) ) {
870 $zoomIcon = "";
871 } else {
872 $zoomIcon = Html::rawElement( 'div', array( 'class' => 'magnify' ),
873 Html::rawElement( 'a', array(
874 'href' => $url,
875 'class' => 'internal',
876 'title' => wfMessage( 'thumbnail-more' )->text() ),
877 Html::element( 'img', array(
878 'src' => $wgStylePath . '/common/images/magnify-clip'
879 . ( $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 MediaTransformOutput $thumb
895 * @param array $hp Image parameters
897 public 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 && $thumb15->getUrl() !== $thumb->getUrl() ) {
912 $thumb->responsiveUrls['1.5'] = $thumb15->getUrl();
914 if ( $thumb20 && $thumb20->getUrl() !== $thumb->getUrl() ) {
915 $thumb->responsiveUrls['2'] = $thumb20->getUrl();
921 * Make a "broken" link to an image
923 * @param Title $title
924 * @param string $label Link label (plain text)
925 * @param string $query Query string
926 * @param string $unused1 Unused parameter kept for b/c
927 * @param string $unused2 Unused parameter kept for b/c
928 * @param bool $time A file of a certain timestamp was requested
929 * @return string
931 public static function makeBrokenImageLinkObj( $title, $label = '',
932 $query = '', $unused1 = '', $unused2 = '', $time = false
934 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
935 if ( ! $title instanceof Title ) {
936 return "<!-- ERROR -->" . htmlspecialchars( $label );
938 wfProfileIn( __METHOD__ );
939 if ( $label == '' ) {
940 $label = $title->getPrefixedText();
942 $encLabel = htmlspecialchars( $label );
943 $currentExists = $time ? ( wfFindFile( $title ) != false ) : false;
945 if ( ( $wgUploadMissingFileUrl || $wgUploadNavigationUrl || $wgEnableUploads )
946 && !$currentExists
948 $redir = RepoGroup::singleton()->getLocalRepo()->checkRedirect( $title );
950 if ( $redir ) {
951 wfProfileOut( __METHOD__ );
952 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
955 $href = self::getUploadUrl( $title, $query );
957 wfProfileOut( __METHOD__ );
958 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
959 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES ) . '">' .
960 $encLabel . '</a>';
963 wfProfileOut( __METHOD__ );
964 return self::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
968 * Get the URL to upload a certain file
970 * @param Title $destFile Title object of the file to upload
971 * @param string $query Urlencoded query string to prepend
972 * @return string Urlencoded URL
974 protected static function getUploadUrl( $destFile, $query = '' ) {
975 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
976 $q = 'wpDestFile=' . $destFile->getPartialURL();
977 if ( $query != '' ) {
978 $q .= '&' . $query;
981 if ( $wgUploadMissingFileUrl ) {
982 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
983 } elseif ( $wgUploadNavigationUrl ) {
984 return wfAppendQuery( $wgUploadNavigationUrl, $q );
985 } else {
986 $upload = SpecialPage::getTitleFor( 'Upload' );
987 return $upload->getLocalURL( $q );
992 * Create a direct link to a given uploaded file.
994 * @param Title $title
995 * @param string $html Pre-sanitized HTML
996 * @param string $time MW timestamp of file creation time
997 * @return string HTML
999 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
1000 $img = wfFindFile( $title, array( 'time' => $time ) );
1001 return self::makeMediaLinkFile( $title, $img, $html );
1005 * Create a direct link to a given uploaded file.
1006 * This will make a broken link if $file is false.
1008 * @param Title $title
1009 * @param File|bool $file File object or false
1010 * @param string $html Pre-sanitized HTML
1011 * @return string HTML
1013 * @todo Handle invalid or missing images better.
1015 public static function makeMediaLinkFile( Title $title, $file, $html = '' ) {
1016 if ( $file && $file->exists() ) {
1017 $url = $file->getURL();
1018 $class = 'internal';
1019 } else {
1020 $url = self::getUploadUrl( $title );
1021 $class = 'new';
1024 $alt = $title->getText();
1025 if ( $html == '' ) {
1026 $html = $alt;
1029 $ret = '';
1030 $attribs = array(
1031 'href' => $url,
1032 'class' => $class,
1033 'title' => $alt
1036 if ( !wfRunHooks( 'LinkerMakeMediaLinkFile',
1037 array( $title, $file, &$html, &$attribs, &$ret ) ) ) {
1038 wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
1039 . "with url {$url} and text {$html} to {$ret}\n", true );
1040 return $ret;
1043 return Html::rawElement( 'a', $attribs, $html );
1047 * Make a link to a special page given its name and, optionally,
1048 * a message key from the link text.
1049 * Usage example: Linker::specialLink( 'Recentchanges' )
1051 * @param string $name
1052 * @param string $key
1053 * @return string
1055 public static function specialLink( $name, $key = '' ) {
1056 if ( $key == '' ) {
1057 $key = strtolower( $name );
1060 return self::linkKnown( SpecialPage::getTitleFor( $name ), wfMessage( $key )->text() );
1064 * Make an external link
1065 * @param string $url URL to link to
1066 * @param string $text Text of link
1067 * @param bool $escape Do we escape the link text?
1068 * @param string $linktype Type of external link. Gets added to the classes
1069 * @param array $attribs Array of extra attributes to <a>
1070 * @param Title|null $title Title object used for title specific link attributes
1071 * @return string
1073 public static function makeExternalLink( $url, $text, $escape = true,
1074 $linktype = '', $attribs = array(), $title = null
1076 global $wgTitle;
1077 $class = "external";
1078 if ( $linktype ) {
1079 $class .= " $linktype";
1081 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1082 $class .= " {$attribs['class']}";
1084 $attribs['class'] = $class;
1086 if ( $escape ) {
1087 $text = htmlspecialchars( $text );
1090 if ( !$title ) {
1091 $title = $wgTitle;
1093 $attribs['rel'] = Parser::getExternalLinkRel( $url, $title );
1094 $link = '';
1095 $success = wfRunHooks( 'LinkerMakeExternalLink',
1096 array( &$url, &$text, &$link, &$attribs, $linktype ) );
1097 if ( !$success ) {
1098 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
1099 . "with url {$url} and text {$text} to {$link}\n", true );
1100 return $link;
1102 $attribs['href'] = $url;
1103 return Html::rawElement( 'a', $attribs, $text );
1107 * Make user link (or user contributions for unregistered users)
1108 * @param int $userId User id in database.
1109 * @param string $userName User name in database.
1110 * @param string $altUserName Text to display instead of the user name (optional)
1111 * @return string HTML fragment
1112 * @since 1.19 Method exists for a long time. $altUserName was added in 1.19.
1114 public static function userLink( $userId, $userName, $altUserName = false ) {
1115 $classes = 'mw-userlink';
1116 if ( $userId == 0 ) {
1117 $page = SpecialPage::getTitleFor( 'Contributions', $userName );
1118 if ( $altUserName === false ) {
1119 $altUserName = IP::prettifyIP( $userName );
1121 $classes .= ' mw-anonuserlink'; // Separate link class for anons (bug 43179)
1122 } else {
1123 $page = Title::makeTitle( NS_USER, $userName );
1126 return self::link(
1127 $page,
1128 htmlspecialchars( $altUserName !== false ? $altUserName : $userName ),
1129 array( 'class' => $classes )
1134 * Generate standard user tool links (talk, contributions, block link, etc.)
1136 * @param int $userId User identifier
1137 * @param string $userText User name or IP address
1138 * @param bool $redContribsWhenNoEdits Should the contributions link be
1139 * red if the user has no edits?
1140 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
1141 * and Linker::TOOL_LINKS_EMAIL).
1142 * @param int $edits User edit count (optional, for performance)
1143 * @return string HTML fragment
1145 public static function userToolLinks(
1146 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1148 global $wgUser, $wgDisableAnonTalk, $wgLang;
1149 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1150 $blockable = !( $flags & self::TOOL_LINKS_NOBLOCK );
1151 $addEmailLink = $flags & self::TOOL_LINKS_EMAIL && $userId;
1153 $items = array();
1154 if ( $talkable ) {
1155 $items[] = self::userTalkLink( $userId, $userText );
1157 if ( $userId ) {
1158 // check if the user has an edit
1159 $attribs = array();
1160 if ( $redContribsWhenNoEdits ) {
1161 if ( intval( $edits ) === 0 && $edits !== 0 ) {
1162 $user = User::newFromId( $userId );
1163 $edits = $user->getEditCount();
1165 if ( $edits === 0 ) {
1166 $attribs['class'] = 'new';
1169 $contribsPage = SpecialPage::getTitleFor( 'Contributions', $userText );
1171 $items[] = self::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1173 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1174 $items[] = self::blockLink( $userId, $userText );
1177 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1178 $items[] = self::emailLink( $userId, $userText );
1181 wfRunHooks( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1183 if ( $items ) {
1184 return wfMessage( 'word-separator' )->plain()
1185 . '<span class="mw-usertoollinks">'
1186 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1187 . '</span>';
1188 } else {
1189 return '';
1194 * Alias for userToolLinks( $userId, $userText, true );
1195 * @param int $userId User identifier
1196 * @param string $userText User name or IP address
1197 * @param int $edits User edit count (optional, for performance)
1198 * @return string
1200 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1201 return self::userToolLinks( $userId, $userText, true, 0, $edits );
1205 * @param int $userId User id in database.
1206 * @param string $userText User name in database.
1207 * @return string HTML fragment with user talk link
1209 public static function userTalkLink( $userId, $userText ) {
1210 $userTalkPage = Title::makeTitle( NS_USER_TALK, $userText );
1211 $userTalkLink = self::link( $userTalkPage, wfMessage( 'talkpagelinktext' )->escaped() );
1212 return $userTalkLink;
1216 * @param int $userId Userid
1217 * @param string $userText User name in database.
1218 * @return string HTML fragment with block link
1220 public static function blockLink( $userId, $userText ) {
1221 $blockPage = SpecialPage::getTitleFor( 'Block', $userText );
1222 $blockLink = self::link( $blockPage, wfMessage( 'blocklink' )->escaped() );
1223 return $blockLink;
1227 * @param int $userId Userid
1228 * @param string $userText User name in database.
1229 * @return string HTML fragment with e-mail user link
1231 public static function emailLink( $userId, $userText ) {
1232 $emailPage = SpecialPage::getTitleFor( 'Emailuser', $userText );
1233 $emailLink = self::link( $emailPage, wfMessage( 'emaillink' )->escaped() );
1234 return $emailLink;
1238 * Generate a user link if the current user is allowed to view it
1239 * @param Revision $rev
1240 * @param bool $isPublic Show only if all users can see it
1241 * @return string HTML fragment
1243 public static function revUserLink( $rev, $isPublic = false ) {
1244 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1245 $link = wfMessage( 'rev-deleted-user' )->escaped();
1246 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1247 $link = self::userLink( $rev->getUser( Revision::FOR_THIS_USER ),
1248 $rev->getUserText( Revision::FOR_THIS_USER ) );
1249 } else {
1250 $link = wfMessage( 'rev-deleted-user' )->escaped();
1252 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1253 return '<span class="history-deleted">' . $link . '</span>';
1255 return $link;
1259 * Generate a user tool link cluster if the current user is allowed to view it
1260 * @param Revision $rev
1261 * @param bool $isPublic Show only if all users can see it
1262 * @return string HTML
1264 public static function revUserTools( $rev, $isPublic = false ) {
1265 if ( $rev->isDeleted( Revision::DELETED_USER ) && $isPublic ) {
1266 $link = wfMessage( 'rev-deleted-user' )->escaped();
1267 } elseif ( $rev->userCan( Revision::DELETED_USER ) ) {
1268 $userId = $rev->getUser( Revision::FOR_THIS_USER );
1269 $userText = $rev->getUserText( Revision::FOR_THIS_USER );
1270 $link = self::userLink( $userId, $userText )
1271 . wfMessage( 'word-separator' )->plain()
1272 . self::userToolLinks( $userId, $userText );
1273 } else {
1274 $link = wfMessage( 'rev-deleted-user' )->escaped();
1276 if ( $rev->isDeleted( Revision::DELETED_USER ) ) {
1277 return ' <span class="history-deleted">' . $link . '</span>';
1279 return $link;
1283 * This function is called by all recent changes variants, by the page history,
1284 * and by the user contributions list. It is responsible for formatting edit
1285 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1286 * auto-generated comments (from section editing) and formats [[wikilinks]].
1288 * @author Erik Moeller <moeller@scireview.de>
1290 * Note: there's not always a title to pass to this function.
1291 * Since you can't set a default parameter for a reference, I've turned it
1292 * temporarily to a value pass. Should be adjusted further. --brion
1294 * @param string $comment
1295 * @param Title|null $title Title object (to generate link to the section in autocomment) or null
1296 * @param bool $local Whether section links should refer to local page
1297 * @return mixed|string
1299 public static function formatComment( $comment, $title = null, $local = false ) {
1300 wfProfileIn( __METHOD__ );
1302 # Sanitize text a bit:
1303 $comment = str_replace( "\n", " ", $comment );
1304 # Allow HTML entities (for bug 13815)
1305 $comment = Sanitizer::escapeHtmlAllowEntities( $comment );
1307 # Render autocomments and make links:
1308 $comment = self::formatAutocomments( $comment, $title, $local );
1309 $comment = self::formatLinksInComment( $comment, $title, $local );
1311 wfProfileOut( __METHOD__ );
1312 return $comment;
1315 /** @var Title */
1316 private static $autocommentTitle;
1318 /** @var bool Whether section links should refer to local page */
1319 private static $autocommentLocal;
1322 * Converts autogenerated comments in edit summaries into section links.
1323 * The pattern for autogen comments is / * foo * /, which makes for
1324 * some nasty regex.
1325 * We look for all comments, match any text before and after the comment,
1326 * add a separator where needed and format the comment itself with CSS
1327 * Called by Linker::formatComment.
1329 * @param string $comment Comment text
1330 * @param Title|null $title An optional title object used to links to sections
1331 * @param bool $local Whether section links should refer to local page
1332 * @return string Formatted comment
1334 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1335 // Bah!
1336 self::$autocommentTitle = $title;
1337 self::$autocommentLocal = $local;
1338 $comment = preg_replace_callback(
1339 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1340 array( 'Linker', 'formatAutocommentsCallback' ),
1341 $comment );
1342 self::$autocommentTitle = null;
1343 self::$autocommentLocal = null;
1344 return $comment;
1348 * Helper function for Linker::formatAutocomments
1349 * @param array $match
1350 * @return string
1352 private static function formatAutocommentsCallback( $match ) {
1353 global $wgLang;
1354 $title = self::$autocommentTitle;
1355 $local = self::$autocommentLocal;
1357 $pre = $match[1];
1358 $auto = $match[2];
1359 $post = $match[3];
1360 $comment = null;
1361 wfRunHooks( 'FormatAutocomments', array( &$comment, $pre, $auto, $post, $title, $local ) );
1362 if ( $comment === null ) {
1363 $link = '';
1364 if ( $title ) {
1365 $section = $auto;
1367 # Remove links that a user may have manually put in the autosummary
1368 # This could be improved by copying as much of Parser::stripSectionName as desired.
1369 $section = str_replace( '[[:', '', $section );
1370 $section = str_replace( '[[', '', $section );
1371 $section = str_replace( ']]', '', $section );
1373 $section = Sanitizer::normalizeSectionNameWhitespace( $section ); # bug 22784
1374 if ( $local ) {
1375 $sectionTitle = Title::newFromText( '#' . $section );
1376 } else {
1377 $sectionTitle = Title::makeTitleSafe( $title->getNamespace(),
1378 $title->getDBkey(), $section );
1380 if ( $sectionTitle ) {
1381 $link = self::link( $sectionTitle,
1382 $wgLang->getArrow(), array(), array(),
1383 'noclasses' );
1384 } else {
1385 $link = '';
1388 if ( $pre ) {
1389 # written summary $presep autocomment (summary /* section */)
1390 $pre .= wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1392 if ( $post ) {
1393 # autocomment $postsep written summary (/* section */ summary)
1394 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1396 $auto = '<span class="autocomment">' . $auto . '</span>';
1397 $comment = $pre . $link . $wgLang->getDirMark()
1398 . '<span dir="auto">' . $auto . $post . '</span>';
1400 return $comment;
1403 /** @var Title */
1404 private static $commentContextTitle;
1406 /** @var bool Whether section links should refer to local page */
1407 private static $commentLocal;
1410 * Formats wiki links and media links in text; all other wiki formatting
1411 * is ignored
1413 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1414 * @param string $comment Text to format links in
1415 * @param Title|null $title An optional title object used to links to sections
1416 * @param bool $local Whether section links should refer to local page
1417 * @return string
1419 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1420 self::$commentContextTitle = $title;
1421 self::$commentLocal = $local;
1422 $html = preg_replace_callback(
1424 \[\[
1425 :? # ignore optional leading colon
1426 ([^\]|]+) # 1. link target; page names cannot include ] or |
1427 (?:\|
1428 # 2. a pipe-separated substring; only the last is captured
1429 # Stop matching at | and ]] without relying on backtracking.
1430 ((?:]?[^\]|])*+)
1432 \]\]
1433 ([^[]*) # 3. link trail (the text up until the next link)
1434 /x',
1435 array( 'Linker', 'formatLinksInCommentCallback' ),
1436 $comment );
1437 self::$commentContextTitle = null;
1438 self::$commentLocal = null;
1439 return $html;
1443 * @param array $match
1444 * @return mixed
1446 protected static function formatLinksInCommentCallback( $match ) {
1447 global $wgContLang;
1449 $medians = '(?:' . preg_quote( MWNamespace::getCanonicalName( NS_MEDIA ), '/' ) . '|';
1450 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA ), '/' ) . '):';
1452 $comment = $match[0];
1454 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1455 if ( strpos( $match[1], '%' ) !== false ) {
1456 $match[1] = str_replace( array( '<', '>' ), array( '&lt;', '&gt;' ), rawurldecode( $match[1] ) );
1459 # Handle link renaming [[foo|text]] will show link as "text"
1460 if ( $match[2] != "" ) {
1461 $text = $match[2];
1462 } else {
1463 $text = $match[1];
1465 $submatch = array();
1466 $thelink = null;
1467 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1468 # Media link; trail not supported.
1469 $linkRegexp = '/\[\[(.*?)\]\]/';
1470 $title = Title::makeTitleSafe( NS_FILE, $submatch[1] );
1471 if ( $title ) {
1472 $thelink = self::makeMediaLinkObj( $title, $text );
1474 } else {
1475 # Other kind of link
1476 if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1477 $trail = $submatch[1];
1478 } else {
1479 $trail = "";
1481 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1482 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1483 $match[1] = substr( $match[1], 1 );
1485 list( $inside, $trail ) = self::splitTrail( $trail );
1487 $linkText = $text;
1488 $linkTarget = self::normalizeSubpageLink( self::$commentContextTitle,
1489 $match[1], $linkText );
1491 $target = Title::newFromText( $linkTarget );
1492 if ( $target ) {
1493 if ( $target->getText() == '' && !$target->isExternal()
1494 && !self::$commentLocal && self::$commentContextTitle
1496 $newTarget = clone ( self::$commentContextTitle );
1497 $newTarget->setFragment( '#' . $target->getFragment() );
1498 $target = $newTarget;
1500 $thelink = self::link(
1501 $target,
1502 $linkText . $inside
1503 ) . $trail;
1506 if ( $thelink ) {
1507 // If the link is still valid, go ahead and replace it in!
1508 $comment = preg_replace(
1509 $linkRegexp,
1510 StringUtils::escapeRegexReplacement( $thelink ),
1511 $comment,
1516 return $comment;
1520 * @param Title $contextTitle
1521 * @param string $target
1522 * @param string $text
1523 * @return string
1525 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1526 # Valid link forms:
1527 # Foobar -- normal
1528 # :Foobar -- override special treatment of prefix (images, language links)
1529 # /Foobar -- convert to CurrentPage/Foobar
1530 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1531 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1532 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1534 wfProfileIn( __METHOD__ );
1535 $ret = $target; # default return value is no change
1537 # Some namespaces don't allow subpages,
1538 # so only perform processing if subpages are allowed
1539 if ( $contextTitle && MWNamespace::hasSubpages( $contextTitle->getNamespace() ) ) {
1540 $hash = strpos( $target, '#' );
1541 if ( $hash !== false ) {
1542 $suffix = substr( $target, $hash );
1543 $target = substr( $target, 0, $hash );
1544 } else {
1545 $suffix = '';
1547 # bug 7425
1548 $target = trim( $target );
1549 # Look at the first character
1550 if ( $target != '' && $target[0] === '/' ) {
1551 # / at end means we don't want the slash to be shown
1552 $m = array();
1553 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1554 if ( $trailingSlashes ) {
1555 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1556 } else {
1557 $noslash = substr( $target, 1 );
1560 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1561 if ( $text === '' ) {
1562 $text = $target . $suffix;
1563 } # this might be changed for ugliness reasons
1564 } else {
1565 # check for .. subpage backlinks
1566 $dotdotcount = 0;
1567 $nodotdot = $target;
1568 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1569 ++$dotdotcount;
1570 $nodotdot = substr( $nodotdot, 3 );
1572 if ( $dotdotcount > 0 ) {
1573 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1574 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1575 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1576 # / at the end means don't show full path
1577 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1578 $nodotdot = substr( $nodotdot, 0, -1 );
1579 if ( $text === '' ) {
1580 $text = $nodotdot . $suffix;
1583 $nodotdot = trim( $nodotdot );
1584 if ( $nodotdot != '' ) {
1585 $ret .= '/' . $nodotdot;
1587 $ret .= $suffix;
1593 wfProfileOut( __METHOD__ );
1594 return $ret;
1598 * Wrap a comment in standard punctuation and formatting if
1599 * it's non-empty, otherwise return empty string.
1601 * @param string $comment
1602 * @param Title|null $title Title object (to generate link to section in autocomment) or null
1603 * @param bool $local Whether section links should refer to local page
1605 * @return string
1607 public static function commentBlock( $comment, $title = null, $local = false ) {
1608 // '*' used to be the comment inserted by the software way back
1609 // in antiquity in case none was provided, here for backwards
1610 // compatibility, acc. to brion -ævar
1611 if ( $comment == '' || $comment == '*' ) {
1612 return '';
1613 } else {
1614 $formatted = self::formatComment( $comment, $title, $local );
1615 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1616 return " <span class=\"comment\">$formatted</span>";
1621 * Wrap and format the given revision's comment block, if the current
1622 * user is allowed to view it.
1624 * @param Revision $rev
1625 * @param bool $local Whether section links should refer to local page
1626 * @param bool $isPublic Show only if all users can see it
1627 * @return string HTML fragment
1629 public static function revComment( Revision $rev, $local = false, $isPublic = false ) {
1630 if ( $rev->getRawComment() == "" ) {
1631 return "";
1633 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) && $isPublic ) {
1634 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1635 } elseif ( $rev->userCan( Revision::DELETED_COMMENT ) ) {
1636 $block = self::commentBlock( $rev->getComment( Revision::FOR_THIS_USER ),
1637 $rev->getTitle(), $local );
1638 } else {
1639 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1641 if ( $rev->isDeleted( Revision::DELETED_COMMENT ) ) {
1642 return " <span class=\"history-deleted\">$block</span>";
1644 return $block;
1648 * @param int $size
1649 * @return string
1651 public static function formatRevisionSize( $size ) {
1652 if ( $size == 0 ) {
1653 $stxt = wfMessage( 'historyempty' )->escaped();
1654 } else {
1655 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1656 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1658 return "<span class=\"history-size\">$stxt</span>";
1662 * Add another level to the Table of Contents
1664 * @return string
1666 public static function tocIndent() {
1667 return "\n<ul>";
1671 * Finish one or more sublevels on the Table of Contents
1673 * @param int $level
1674 * @return string
1676 public static function tocUnindent( $level ) {
1677 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ? $level : 0 );
1681 * parameter level defines if we are on an indentation level
1683 * @param string $anchor
1684 * @param string $tocline
1685 * @param string $tocnumber
1686 * @param string $level
1687 * @param string|bool $sectionIndex
1688 * @return string
1690 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1691 $classes = "toclevel-$level";
1692 if ( $sectionIndex !== false ) {
1693 $classes .= " tocsection-$sectionIndex";
1695 return "\n<li class=\"$classes\"><a href=\"#" .
1696 $anchor . '"><span class="tocnumber">' .
1697 $tocnumber . '</span> <span class="toctext">' .
1698 $tocline . '</span></a>';
1702 * End a Table Of Contents line.
1703 * tocUnindent() will be used instead if we're ending a line below
1704 * the new level.
1705 * @return string
1707 public static function tocLineEnd() {
1708 return "</li>\n";
1712 * Wraps the TOC in a table and provides the hide/collapse javascript.
1714 * @param string $toc Html of the Table Of Contents
1715 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1716 * @return string Full html of the TOC
1718 public static function tocList( $toc, $lang = false ) {
1719 $lang = wfGetLangObj( $lang );
1720 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1722 return '<div id="toc" class="toc">'
1723 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1724 . $toc
1725 . "</ul>\n</div>\n";
1729 * Generate a table of contents from a section tree
1730 * Currently unused.
1732 * @param array $tree Return value of ParserOutput::getSections()
1733 * @return string HTML fragment
1735 public static function generateTOC( $tree ) {
1736 $toc = '';
1737 $lastLevel = 0;
1738 foreach ( $tree as $section ) {
1739 if ( $section['toclevel'] > $lastLevel ) {
1740 $toc .= self::tocIndent();
1741 } elseif ( $section['toclevel'] < $lastLevel ) {
1742 $toc .= self::tocUnindent(
1743 $lastLevel - $section['toclevel'] );
1744 } else {
1745 $toc .= self::tocLineEnd();
1748 $toc .= self::tocLine( $section['anchor'],
1749 $section['line'], $section['number'],
1750 $section['toclevel'], $section['index'] );
1751 $lastLevel = $section['toclevel'];
1753 $toc .= self::tocLineEnd();
1754 return self::tocList( $toc );
1758 * Create a headline for content
1760 * @param int $level The level of the headline (1-6)
1761 * @param string $attribs Any attributes for the headline, starting with
1762 * a space and ending with '>'
1763 * This *must* be at least '>' for no attribs
1764 * @param string $anchor The anchor to give the headline (the bit after the #)
1765 * @param string $html Html for the text of the header
1766 * @param string $link HTML to add for the section edit link
1767 * @param bool|string $legacyAnchor A second, optional anchor to give for
1768 * backward compatibility (false to omit)
1770 * @return string HTML headline
1772 public static function makeHeadline( $level, $attribs, $anchor, $html,
1773 $link, $legacyAnchor = false
1775 $ret = "<h$level$attribs"
1776 . "<span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1777 . $link
1778 . "</h$level>";
1779 if ( $legacyAnchor !== false ) {
1780 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1782 return $ret;
1786 * Split a link trail, return the "inside" portion and the remainder of the trail
1787 * as a two-element array
1788 * @param string $trail
1789 * @return array
1791 static function splitTrail( $trail ) {
1792 global $wgContLang;
1793 $regex = $wgContLang->linkTrail();
1794 $inside = '';
1795 if ( $trail !== '' ) {
1796 $m = array();
1797 if ( preg_match( $regex, $trail, $m ) ) {
1798 $inside = $m[1];
1799 $trail = $m[2];
1802 return array( $inside, $trail );
1806 * Generate a rollback link for a given revision. Currently it's the
1807 * caller's responsibility to ensure that the revision is the top one. If
1808 * it's not, of course, the user will get an error message.
1810 * If the calling page is called with the parameter &bot=1, all rollback
1811 * links also get that parameter. It causes the edit itself and the rollback
1812 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1813 * changes, so this allows sysops to combat a busy vandal without bothering
1814 * other users.
1816 * If the option verify is set this function will return the link only in case the
1817 * revision can be reverted. Please note that due to performance limitations
1818 * it might be assumed that a user isn't the only contributor of a page while
1819 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1820 * work if $wgShowRollbackEditCount is disabled, so this can only function
1821 * as an additional check.
1823 * If the option noBrackets is set the rollback link wont be enclosed in []
1825 * @param Revision $rev
1826 * @param IContextSource $context Context to use or null for the main context.
1827 * @param array $options
1828 * @return string
1830 public static function generateRollback( $rev, IContextSource $context = null,
1831 $options = array( 'verify' )
1833 if ( $context === null ) {
1834 $context = RequestContext::getMain();
1837 $editCount = false;
1838 if ( in_array( 'verify', $options ) ) {
1839 $editCount = self::getRollbackEditCount( $rev, true );
1840 if ( $editCount === false ) {
1841 return '';
1845 $inner = self::buildRollbackLink( $rev, $context, $editCount );
1847 if ( !in_array( 'noBrackets', $options ) ) {
1848 $inner = $context->msg( 'brackets' )->rawParams( $inner )->plain();
1851 return '<span class="mw-rollback-link">' . $inner . '</span>';
1855 * This function will return the number of revisions which a rollback
1856 * would revert and, if $verify is set it will verify that a revision
1857 * can be reverted (that the user isn't the only contributor and the
1858 * revision we might rollback to isn't deleted). These checks can only
1859 * function as an additional check as this function only checks against
1860 * the last $wgShowRollbackEditCount edits.
1862 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1863 * is set and the user is the only contributor of the page.
1865 * @param Revision $rev
1866 * @param bool $verify Try to verify that this revision can really be rolled back
1867 * @return int|bool|null
1869 public static function getRollbackEditCount( $rev, $verify ) {
1870 global $wgShowRollbackEditCount;
1871 if ( !is_int( $wgShowRollbackEditCount ) || !$wgShowRollbackEditCount > 0 ) {
1872 // Nothing has happened, indicate this by returning 'null'
1873 return null;
1876 $dbr = wfGetDB( DB_SLAVE );
1878 // Up to the value of $wgShowRollbackEditCount revisions are counted
1879 $res = $dbr->select(
1880 'revision',
1881 array( 'rev_user_text', 'rev_deleted' ),
1882 // $rev->getPage() returns null sometimes
1883 array( 'rev_page' => $rev->getTitle()->getArticleID() ),
1884 __METHOD__,
1885 array(
1886 'USE INDEX' => array( 'revision' => 'page_timestamp' ),
1887 'ORDER BY' => 'rev_timestamp DESC',
1888 'LIMIT' => $wgShowRollbackEditCount + 1
1892 $editCount = 0;
1893 $moreRevs = false;
1894 foreach ( $res as $row ) {
1895 if ( $rev->getRawUserText() != $row->rev_user_text ) {
1896 if ( $verify &&
1897 ( $row->rev_deleted & Revision::DELETED_TEXT
1898 || $row->rev_deleted & Revision::DELETED_USER
1899 ) ) {
1900 // If the user or the text of the revision we might rollback
1901 // to is deleted in some way we can't rollback. Similar to
1902 // the sanity checks in WikiPage::commitRollback.
1903 return false;
1905 $moreRevs = true;
1906 break;
1908 $editCount++;
1911 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1912 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1913 // and there weren't any other revisions. That means that the current user is the only
1914 // editor, so we can't rollback
1915 return false;
1917 return $editCount;
1921 * Build a raw rollback link, useful for collections of "tool" links
1923 * @param Revision $rev
1924 * @param IContextSource|null $context Context to use or null for the main context.
1925 * @param int $editCount Number of edits that would be reverted
1926 * @return string HTML fragment
1928 public static function buildRollbackLink( $rev, IContextSource $context = null,
1929 $editCount = false
1931 global $wgShowRollbackEditCount, $wgMiserMode;
1933 // To config which pages are effected by miser mode
1934 $disableRollbackEditCountSpecialPage = array( 'Recentchanges', 'Watchlist' );
1936 if ( $context === null ) {
1937 $context = RequestContext::getMain();
1940 $title = $rev->getTitle();
1941 $query = array(
1942 'action' => 'rollback',
1943 'from' => $rev->getUserText(),
1944 'token' => $context->getUser()->getEditToken( array(
1945 $title->getPrefixedText(),
1946 $rev->getUserText()
1947 ) ),
1949 if ( $context->getRequest()->getBool( 'bot' ) ) {
1950 $query['bot'] = '1';
1951 $query['hidediff'] = '1'; // bug 15999
1954 $disableRollbackEditCount = false;
1955 if ( $wgMiserMode ) {
1956 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1957 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1958 $disableRollbackEditCount = true;
1959 break;
1964 if ( !$disableRollbackEditCount
1965 && is_int( $wgShowRollbackEditCount )
1966 && $wgShowRollbackEditCount > 0
1968 if ( !is_numeric( $editCount ) ) {
1969 $editCount = self::getRollbackEditCount( $rev, false );
1972 if ( $editCount > $wgShowRollbackEditCount ) {
1973 $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )
1974 ->numParams( $wgShowRollbackEditCount )->parse();
1975 } else {
1976 $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1979 return self::link(
1980 $title,
1981 $editCount_output,
1982 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1983 $query,
1984 array( 'known', 'noclasses' )
1986 } else {
1987 return self::link(
1988 $title,
1989 $context->msg( 'rollbacklink' )->escaped(),
1990 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1991 $query,
1992 array( 'known', 'noclasses' )
1998 * Returns HTML for the "templates used on this page" list.
2000 * Make an HTML list of templates, and then add a "More..." link at
2001 * the bottom. If $more is null, do not add a "More..." link. If $more
2002 * is a Title, make a link to that title and use it. If $more is a string,
2003 * directly paste it in as the link (escaping needs to be done manually).
2004 * Finally, if $more is a Message, call toString().
2006 * @param array $templates Array of templates from Article::getUsedTemplate or similar
2007 * @param bool $preview Whether this is for a preview
2008 * @param bool $section Whether this is for a section edit
2009 * @param Title|Message|string|null $more An escaped link for "More..." of the templates
2010 * @return string HTML output
2012 public static function formatTemplates( $templates, $preview = false,
2013 $section = false, $more = null
2015 global $wgLang;
2016 wfProfileIn( __METHOD__ );
2018 $outText = '';
2019 if ( count( $templates ) > 0 ) {
2020 # Do a batch existence check
2021 $batch = new LinkBatch;
2022 foreach ( $templates as $title ) {
2023 $batch->addObj( $title );
2025 $batch->execute();
2027 # Construct the HTML
2028 $outText = '<div class="mw-templatesUsedExplanation">';
2029 if ( $preview ) {
2030 $outText .= wfMessage( 'templatesusedpreview' )->numParams( count( $templates ) )
2031 ->parseAsBlock();
2032 } elseif ( $section ) {
2033 $outText .= wfMessage( 'templatesusedsection' )->numParams( count( $templates ) )
2034 ->parseAsBlock();
2035 } else {
2036 $outText .= wfMessage( 'templatesused' )->numParams( count( $templates ) )
2037 ->parseAsBlock();
2039 $outText .= "</div><ul>\n";
2041 usort( $templates, 'Title::compare' );
2042 foreach ( $templates as $titleObj ) {
2043 $protected = '';
2044 $restrictions = $titleObj->getRestrictions( 'edit' );
2045 if ( $restrictions ) {
2046 // Check backwards-compatible messages
2047 $msg = null;
2048 if ( $restrictions === array( 'sysop' ) ) {
2049 $msg = wfMessage( 'template-protected' );
2050 } elseif ( $restrictions === array( 'autoconfirmed' ) ) {
2051 $msg = wfMessage( 'template-semiprotected' );
2053 if ( $msg && !$msg->isDisabled() ) {
2054 $protected = $msg->parse();
2055 } else {
2056 // Construct the message from restriction-level-*
2057 // e.g. restriction-level-sysop, restriction-level-autoconfirmed
2058 $msgs = array();
2059 foreach ( $restrictions as $r ) {
2060 $msgs[] = wfMessage( "restriction-level-$r" )->parse();
2062 $protected = wfMessage( 'parentheses' )
2063 ->rawParams( $wgLang->commaList( $msgs ) )->escaped();
2066 if ( $titleObj->quickUserCan( 'edit' ) ) {
2067 $editLink = self::link(
2068 $titleObj,
2069 wfMessage( 'editlink' )->text(),
2070 array(),
2071 array( 'action' => 'edit' )
2073 } else {
2074 $editLink = self::link(
2075 $titleObj,
2076 wfMessage( 'viewsourcelink' )->text(),
2077 array(),
2078 array( 'action' => 'edit' )
2081 $outText .= '<li>' . self::link( $titleObj )
2082 . wfMessage( 'word-separator' )->escaped()
2083 . wfMessage( 'parentheses' )->rawParams( $editLink )->escaped()
2084 . wfMessage( 'word-separator' )->escaped()
2085 . $protected . '</li>';
2088 if ( $more instanceof Title ) {
2089 $outText .= '<li>' . self::link( $more, wfMessage( 'moredotdotdot' ) ) . '</li>';
2090 } elseif ( $more ) {
2091 $outText .= "<li>$more</li>";
2094 $outText .= '</ul>';
2096 wfProfileOut( __METHOD__ );
2097 return $outText;
2101 * Returns HTML for the "hidden categories on this page" list.
2103 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
2104 * or similar
2105 * @return string HTML output
2107 public static function formatHiddenCategories( $hiddencats ) {
2108 wfProfileIn( __METHOD__ );
2110 $outText = '';
2111 if ( count( $hiddencats ) > 0 ) {
2112 # Construct the HTML
2113 $outText = '<div class="mw-hiddenCategoriesExplanation">';
2114 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
2115 $outText .= "</div><ul>\n";
2117 foreach ( $hiddencats as $titleObj ) {
2118 # If it's hidden, it must exist - no need to check with a LinkBatch
2119 $outText .= '<li>'
2120 . self::link( $titleObj, null, array(), array(), 'known' )
2121 . "</li>\n";
2123 $outText .= '</ul>';
2125 wfProfileOut( __METHOD__ );
2126 return $outText;
2130 * Format a size in bytes for output, using an appropriate
2131 * unit (B, KB, MB or GB) according to the magnitude in question
2133 * @param int $size Size to format
2134 * @return string
2136 public static function formatSize( $size ) {
2137 global $wgLang;
2138 return htmlspecialchars( $wgLang->formatSize( $size ) );
2142 * Given the id of an interface element, constructs the appropriate title
2143 * attribute from the system messages. (Note, this is usually the id but
2144 * isn't always, because sometimes the accesskey needs to go on a different
2145 * element than the id, for reverse-compatibility, etc.)
2147 * @param string $name Id of the element, minus prefixes.
2148 * @param string|null $options Null or the string 'withaccess' to add an access-
2149 * key hint
2150 * @return string Contents of the title attribute (which you must HTML-
2151 * escape), or false for no title attribute
2153 public static function titleAttrib( $name, $options = null ) {
2154 wfProfileIn( __METHOD__ );
2156 $message = wfMessage( "tooltip-$name" );
2158 if ( !$message->exists() ) {
2159 $tooltip = false;
2160 } else {
2161 $tooltip = $message->text();
2162 # Compatibility: formerly some tooltips had [alt-.] hardcoded
2163 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2164 # Message equal to '-' means suppress it.
2165 if ( $tooltip == '-' ) {
2166 $tooltip = false;
2170 if ( $options == 'withaccess' ) {
2171 $accesskey = self::accesskey( $name );
2172 if ( $accesskey !== false ) {
2173 // Should be build the same as in jquery.accessKeyLabel.js
2174 if ( $tooltip === false || $tooltip === '' ) {
2175 $tooltip = wfMessage( 'brackets', $accesskey )->text();
2176 } else {
2177 $tooltip .= wfMessage( 'word-separator' )->text();
2178 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
2183 wfProfileOut( __METHOD__ );
2184 return $tooltip;
2187 private static $accesskeycache;
2190 * Given the id of an interface element, constructs the appropriate
2191 * accesskey attribute from the system messages. (Note, this is usually
2192 * the id but isn't always, because sometimes the accesskey needs to go on
2193 * a different element than the id, for reverse-compatibility, etc.)
2195 * @param string $name Id of the element, minus prefixes.
2196 * @return string Contents of the accesskey attribute (which you must HTML-
2197 * escape), or false for no accesskey attribute
2199 public static function accesskey( $name ) {
2200 if ( isset( self::$accesskeycache[$name] ) ) {
2201 return self::$accesskeycache[$name];
2203 wfProfileIn( __METHOD__ );
2205 $message = wfMessage( "accesskey-$name" );
2207 if ( !$message->exists() ) {
2208 $accesskey = false;
2209 } else {
2210 $accesskey = $message->plain();
2211 if ( $accesskey === '' || $accesskey === '-' ) {
2212 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2213 # attribute, but this is broken for accesskey: that might be a useful
2214 # value.
2215 $accesskey = false;
2219 wfProfileOut( __METHOD__ );
2220 self::$accesskeycache[$name] = $accesskey;
2221 return self::$accesskeycache[$name];
2225 * Get a revision-deletion link, or disabled link, or nothing, depending
2226 * on user permissions & the settings on the revision.
2228 * Will use forward-compatible revision ID in the Special:RevDelete link
2229 * if possible, otherwise the timestamp-based ID which may break after
2230 * undeletion.
2232 * @param User $user
2233 * @param Revision $rev
2234 * @param Revision $title
2235 * @return string HTML fragment
2237 public static function getRevDeleteLink( User $user, Revision $rev, Title $title ) {
2238 $canHide = $user->isAllowed( 'deleterevision' );
2239 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2240 return '';
2243 if ( !$rev->userCan( Revision::DELETED_RESTRICTED, $user ) ) {
2244 return Linker::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2245 } else {
2246 if ( $rev->getId() ) {
2247 // RevDelete links using revision ID are stable across
2248 // page deletion and undeletion; use when possible.
2249 $query = array(
2250 'type' => 'revision',
2251 'target' => $title->getPrefixedDBkey(),
2252 'ids' => $rev->getId()
2254 } else {
2255 // Older deleted entries didn't save a revision ID.
2256 // We have to refer to these by timestamp, ick!
2257 $query = array(
2258 'type' => 'archive',
2259 'target' => $title->getPrefixedDBkey(),
2260 'ids' => $rev->getTimestamp()
2263 return Linker::revDeleteLink( $query,
2264 $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
2269 * Creates a (show/hide) link for deleting revisions/log entries
2271 * @param array $query Query parameters to be passed to link()
2272 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2273 * @param bool $delete Set to true to use (show/hide) rather than (show)
2275 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2276 * span to allow for customization of appearance with CSS
2278 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
2279 $sp = SpecialPage::getTitleFor( 'Revisiondelete' );
2280 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2281 $html = wfMessage( $msgKey )->escaped();
2282 $tag = $restricted ? 'strong' : 'span';
2283 $link = self::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
2284 return Xml::tags(
2285 $tag,
2286 array( 'class' => 'mw-revdelundel-link' ),
2287 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2292 * Creates a dead (show/hide) link for deleting revisions/log entries
2294 * @param bool $delete Set to true to use (show/hide) rather than (show)
2296 * @return string HTML text wrapped in a span to allow for customization
2297 * of appearance with CSS
2299 public static function revDeleteLinkDisabled( $delete = true ) {
2300 $msgKey = $delete ? 'rev-delundel' : 'rev-showdeleted';
2301 $html = wfMessage( $msgKey )->escaped();
2302 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2303 return Xml::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), $htmlParentheses );
2306 /* Deprecated methods */
2309 * @deprecated since 1.16 Use link(); warnings since 1.21
2311 * Make a link for a title which may or may not be in the database. If you need to
2312 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
2313 * call to this will result in a DB query.
2315 * @param Title $nt The title object to make the link from, e.g. from Title::newFromText.
2316 * @param string $text Link text
2317 * @param string $query Optional query part
2318 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
2319 * be included in the link text. Other characters will be appended after
2320 * the end of the link.
2321 * @param string $prefix Optional prefix. As trail, only before instead of after.
2322 * @return string
2324 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
2325 wfDeprecated( __METHOD__, '1.21' );
2327 wfProfileIn( __METHOD__ );
2328 $query = wfCgiToArray( $query );
2329 list( $inside, $trail ) = self::splitTrail( $trail );
2330 if ( $text === '' ) {
2331 $text = self::linkText( $nt );
2334 $ret = self::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
2336 wfProfileOut( __METHOD__ );
2337 return $ret;
2341 * @deprecated since 1.16 Use link(); warnings since 1.21
2343 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
2344 * it doesn't have to do a database query. It's also valid for interwiki titles and special
2345 * pages.
2347 * @param Title $title Title object of target page
2348 * @param string $text Text to replace the title
2349 * @param string $query Link target
2350 * @param string $trail Text after link
2351 * @param string $prefix Text before link text
2352 * @param string $aprops Extra attributes to the a-element
2353 * @param string $style Style to apply - if empty, use getInternalLinkAttributesObj instead
2354 * @return string The a-element
2356 static function makeKnownLinkObj(
2357 $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = '', $style = ''
2359 wfDeprecated( __METHOD__, '1.21' );
2361 wfProfileIn( __METHOD__ );
2363 if ( $text == '' ) {
2364 $text = self::linkText( $title );
2366 $attribs = Sanitizer::mergeAttributes(
2367 Sanitizer::decodeTagAttributes( $aprops ),
2368 Sanitizer::decodeTagAttributes( $style )
2370 $query = wfCgiToArray( $query );
2371 list( $inside, $trail ) = self::splitTrail( $trail );
2373 $ret = self::link( $title, "$prefix$text$inside", $attribs, $query,
2374 array( 'known', 'noclasses' ) ) . $trail;
2376 wfProfileOut( __METHOD__ );
2377 return $ret;
2381 * Returns the attributes for the tooltip and access key.
2382 * @param string $name
2383 * @return array
2385 public static function tooltipAndAccesskeyAttribs( $name ) {
2386 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2387 # no attribute" instead of "output '' as value for attribute", this
2388 # would be three lines.
2389 $attribs = array(
2390 'title' => self::titleAttrib( $name, 'withaccess' ),
2391 'accesskey' => self::accesskey( $name )
2393 if ( $attribs['title'] === false ) {
2394 unset( $attribs['title'] );
2396 if ( $attribs['accesskey'] === false ) {
2397 unset( $attribs['accesskey'] );
2399 return $attribs;
2403 * Returns raw bits of HTML, use titleAttrib()
2404 * @param string $name
2405 * @param array|null $options
2406 * @return null|string
2408 public static function tooltip( $name, $options = null ) {
2409 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2410 # no attribute" instead of "output '' as value for attribute", this
2411 # would be two lines.
2412 $tooltip = self::titleAttrib( $name, $options );
2413 if ( $tooltip === false ) {
2414 return '';
2416 return Xml::expandAttributes( array(
2417 'title' => $tooltip
2418 ) );
2423 * @since 1.18
2425 class DummyLinker {
2428 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2429 * into static calls to the new Linker for backwards compatibility.
2431 * @param string $fname Name of called method
2432 * @param array $args Arguments to the method
2433 * @return mixed
2435 public function __call( $fname, $args ) {
2436 return call_user_func_array( array( 'Linker', $fname ), $args );