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
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.
34 * Flags for userToolLinks()
36 const TOOL_LINKS_NOBLOCK
= 1;
37 const TOOL_LINKS_EMAIL
= 2;
40 * Get the appropriate HTML attributes to add to the "a" element of an interwiki link.
42 * @deprecated since 1.25
44 * @param string $title The title text for the link, URL-encoded (???) but
46 * @param string $unused Unused
47 * @param string $class The contents of the class attribute; if an empty
48 * string is passed, which is the default value, defaults to 'external'.
51 static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
54 wfDeprecated( __METHOD__
, '1.25' );
56 # @todo FIXME: We have a whole bunch of handling here that doesn't happen in
57 # getExternalLinkAttributes, why?
58 $title = urldecode( $title );
59 $title = $wgContLang->checkTitleEncoding( $title );
60 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
62 return self
::getLinkAttributesInternal( $title, $class );
66 * Get the appropriate HTML attributes to add to the "a" element of an internal link.
68 * @deprecated since 1.25
70 * @param string $title The title text for the link, URL-encoded (???) but
72 * @param string $unused Unused
73 * @param string $class The contents of the class attribute, default none
76 static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
77 wfDeprecated( __METHOD__
, '1.25' );
79 $title = urldecode( $title );
80 $title = strtr( $title, '_', ' ' );
81 return self
::getLinkAttributesInternal( $title, $class );
85 * Get the appropriate HTML attributes to add to the "a" element of an internal
86 * link, given the Title object for the page we want to link to.
88 * @deprecated since 1.25
91 * @param string $unused Unused
92 * @param string $class The contents of the class attribute, default none
93 * @param string|bool $title Optional (unescaped) string to use in the title
94 * attribute; if false, default to the name of the page we're linking to
97 static function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
98 wfDeprecated( __METHOD__
, '1.25' );
100 if ( $title === false ) {
101 $title = $nt->getPrefixedText();
103 return self
::getLinkAttributesInternal( $title, $class );
107 * Common code for getLinkAttributesX functions
109 * @deprecated since 1.25
111 * @param string $title
112 * @param string $class
116 private static function getLinkAttributesInternal( $title, $class ) {
117 wfDeprecated( __METHOD__
, '1.25' );
119 $title = htmlspecialchars( $title );
120 $class = htmlspecialchars( $class );
122 if ( $class != '' ) {
123 $r .= " class=\"$class\"";
125 if ( $title != '' ) {
126 $r .= " title=\"$title\"";
132 * Return the CSS colour of a known link
135 * @param int $threshold User defined threshold
136 * @return string CSS class
138 public static function getLinkColour( $t, $threshold ) {
140 if ( $t->isRedirect() ) {
142 $colour = 'mw-redirect';
143 } elseif ( $threshold > 0 && $t->isContentPage() &&
144 $t->exists() && $t->getLength() < $threshold
153 * This function returns an HTML link to the given target. It serves a few
155 * 1) If $target is a Title, the correct URL to link to will be figured
157 * 2) It automatically adds the usual classes for various types of link
158 * targets: "new" for red links, "stub" for short articles, etc.
159 * 3) It escapes all attribute values safely so there's no risk of XSS.
160 * 4) It provides a default tooltip if the target is a Title (the page
161 * name of the target).
162 * link() replaces the old functions in the makeLink() family.
164 * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
166 * @param Title $target Can currently only be a Title, but this may
167 * change to support Images, literal URLs, etc.
168 * @param string $html 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 array $query 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-
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 if ( !$target instanceof Title
) {
197 wfWarn( __METHOD__
. ': Requires $target to be a Title object.', 2 );
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
211 if ( !Hooks
::run( 'LinkBegin',
212 array( $dummy, $target, &$html, &$customAttribs, &$query, &$options, &$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 if ( !in_array( 'known', $options ) && !in_array( 'broken', $options ) ) {
222 if ( $target->isKnown() ) {
223 $options[] = 'known';
225 $options[] = 'broken';
230 if ( in_array( "forcearticlepath", $options ) && $query ) {
235 # Note: we want the href attribute first, for prettiness.
236 $attribs = array( 'href' => self
::linkUrl( $target, $query, $options ) );
237 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
238 $attribs['href'] = wfAppendQuery( $attribs['href'], $oldquery );
241 $attribs = array_merge(
243 self
::linkAttribs( $target, $customAttribs, $options )
245 if ( is_null( $html ) ) {
246 $html = self
::linkText( $target );
250 if ( Hooks
::run( 'LinkEnd', array( $dummy, $target, $options, &$html, &$attribs, &$ret ) ) ) {
251 $ret = Html
::rawElement( 'a', $attribs, $html );
258 * Identical to link(), except $options defaults to 'known'.
262 public static function linkKnown(
263 $target, $html = null, $customAttribs = array(),
264 $query = array(), $options = array( 'known', 'noclasses' )
266 return self
::link( $target, $html, $customAttribs, $query, $options );
270 * Returns the Url used to link to a Title
272 * @param Title $target
273 * @param array $query Query parameters
274 * @param array $options
277 private static function linkUrl( $target, $query, $options ) {
278 # We don't want to include fragments for broken links, because they
279 # generally make no sense.
280 if ( in_array( 'broken', $options ) && $target->hasFragment() ) {
281 $target = clone $target;
282 $target->setFragment( '' );
285 # If it's a broken link, add the appropriate query pieces, unless
286 # there's already an action specified, or unless 'edit' makes no sense
287 # (i.e., for a nonexistent special page).
288 if ( in_array( 'broken', $options ) && empty( $query['action'] )
289 && !$target->isSpecialPage() ) {
290 $query['action'] = 'edit';
291 $query['redlink'] = '1';
294 if ( in_array( 'http', $options ) ) {
296 } elseif ( in_array( 'https', $options ) ) {
297 $proto = PROTO_HTTPS
;
299 $proto = PROTO_RELATIVE
;
302 $ret = $target->getLinkURL( $query, false, $proto );
307 * Returns the array of attributes used when linking to the Title $target
309 * @param Title $target
310 * @param array $attribs
311 * @param array $options
315 private static function linkAttribs( $target, $attribs, $options ) {
319 if ( !in_array( 'noclasses', $options ) ) {
320 # Now build the classes.
323 if ( in_array( 'broken', $options ) ) {
327 if ( $target->isExternal() ) {
328 $classes[] = 'extiw';
331 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
332 $colour = self
::getLinkColour( $target, $wgUser->getStubThreshold() );
333 if ( $colour !== '' ) {
334 $classes[] = $colour; # mw-redirect or stub
337 if ( $classes != array() ) {
338 $defaults['class'] = implode( ' ', $classes );
342 # Get a default title attribute.
343 if ( $target->getPrefixedText() == '' ) {
344 # A link like [[#Foo]]. This used to mean an empty title
345 # attribute, but that's silly. Just don't output a title.
346 } elseif ( in_array( 'known', $options ) ) {
347 $defaults['title'] = $target->getPrefixedText();
349 // This ends up in parser cache!
350 $defaults['title'] = wfMessage( 'red-link-title', $target->getPrefixedText() )
351 ->inContentLanguage()
355 # Finally, merge the custom attribs with the default ones, and iterate
356 # over that, deleting all "false" attributes.
358 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
359 foreach ( $merged as $key => $val ) {
360 # A false value suppresses the attribute, and we don't want the
361 # href attribute to be overridden.
362 if ( $key != 'href' && $val !== false ) {
370 * Default text of the links to the Title $target
372 * @param Title $target
376 private static function linkText( $target ) {
377 if ( !$target instanceof Title
) {
378 wfWarn( __METHOD__
. ': Requires $target to be a Title object.' );
381 // If the target is just a fragment, with no title, we return the fragment
382 // text. Otherwise, we return the title text itself.
383 if ( $target->getPrefixedText() === '' && $target->hasFragment() ) {
384 return htmlspecialchars( $target->getFragment() );
387 return htmlspecialchars( $target->getPrefixedText() );
391 * Make appropriate markup for a link to the current article. This is
392 * currently rendered as the bold link text. The calling sequence is the
393 * same as the other make*LinkObj static functions, despite $query not
397 * @param string $html [optional]
398 * @param string $query [optional]
399 * @param string $trail [optional]
400 * @param string $prefix [optional]
404 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
405 $ret = "<strong class=\"selflink\">{$prefix}{$html}</strong>{$trail}";
406 if ( !Hooks
::run( 'SelfLinkBegin', array( $nt, &$html, &$trail, &$prefix, &$ret ) ) ) {
411 $html = htmlspecialchars( $nt->getPrefixedText() );
413 list( $inside, $trail ) = self
::splitTrail( $trail );
414 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
418 * Get a message saying that an invalid title was encountered.
419 * This should be called after a method like Title::makeTitleSafe() returned
420 * a value indicating that the title object is invalid.
422 * @param IContextSource $context Context to use to get the messages
423 * @param int $namespace Namespace number
424 * @param string $title Text of the title, without the namespace part
427 public static function getInvalidTitleDescription( IContextSource
$context, $namespace, $title ) {
430 // First we check whether the namespace exists or not.
431 if ( MWNamespace
::exists( $namespace ) ) {
432 if ( $namespace == NS_MAIN
) {
433 $name = $context->msg( 'blanknamespace' )->text();
435 $name = $wgContLang->getFormattedNsText( $namespace );
437 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
439 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
444 * @param Title $title
447 static function normaliseSpecialPage( Title
$title ) {
448 if ( $title->isSpecialPage() ) {
449 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
453 $ret = SpecialPage
::getTitleFor( $name, $subpage, $title->getFragment() );
461 * Returns the filename part of an url.
462 * Used as alternative text for external images.
468 private static function fnamePart( $url ) {
469 $basename = strrchr( $url, '/' );
470 if ( false === $basename ) {
473 $basename = substr( $basename, 1 );
479 * Return the code for images which were added via external links,
480 * via Parser::maybeMakeExternalImage().
487 public static function makeExternalImage( $url, $alt = '' ) {
489 $alt = self
::fnamePart( $url );
492 $success = Hooks
::run( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
494 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
495 . "with url {$url} and alt text {$alt} to {$img}\n", true );
498 return Html
::element( 'img',
505 * Given parameters derived from [[Image:Foo|options...]], generate the
506 * HTML that that syntax inserts in the page.
508 * @param Parser $parser
509 * @param Title $title Title object of the file (not the currently viewed page)
510 * @param File $file File object, or false if it doesn't exist
511 * @param array $frameParams Associative array of parameters external to the media handler.
512 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
513 * will often be false.
514 * thumbnail If present, downscale and frame
515 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
516 * framed Shows image in original size in a frame
517 * frameless Downscale but don't frame
518 * upright If present, tweak default sizes for portrait orientation
519 * upright_factor Fudge factor for "upright" tweak (default 0.75)
520 * border If present, show a border around the image
521 * align Horizontal alignment (left, right, center, none)
522 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
523 * bottom, text-bottom)
524 * alt Alternate text for image (i.e. alt attribute). Plain text.
525 * class HTML for image classes. Plain text.
526 * caption HTML for image caption.
527 * link-url URL to link to
528 * link-title Title object to link to
529 * link-target Value for the target attribute, only with link-url
530 * no-link Boolean, suppress description link
532 * @param array $handlerParams Associative array of media handler parameters, to be passed
533 * to transform(). Typical keys are "width" and "page".
534 * @param string|bool $time Timestamp of the file, set as false for current
535 * @param string $query Query params for desc url
536 * @param int|null $widthOption Used by the parser to remember the user preference thumbnailsize
538 * @return string HTML for an image, with links, wrappers, etc.
540 public static function makeImageLink( Parser
$parser, Title
$title,
541 $file, $frameParams = array(), $handlerParams = array(), $time = false,
542 $query = "", $widthOption = null
545 $dummy = new DummyLinker
;
546 if ( !Hooks
::run( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
547 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
551 if ( $file && !$file->allowInlineDisplay() ) {
552 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
553 return self
::link( $title );
558 $hp =& $handlerParams;
560 // Clean up parameters
561 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
562 if ( !isset( $fp['align'] ) ) {
565 if ( !isset( $fp['alt'] ) ) {
568 if ( !isset( $fp['title'] ) ) {
571 if ( !isset( $fp['class'] ) ) {
575 $prefix = $postfix = '';
577 if ( 'center' == $fp['align'] ) {
578 $prefix = '<div class="center">';
580 $fp['align'] = 'none';
582 if ( $file && !isset( $hp['width'] ) ) {
583 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
584 // If its a vector image, and user only specifies height
585 // we don't want it to be limited by its "normal" width.
586 global $wgSVGMaxSize;
587 $hp['width'] = $wgSVGMaxSize;
589 $hp['width'] = $file->getWidth( $page );
592 if ( isset( $fp['thumbnail'] )
593 ||
isset( $fp['manualthumb'] )
594 ||
isset( $fp['framed'] )
595 ||
isset( $fp['frameless'] )
598 global $wgThumbLimits, $wgThumbUpright;
600 if ( $widthOption === null ||
!isset( $wgThumbLimits[$widthOption] ) ) {
601 $widthOption = User
::getDefaultOption( 'thumbsize' );
604 // Reduce width for upright images when parameter 'upright' is used
605 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
606 $fp['upright'] = $wgThumbUpright;
609 // For caching health: If width scaled down due to upright
610 // parameter, round to full __0 pixel to avoid the creation of a
611 // lot of odd thumbs.
612 $prefWidth = isset( $fp['upright'] ) ?
613 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
614 $wgThumbLimits[$widthOption];
616 // Use width which is smaller: real image width or user preference width
617 // Unless image is scalable vector.
618 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
619 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
620 $hp['width'] = $prefWidth;
625 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
626 # Create a thumbnail. Alignment depends on the writing direction of
627 # the page content language (right-aligned for LTR languages,
628 # left-aligned for RTL languages)
629 # If a thumbnail width has not been provided, it is set
630 # to the default user option as specified in Language*.php
631 if ( $fp['align'] == '' ) {
632 $fp['align'] = $parser->getTargetLanguage()->alignEnd();
634 return $prefix . self
::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
637 if ( $file && isset( $fp['frameless'] ) ) {
638 $srcWidth = $file->getWidth( $page );
639 # For "frameless" option: do not present an image bigger than the
640 # source (for bitmap-style images). This is the same behavior as the
641 # "thumb" option does it already.
642 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
643 $hp['width'] = $srcWidth;
647 if ( $file && isset( $hp['width'] ) ) {
648 # Create a resized image, without the additional thumbnail features
649 $thumb = $file->transform( $hp );
655 $s = self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
657 self
::processResponsiveImages( $file, $thumb, $hp );
660 'title' => $fp['title'],
661 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false,
662 'img-class' => $fp['class'] );
663 if ( isset( $fp['border'] ) ) {
664 $params['img-class'] .= ( $params['img-class'] !== '' ?
' ' : '' ) . 'thumbborder';
666 $params = self
::getImageLinkMTOParams( $fp, $query, $parser ) +
$params;
668 $s = $thumb->toHtml( $params );
670 if ( $fp['align'] != '' ) {
671 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
673 return str_replace( "\n", ' ', $prefix . $s . $postfix );
677 * Get the link parameters for MediaTransformOutput::toHtml() from given
678 * frame parameters supplied by the Parser.
679 * @param array $frameParams The frame parameters
680 * @param string $query An optional query string to add to description page links
681 * @param Parser|null $parser
684 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
685 $mtoParams = array();
686 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
687 $mtoParams['custom-url-link'] = $frameParams['link-url'];
688 if ( isset( $frameParams['link-target'] ) ) {
689 $mtoParams['custom-target-link'] = $frameParams['link-target'];
692 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
693 foreach ( $extLinkAttrs as $name => $val ) {
694 // Currently could include 'rel' and 'target'
695 $mtoParams['parser-extlink-' . $name] = $val;
698 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
699 $mtoParams['custom-title-link'] = self
::normaliseSpecialPage( $frameParams['link-title'] );
700 } elseif ( !empty( $frameParams['no-link'] ) ) {
703 $mtoParams['desc-link'] = true;
704 $mtoParams['desc-query'] = $query;
710 * Make HTML for a thumbnail including image, border and caption
711 * @param Title $title
712 * @param File|bool $file File object or false if it doesn't exist
713 * @param string $label
715 * @param string $align
716 * @param array $params
717 * @param bool $framed
718 * @param string $manualthumb
721 public static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt,
722 $align = 'right', $params = array(), $framed = false, $manualthumb = ""
724 $frameParams = array(
730 $frameParams['framed'] = true;
732 if ( $manualthumb ) {
733 $frameParams['manualthumb'] = $manualthumb;
735 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
739 * @param Title $title
741 * @param array $frameParams
742 * @param array $handlerParams
744 * @param string $query
747 public static function makeThumbLink2( Title
$title, $file, $frameParams = array(),
748 $handlerParams = array(), $time = false, $query = ""
750 $exists = $file && $file->exists();
754 $hp =& $handlerParams;
756 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
757 if ( !isset( $fp['align'] ) ) {
758 $fp['align'] = 'right';
760 if ( !isset( $fp['alt'] ) ) {
763 if ( !isset( $fp['title'] ) ) {
766 if ( !isset( $fp['caption'] ) ) {
770 if ( empty( $hp['width'] ) ) {
771 // Reduce width for upright images when parameter 'upright' is used
772 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
776 $manualthumb = false;
779 $outerWidth = $hp['width'] +
2;
781 if ( isset( $fp['manualthumb'] ) ) {
782 # Use manually specified thumbnail
783 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
784 if ( $manual_title ) {
785 $manual_img = wfFindFile( $manual_title );
787 $thumb = $manual_img->getUnscaledThumb( $hp );
793 } elseif ( isset( $fp['framed'] ) ) {
794 // Use image dimensions, don't scale
795 $thumb = $file->getUnscaledThumb( $hp );
798 # Do not present an image bigger than the source, for bitmap-style images
799 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
800 $srcWidth = $file->getWidth( $page );
801 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
802 $hp['width'] = $srcWidth;
804 $thumb = $file->transform( $hp );
808 $outerWidth = $thumb->getWidth() +
2;
810 $outerWidth = $hp['width'] +
2;
814 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
815 # So we don't need to pass it here in $query. However, the URL for the
816 # zoom icon still needs it, so we make a unique query for it. See bug 14771
817 $url = $title->getLocalURL( $query );
819 $url = wfAppendQuery( $url, array( 'page' => $page ) );
822 && !isset( $fp['link-title'] )
823 && !isset( $fp['link-url'] )
824 && !isset( $fp['no-link'] ) ) {
825 $fp['link-url'] = $url;
828 $s = "<div class=\"thumb t{$fp['align']}\">"
829 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
832 $s .= self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
834 } elseif ( !$thumb ) {
835 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
838 if ( !$noscale && !$manualthumb ) {
839 self
::processResponsiveImages( $file, $thumb, $hp );
843 'title' => $fp['title'],
844 'img-class' => ( isset( $fp['class'] ) && $fp['class'] !== ''
846 : '' ) . 'thumbimage'
848 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
849 $s .= $thumb->toHtml( $params );
850 if ( isset( $fp['framed'] ) ) {
853 $zoomIcon = Html
::rawElement( 'div', array( 'class' => 'magnify' ),
854 Html
::rawElement( 'a', array(
856 'class' => 'internal',
857 'title' => wfMessage( 'thumbnail-more' )->text() ),
861 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
862 return str_replace( "\n", ' ', $s );
866 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
870 * @param MediaTransformOutput $thumb
871 * @param array $hp Image parameters
873 public static function processResponsiveImages( $file, $thumb, $hp ) {
874 global $wgResponsiveImages;
875 if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
877 $hp15['width'] = round( $hp['width'] * 1.5 );
879 $hp20['width'] = $hp['width'] * 2;
880 if ( isset( $hp['height'] ) ) {
881 $hp15['height'] = round( $hp['height'] * 1.5 );
882 $hp20['height'] = $hp['height'] * 2;
885 $thumb15 = $file->transform( $hp15 );
886 $thumb20 = $file->transform( $hp20 );
887 if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
888 $thumb->responsiveUrls
['1.5'] = $thumb15->getUrl();
890 if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
891 $thumb->responsiveUrls
['2'] = $thumb20->getUrl();
897 * Make a "broken" link to an image
899 * @param Title $title
900 * @param string $label Link label (plain text)
901 * @param string $query Query string
902 * @param string $unused1 Unused parameter kept for b/c
903 * @param string $unused2 Unused parameter kept for b/c
904 * @param bool $time A file of a certain timestamp was requested
907 public static function makeBrokenImageLinkObj( $title, $label = '',
908 $query = '', $unused1 = '', $unused2 = '', $time = false
910 if ( !$title instanceof Title
) {
911 wfWarn( __METHOD__
. ': Requires $title to be a Title object.' );
912 return "<!-- ERROR -->" . htmlspecialchars( $label );
915 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
916 if ( $label == '' ) {
917 $label = $title->getPrefixedText();
919 $encLabel = htmlspecialchars( $label );
920 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
922 if ( ( $wgUploadMissingFileUrl ||
$wgUploadNavigationUrl ||
$wgEnableUploads )
925 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
928 return self
::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
931 $href = self
::getUploadUrl( $title, $query );
933 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
934 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
938 return self
::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
942 * Get the URL to upload a certain file
944 * @param Title $destFile Title object of the file to upload
945 * @param string $query Urlencoded query string to prepend
946 * @return string Urlencoded URL
948 protected static function getUploadUrl( $destFile, $query = '' ) {
949 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
950 $q = 'wpDestFile=' . $destFile->getPartialURL();
951 if ( $query != '' ) {
955 if ( $wgUploadMissingFileUrl ) {
956 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
957 } elseif ( $wgUploadNavigationUrl ) {
958 return wfAppendQuery( $wgUploadNavigationUrl, $q );
960 $upload = SpecialPage
::getTitleFor( 'Upload' );
961 return $upload->getLocalURL( $q );
966 * Create a direct link to a given uploaded file.
968 * @param Title $title
969 * @param string $html Pre-sanitized HTML
970 * @param string $time MW timestamp of file creation time
971 * @return string HTML
973 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
974 $img = wfFindFile( $title, array( 'time' => $time ) );
975 return self
::makeMediaLinkFile( $title, $img, $html );
979 * Create a direct link to a given uploaded file.
980 * This will make a broken link if $file is false.
982 * @param Title $title
983 * @param File|bool $file File object or false
984 * @param string $html Pre-sanitized HTML
985 * @return string HTML
987 * @todo Handle invalid or missing images better.
989 public static function makeMediaLinkFile( Title
$title, $file, $html = '' ) {
990 if ( $file && $file->exists() ) {
991 $url = $file->getURL();
994 $url = self
::getUploadUrl( $title );
998 $alt = $title->getText();
1010 if ( !Hooks
::run( 'LinkerMakeMediaLinkFile',
1011 array( $title, $file, &$html, &$attribs, &$ret ) ) ) {
1012 wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
1013 . "with url {$url} and text {$html} to {$ret}\n", true );
1017 return Html
::rawElement( 'a', $attribs, $html );
1021 * Make a link to a special page given its name and, optionally,
1022 * a message key from the link text.
1023 * Usage example: Linker::specialLink( 'Recentchanges' )
1025 * @param string $name
1026 * @param string $key
1029 public static function specialLink( $name, $key = '' ) {
1031 $key = strtolower( $name );
1034 return self
::linkKnown( SpecialPage
::getTitleFor( $name ), wfMessage( $key )->text() );
1038 * Make an external link
1039 * @param string $url URL to link to
1040 * @param string $text Text of link
1041 * @param bool $escape Do we escape the link text?
1042 * @param string $linktype Type of external link. Gets added to the classes
1043 * @param array $attribs Array of extra attributes to <a>
1044 * @param Title|null $title Title object used for title specific link attributes
1047 public static function makeExternalLink( $url, $text, $escape = true,
1048 $linktype = '', $attribs = array(), $title = null
1051 $class = "external";
1053 $class .= " $linktype";
1055 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1056 $class .= " {$attribs['class']}";
1058 $attribs['class'] = $class;
1061 $text = htmlspecialchars( $text );
1067 $attribs['rel'] = Parser
::getExternalLinkRel( $url, $title );
1069 $success = Hooks
::run( 'LinkerMakeExternalLink',
1070 array( &$url, &$text, &$link, &$attribs, $linktype ) );
1072 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
1073 . "with url {$url} and text {$text} to {$link}\n", true );
1076 $attribs['href'] = $url;
1077 return Html
::rawElement( 'a', $attribs, $text );
1081 * Make user link (or user contributions for unregistered users)
1082 * @param int $userId User id in database.
1083 * @param string $userName User name in database.
1084 * @param string $altUserName Text to display instead of the user name (optional)
1085 * @return string HTML fragment
1086 * @since 1.19 Method exists for a long time. $altUserName was added in 1.19.
1088 public static function userLink( $userId, $userName, $altUserName = false ) {
1089 $classes = 'mw-userlink';
1090 if ( $userId == 0 ) {
1091 $page = SpecialPage
::getTitleFor( 'Contributions', $userName );
1092 if ( $altUserName === false ) {
1093 $altUserName = IP
::prettifyIP( $userName );
1095 $classes .= ' mw-anonuserlink'; // Separate link class for anons (bug 43179)
1097 $page = Title
::makeTitle( NS_USER
, $userName );
1102 htmlspecialchars( $altUserName !== false ?
$altUserName : $userName ),
1103 array( 'class' => $classes )
1108 * Generate standard user tool links (talk, contributions, block link, etc.)
1110 * @param int $userId User identifier
1111 * @param string $userText User name or IP address
1112 * @param bool $redContribsWhenNoEdits Should the contributions link be
1113 * red if the user has no edits?
1114 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
1115 * and Linker::TOOL_LINKS_EMAIL).
1116 * @param int $edits User edit count (optional, for performance)
1117 * @return string HTML fragment
1119 public static function userToolLinks(
1120 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1122 global $wgUser, $wgDisableAnonTalk, $wgLang;
1123 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1124 $blockable = !( $flags & self
::TOOL_LINKS_NOBLOCK
);
1125 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
&& $userId;
1129 $items[] = self
::userTalkLink( $userId, $userText );
1132 // check if the user has an edit
1134 if ( $redContribsWhenNoEdits ) {
1135 if ( intval( $edits ) === 0 && $edits !== 0 ) {
1136 $user = User
::newFromId( $userId );
1137 $edits = $user->getEditCount();
1139 if ( $edits === 0 ) {
1140 $attribs['class'] = 'new';
1143 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
1145 $items[] = self
::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1147 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1148 $items[] = self
::blockLink( $userId, $userText );
1151 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1152 $items[] = self
::emailLink( $userId, $userText );
1155 Hooks
::run( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1158 return wfMessage( 'word-separator' )->escaped()
1159 . '<span class="mw-usertoollinks">'
1160 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1168 * Alias for userToolLinks( $userId, $userText, true );
1169 * @param int $userId User identifier
1170 * @param string $userText User name or IP address
1171 * @param int $edits User edit count (optional, for performance)
1174 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1175 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
1179 * @param int $userId User id in database.
1180 * @param string $userText User name in database.
1181 * @return string HTML fragment with user talk link
1183 public static function userTalkLink( $userId, $userText ) {
1184 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
1185 $userTalkLink = self
::link( $userTalkPage, wfMessage( 'talkpagelinktext' )->escaped() );
1186 return $userTalkLink;
1190 * @param int $userId Userid
1191 * @param string $userText User name in database.
1192 * @return string HTML fragment with block link
1194 public static function blockLink( $userId, $userText ) {
1195 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1196 $blockLink = self
::link( $blockPage, wfMessage( 'blocklink' )->escaped() );
1201 * @param int $userId Userid
1202 * @param string $userText User name in database.
1203 * @return string HTML fragment with e-mail user link
1205 public static function emailLink( $userId, $userText ) {
1206 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1207 $emailLink = self
::link( $emailPage, wfMessage( 'emaillink' )->escaped() );
1212 * Generate a user link if the current user is allowed to view it
1213 * @param Revision $rev
1214 * @param bool $isPublic Show only if all users can see it
1215 * @return string HTML fragment
1217 public static function revUserLink( $rev, $isPublic = false ) {
1218 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1219 $link = wfMessage( 'rev-deleted-user' )->escaped();
1220 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1221 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1222 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1224 $link = wfMessage( 'rev-deleted-user' )->escaped();
1226 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1227 return '<span class="history-deleted">' . $link . '</span>';
1233 * Generate a user tool link cluster if the current user is allowed to view it
1234 * @param Revision $rev
1235 * @param bool $isPublic Show only if all users can see it
1236 * @return string HTML
1238 public static function revUserTools( $rev, $isPublic = false ) {
1239 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1240 $link = wfMessage( 'rev-deleted-user' )->escaped();
1241 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1242 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1243 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1244 $link = self
::userLink( $userId, $userText )
1245 . self
::userToolLinks( $userId, $userText );
1247 $link = wfMessage( 'rev-deleted-user' )->escaped();
1249 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1250 return ' <span class="history-deleted">' . $link . '</span>';
1256 * This function is called by all recent changes variants, by the page history,
1257 * and by the user contributions list. It is responsible for formatting edit
1258 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1259 * auto-generated comments (from section editing) and formats [[wikilinks]].
1261 * @author Erik Moeller <moeller@scireview.de>
1263 * Note: there's not always a title to pass to this function.
1264 * Since you can't set a default parameter for a reference, I've turned it
1265 * temporarily to a value pass. Should be adjusted further. --brion
1267 * @param string $comment
1268 * @param Title|null $title Title object (to generate link to the section in autocomment)
1270 * @param bool $local Whether section links should refer to local page
1271 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1272 * For use with external changes.
1274 * @return mixed|string
1276 public static function formatComment(
1277 $comment, $title = null, $local = false, $wikiId = null
1279 # Sanitize text a bit:
1280 $comment = str_replace( "\n", " ", $comment );
1281 # Allow HTML entities (for bug 13815)
1282 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1284 # Render autocomments and make links:
1285 $comment = self
::formatAutocomments( $comment, $title, $local, $wikiId );
1286 $comment = self
::formatLinksInComment( $comment, $title, $local, $wikiId );
1292 * Converts autogenerated comments in edit summaries into section links.
1294 * The pattern for autogen comments is / * foo * /, which makes for
1296 * We look for all comments, match any text before and after the comment,
1297 * add a separator where needed and format the comment itself with CSS
1298 * Called by Linker::formatComment.
1300 * @param string $comment Comment text
1301 * @param Title|null $title An optional title object used to links to sections
1302 * @param bool $local Whether section links should refer to local page
1303 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1304 * as used by WikiMap.
1306 * @return string Formatted comment (wikitext)
1308 private static function formatAutocomments(
1309 $comment, $title = null, $local = false, $wikiId = null
1311 // @todo $append here is something of a hack to preserve the status
1312 // quo. Someone who knows more about bidi and such should decide
1313 // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1314 // wiki, both when autocomments exist and when they don't, and
1315 // (2) what markup will make that actually happen.
1317 $comment = preg_replace_callback(
1318 // To detect the presence of content before or after the
1319 // auto-comment, we use capturing groups inside optional zero-width
1320 // assertions. But older versions of PCRE can't directly make
1321 // zero-width assertions optional, so wrap them in a non-capturing
1323 '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1324 function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1327 // Ensure all match positions are defined
1328 $match +
= array( '', '', '', '' );
1330 $pre = $match[1] !== '';
1332 $post = $match[3] !== '';
1336 'FormatAutocomments',
1337 array( &$comment, $pre, $auto, $post, $title, $local, $wikiId )
1340 if ( $comment === null ) {
1344 # Remove links that a user may have manually put in the autosummary
1345 # This could be improved by copying as much of Parser::stripSectionName as desired.
1346 $section = str_replace( '[[:', '', $section );
1347 $section = str_replace( '[[', '', $section );
1348 $section = str_replace( ']]', '', $section );
1350 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1352 $sectionTitle = Title
::newFromText( '#' . $section );
1354 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1355 $title->getDBkey(), $section );
1357 if ( $sectionTitle ) {
1358 $link = Linker
::makeCommentLink( $sectionTitle, $wgLang->getArrow(), $wikiId, 'noclasses' );
1364 # written summary $presep autocomment (summary /* section */)
1365 $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1368 # autocomment $postsep written summary (/* section */ summary)
1369 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1371 $auto = '<span class="autocomment">' . $auto . '</span>';
1372 $comment = $pre . $link . $wgLang->getDirMark()
1373 . '<span dir="auto">' . $auto;
1374 $append .= '</span>';
1380 return $comment . $append;
1384 * Formats wiki links and media links in text; all other wiki formatting
1387 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1388 * @param string $comment Text to format links in. WARNING! Since the output of this
1389 * function is html, $comment must be sanitized for use as html. You probably want
1390 * to pass $comment through Sanitizer::escapeHtmlAllowEntities() before calling
1392 * @param Title|null $title An optional title object used to links to sections
1393 * @param bool $local Whether section links should refer to local page
1394 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1395 * as used by WikiMap.
1399 public static function formatLinksInComment(
1400 $comment, $title = null, $local = false, $wikiId = null
1402 return preg_replace_callback(
1405 :? # ignore optional leading colon
1406 ([^\]|]+) # 1. link target; page names cannot include ] or |
1408 # 2. a pipe-separated substring; only the last is captured
1409 # Stop matching at | and ]] without relying on backtracking.
1413 ([^[]*) # 3. link trail (the text up until the next link)
1415 function ( $match ) use ( $title, $local, $wikiId ) {
1418 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1419 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1421 $comment = $match[0];
1423 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1424 if ( strpos( $match[1], '%' ) !== false ) {
1426 rawurldecode( $match[1] ),
1427 array( '<' => '<', '>' => '>' )
1431 # Handle link renaming [[foo|text]] will show link as "text"
1432 if ( $match[2] != "" ) {
1437 $submatch = array();
1439 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1440 # Media link; trail not supported.
1441 $linkRegexp = '/\[\[(.*?)\]\]/';
1442 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1444 $thelink = Linker
::makeMediaLinkObj( $title, $text );
1447 # Other kind of link
1448 if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1449 $trail = $submatch[1];
1453 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1454 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1455 $match[1] = substr( $match[1], 1 );
1457 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1460 $linkTarget = Linker
::normalizeSubpageLink( $title, $match[1], $linkText );
1462 $target = Title
::newFromText( $linkTarget );
1464 if ( $target->getText() == '' && !$target->isExternal()
1465 && !$local && $title
1467 $newTarget = clone $title;
1468 $newTarget->setFragment( '#' . $target->getFragment() );
1469 $target = $newTarget;
1472 $thelink = Linker
::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1476 // If the link is still valid, go ahead and replace it in!
1477 $comment = preg_replace(
1479 StringUtils
::escapeRegexReplacement( $thelink ),
1492 * Generates a link to the given Title
1494 * @note This is only public for technical reasons. It's not intended for use outside Linker.
1496 * @param Title $title
1497 * @param string $text
1498 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1499 * as used by WikiMap.
1500 * @param string|string[] $options See the $options parameter in Linker::link.
1502 * @return string HTML link
1504 public static function makeCommentLink(
1505 Title
$title, $text, $wikiId = null, $options = array()
1507 if ( $wikiId !== null && !$title->isExternal() ) {
1508 $link = Linker
::makeExternalLink(
1509 WikiMap
::getForeignURL(
1511 $title->getPrefixedText(),
1512 $title->getFragment()
1515 /* escape = */ false // Already escaped
1518 $link = Linker
::link( $title, $text, array(), array(), $options );
1525 * @param Title $contextTitle
1526 * @param string $target
1527 * @param string $text
1530 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1533 # :Foobar -- override special treatment of prefix (images, language links)
1534 # /Foobar -- convert to CurrentPage/Foobar
1535 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1536 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1537 # ../Foobar -- convert to CurrentPage/Foobar,
1538 # (from CurrentPage/CurrentSubPage)
1539 # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1540 # (from CurrentPage/CurrentSubPage)
1542 $ret = $target; # default return value is no change
1544 # Some namespaces don't allow subpages,
1545 # so only perform processing if subpages are allowed
1546 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1547 $hash = strpos( $target, '#' );
1548 if ( $hash !== false ) {
1549 $suffix = substr( $target, $hash );
1550 $target = substr( $target, 0, $hash );
1555 $target = trim( $target );
1556 # Look at the first character
1557 if ( $target != '' && $target[0] === '/' ) {
1558 # / at end means we don't want the slash to be shown
1560 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1561 if ( $trailingSlashes ) {
1562 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1564 $noslash = substr( $target, 1 );
1567 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1568 if ( $text === '' ) {
1569 $text = $target . $suffix;
1570 } # this might be changed for ugliness reasons
1572 # check for .. subpage backlinks
1574 $nodotdot = $target;
1575 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1577 $nodotdot = substr( $nodotdot, 3 );
1579 if ( $dotdotcount > 0 ) {
1580 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1581 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1582 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1583 # / at the end means don't show full path
1584 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1585 $nodotdot = rtrim( $nodotdot, '/' );
1586 if ( $text === '' ) {
1587 $text = $nodotdot . $suffix;
1590 $nodotdot = trim( $nodotdot );
1591 if ( $nodotdot != '' ) {
1592 $ret .= '/' . $nodotdot;
1604 * Wrap a comment in standard punctuation and formatting if
1605 * it's non-empty, otherwise return empty string.
1607 * @param string $comment
1608 * @param Title|null $title Title object (to generate link to section in autocomment) or null
1609 * @param bool $local Whether section links should refer to local page
1610 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1611 * For use with external changes.
1615 public static function commentBlock(
1616 $comment, $title = null, $local = false, $wikiId = null
1618 // '*' used to be the comment inserted by the software way back
1619 // in antiquity in case none was provided, here for backwards
1620 // compatibility, acc. to brion -ævar
1621 if ( $comment == '' ||
$comment == '*' ) {
1624 $formatted = self
::formatComment( $comment, $title, $local, $wikiId );
1625 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1626 return " <span class=\"comment\">$formatted</span>";
1631 * Wrap and format the given revision's comment block, if the current
1632 * user is allowed to view it.
1634 * @param Revision $rev
1635 * @param bool $local Whether section links should refer to local page
1636 * @param bool $isPublic Show only if all users can see it
1637 * @return string HTML fragment
1639 public static function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1640 if ( $rev->getComment( Revision
::RAW
) == "" ) {
1643 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1644 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1645 } elseif ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1646 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1647 $rev->getTitle(), $local );
1649 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1651 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1652 return " <span class=\"history-deleted\">$block</span>";
1661 public static function formatRevisionSize( $size ) {
1663 $stxt = wfMessage( 'historyempty' )->escaped();
1665 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1666 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1668 return "<span class=\"history-size\">$stxt</span>";
1672 * Add another level to the Table of Contents
1676 public static function tocIndent() {
1681 * Finish one or more sublevels on the Table of Contents
1686 public static function tocUnindent( $level ) {
1687 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1691 * parameter level defines if we are on an indentation level
1693 * @param string $anchor
1694 * @param string $tocline
1695 * @param string $tocnumber
1696 * @param string $level
1697 * @param string|bool $sectionIndex
1700 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1701 $classes = "toclevel-$level";
1702 if ( $sectionIndex !== false ) {
1703 $classes .= " tocsection-$sectionIndex";
1705 return "\n<li class=\"$classes\"><a href=\"#" .
1706 $anchor . '"><span class="tocnumber">' .
1707 $tocnumber . '</span> <span class="toctext">' .
1708 $tocline . '</span></a>';
1712 * End a Table Of Contents line.
1713 * tocUnindent() will be used instead if we're ending a line below
1717 public static function tocLineEnd() {
1722 * Wraps the TOC in a table and provides the hide/collapse javascript.
1724 * @param string $toc Html of the Table Of Contents
1725 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1726 * @return string Full html of the TOC
1728 public static function tocList( $toc, $lang = false ) {
1729 $lang = wfGetLangObj( $lang );
1730 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1732 return '<div id="toc" class="toc">'
1733 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1735 . "</ul>\n</div>\n";
1739 * Generate a table of contents from a section tree.
1741 * @param array $tree Return value of ParserOutput::getSections()
1742 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1743 * @return string HTML fragment
1745 public static function generateTOC( $tree, $lang = false ) {
1748 foreach ( $tree as $section ) {
1749 if ( $section['toclevel'] > $lastLevel ) {
1750 $toc .= self
::tocIndent();
1751 } elseif ( $section['toclevel'] < $lastLevel ) {
1752 $toc .= self
::tocUnindent(
1753 $lastLevel - $section['toclevel'] );
1755 $toc .= self
::tocLineEnd();
1758 $toc .= self
::tocLine( $section['anchor'],
1759 $section['line'], $section['number'],
1760 $section['toclevel'], $section['index'] );
1761 $lastLevel = $section['toclevel'];
1763 $toc .= self
::tocLineEnd();
1764 return self
::tocList( $toc, $lang );
1768 * Create a headline for content
1770 * @param int $level The level of the headline (1-6)
1771 * @param string $attribs Any attributes for the headline, starting with
1772 * a space and ending with '>'
1773 * This *must* be at least '>' for no attribs
1774 * @param string $anchor The anchor to give the headline (the bit after the #)
1775 * @param string $html Html for the text of the header
1776 * @param string $link HTML to add for the section edit link
1777 * @param bool|string $legacyAnchor A second, optional anchor to give for
1778 * backward compatibility (false to omit)
1780 * @return string HTML headline
1782 public static function makeHeadline( $level, $attribs, $anchor, $html,
1783 $link, $legacyAnchor = false
1785 $ret = "<h$level$attribs"
1786 . "<span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1789 if ( $legacyAnchor !== false ) {
1790 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1796 * Split a link trail, return the "inside" portion and the remainder of the trail
1797 * as a two-element array
1798 * @param string $trail
1801 static function splitTrail( $trail ) {
1803 $regex = $wgContLang->linkTrail();
1805 if ( $trail !== '' ) {
1807 if ( preg_match( $regex, $trail, $m ) ) {
1812 return array( $inside, $trail );
1816 * Generate a rollback link for a given revision. Currently it's the
1817 * caller's responsibility to ensure that the revision is the top one. If
1818 * it's not, of course, the user will get an error message.
1820 * If the calling page is called with the parameter &bot=1, all rollback
1821 * links also get that parameter. It causes the edit itself and the rollback
1822 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1823 * changes, so this allows sysops to combat a busy vandal without bothering
1826 * If the option verify is set this function will return the link only in case the
1827 * revision can be reverted. Please note that due to performance limitations
1828 * it might be assumed that a user isn't the only contributor of a page while
1829 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1830 * work if $wgShowRollbackEditCount is disabled, so this can only function
1831 * as an additional check.
1833 * If the option noBrackets is set the rollback link wont be enclosed in []
1835 * @param Revision $rev
1836 * @param IContextSource $context Context to use or null for the main context.
1837 * @param array $options
1840 public static function generateRollback( $rev, IContextSource
$context = null,
1841 $options = array( 'verify' )
1843 if ( $context === null ) {
1844 $context = RequestContext
::getMain();
1848 if ( in_array( 'verify', $options ) ) {
1849 $editCount = self
::getRollbackEditCount( $rev, true );
1850 if ( $editCount === false ) {
1855 $inner = self
::buildRollbackLink( $rev, $context, $editCount );
1857 if ( !in_array( 'noBrackets', $options ) ) {
1858 $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1861 return '<span class="mw-rollback-link">' . $inner . '</span>';
1865 * This function will return the number of revisions which a rollback
1866 * would revert and, if $verify is set it will verify that a revision
1867 * can be reverted (that the user isn't the only contributor and the
1868 * revision we might rollback to isn't deleted). These checks can only
1869 * function as an additional check as this function only checks against
1870 * the last $wgShowRollbackEditCount edits.
1872 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1873 * is set and the user is the only contributor of the page.
1875 * @param Revision $rev
1876 * @param bool $verify Try to verify that this revision can really be rolled back
1877 * @return int|bool|null
1879 public static function getRollbackEditCount( $rev, $verify ) {
1880 global $wgShowRollbackEditCount;
1881 if ( !is_int( $wgShowRollbackEditCount ) ||
!$wgShowRollbackEditCount > 0 ) {
1882 // Nothing has happened, indicate this by returning 'null'
1886 $dbr = wfGetDB( DB_SLAVE
);
1888 // Up to the value of $wgShowRollbackEditCount revisions are counted
1889 $res = $dbr->select(
1891 array( 'rev_user_text', 'rev_deleted' ),
1892 // $rev->getPage() returns null sometimes
1893 array( 'rev_page' => $rev->getTitle()->getArticleID() ),
1896 'USE INDEX' => array( 'revision' => 'page_timestamp' ),
1897 'ORDER BY' => 'rev_timestamp DESC',
1898 'LIMIT' => $wgShowRollbackEditCount +
1
1904 foreach ( $res as $row ) {
1905 if ( $rev->getUserText( Revision
::RAW
) != $row->rev_user_text
) {
1907 ( $row->rev_deleted
& Revision
::DELETED_TEXT
1908 ||
$row->rev_deleted
& Revision
::DELETED_USER
1910 // If the user or the text of the revision we might rollback
1911 // to is deleted in some way we can't rollback. Similar to
1912 // the sanity checks in WikiPage::commitRollback.
1921 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1922 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1923 // and there weren't any other revisions. That means that the current user is the only
1924 // editor, so we can't rollback
1931 * Build a raw rollback link, useful for collections of "tool" links
1933 * @param Revision $rev
1934 * @param IContextSource|null $context Context to use or null for the main context.
1935 * @param int $editCount Number of edits that would be reverted
1936 * @return string HTML fragment
1938 public static function buildRollbackLink( $rev, IContextSource
$context = null,
1941 global $wgShowRollbackEditCount, $wgMiserMode;
1943 // To config which pages are affected by miser mode
1944 $disableRollbackEditCountSpecialPage = array( 'Recentchanges', 'Watchlist' );
1946 if ( $context === null ) {
1947 $context = RequestContext
::getMain();
1950 $title = $rev->getTitle();
1952 'action' => 'rollback',
1953 'from' => $rev->getUserText(),
1954 'token' => $context->getUser()->getEditToken( array(
1955 $title->getPrefixedText(),
1959 if ( $context->getRequest()->getBool( 'bot' ) ) {
1960 $query['bot'] = '1';
1961 $query['hidediff'] = '1'; // bug 15999
1964 $disableRollbackEditCount = false;
1965 if ( $wgMiserMode ) {
1966 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1967 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1968 $disableRollbackEditCount = true;
1974 if ( !$disableRollbackEditCount
1975 && is_int( $wgShowRollbackEditCount )
1976 && $wgShowRollbackEditCount > 0
1978 if ( !is_numeric( $editCount ) ) {
1979 $editCount = self
::getRollbackEditCount( $rev, false );
1982 if ( $editCount > $wgShowRollbackEditCount ) {
1983 $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )
1984 ->numParams( $wgShowRollbackEditCount )->parse();
1986 $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1992 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1994 array( 'known', 'noclasses' )
1999 $context->msg( 'rollbacklink' )->escaped(),
2000 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
2002 array( 'known', 'noclasses' )
2008 * Returns HTML for the "templates used on this page" list.
2010 * Make an HTML list of templates, and then add a "More..." link at
2011 * the bottom. If $more is null, do not add a "More..." link. If $more
2012 * is a Title, make a link to that title and use it. If $more is a string,
2013 * directly paste it in as the link (escaping needs to be done manually).
2014 * Finally, if $more is a Message, call toString().
2016 * @param Title[] $templates Array of templates
2017 * @param bool $preview Whether this is for a preview
2018 * @param bool $section Whether this is for a section edit
2019 * @param Title|Message|string|null $more An escaped link for "More..." of the templates
2020 * @return string HTML output
2022 public static function formatTemplates( $templates, $preview = false,
2023 $section = false, $more = null
2028 if ( count( $templates ) > 0 ) {
2029 # Do a batch existence check
2030 $batch = new LinkBatch
;
2031 foreach ( $templates as $title ) {
2032 $batch->addObj( $title );
2036 # Construct the HTML
2037 $outText = '<div class="mw-templatesUsedExplanation">';
2039 $outText .= wfMessage( 'templatesusedpreview' )->numParams( count( $templates ) )
2041 } elseif ( $section ) {
2042 $outText .= wfMessage( 'templatesusedsection' )->numParams( count( $templates ) )
2045 $outText .= wfMessage( 'templatesused' )->numParams( count( $templates ) )
2048 $outText .= "</div><ul>\n";
2050 usort( $templates, 'Title::compare' );
2051 foreach ( $templates as $titleObj ) {
2053 $restrictions = $titleObj->getRestrictions( 'edit' );
2054 if ( $restrictions ) {
2055 // Check backwards-compatible messages
2057 if ( $restrictions === array( 'sysop' ) ) {
2058 $msg = wfMessage( 'template-protected' );
2059 } elseif ( $restrictions === array( 'autoconfirmed' ) ) {
2060 $msg = wfMessage( 'template-semiprotected' );
2062 if ( $msg && !$msg->isDisabled() ) {
2063 $protected = $msg->parse();
2065 // Construct the message from restriction-level-*
2066 // e.g. restriction-level-sysop, restriction-level-autoconfirmed
2068 foreach ( $restrictions as $r ) {
2069 $msgs[] = wfMessage( "restriction-level-$r" )->parse();
2071 $protected = wfMessage( 'parentheses' )
2072 ->rawParams( $wgLang->commaList( $msgs ) )->escaped();
2075 if ( $titleObj->quickUserCan( 'edit' ) ) {
2076 $editLink = self
::link(
2078 wfMessage( 'editlink' )->escaped(),
2080 array( 'action' => 'edit' )
2083 $editLink = self
::link(
2085 wfMessage( 'viewsourcelink' )->escaped(),
2087 array( 'action' => 'edit' )
2090 $outText .= '<li>' . self
::link( $titleObj )
2091 . wfMessage( 'word-separator' )->escaped()
2092 . wfMessage( 'parentheses' )->rawParams( $editLink )->escaped()
2093 . wfMessage( 'word-separator' )->escaped()
2094 . $protected . '</li>';
2097 if ( $more instanceof Title
) {
2098 $outText .= '<li>' . self
::link( $more, wfMessage( 'moredotdotdot' ) ) . '</li>';
2099 } elseif ( $more ) {
2100 $outText .= "<li>$more</li>";
2103 $outText .= '</ul>';
2109 * Returns HTML for the "hidden categories on this page" list.
2111 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
2113 * @return string HTML output
2115 public static function formatHiddenCategories( $hiddencats ) {
2118 if ( count( $hiddencats ) > 0 ) {
2119 # Construct the HTML
2120 $outText = '<div class="mw-hiddenCategoriesExplanation">';
2121 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
2122 $outText .= "</div><ul>\n";
2124 foreach ( $hiddencats as $titleObj ) {
2125 # If it's hidden, it must exist - no need to check with a LinkBatch
2127 . self
::link( $titleObj, null, array(), array(), 'known' )
2130 $outText .= '</ul>';
2136 * Format a size in bytes for output, using an appropriate
2137 * unit (B, KB, MB or GB) according to the magnitude in question
2139 * @param int $size Size to format
2142 public static function formatSize( $size ) {
2144 return htmlspecialchars( $wgLang->formatSize( $size ) );
2148 * Given the id of an interface element, constructs the appropriate title
2149 * attribute from the system messages. (Note, this is usually the id but
2150 * isn't always, because sometimes the accesskey needs to go on a different
2151 * element than the id, for reverse-compatibility, etc.)
2153 * @param string $name Id of the element, minus prefixes.
2154 * @param string|null $options Null or the string 'withaccess' to add an access-
2156 * @param array $msgParams Parameters to pass to the message
2158 * @return string Contents of the title attribute (which you must HTML-
2159 * escape), or false for no title attribute
2161 public static function titleAttrib( $name, $options = null, array $msgParams = array() ) {
2162 $message = wfMessage( "tooltip-$name", $msgParams );
2163 if ( !$message->exists() ) {
2166 $tooltip = $message->text();
2167 # Compatibility: formerly some tooltips had [alt-.] hardcoded
2168 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2169 # Message equal to '-' means suppress it.
2170 if ( $tooltip == '-' ) {
2175 if ( $options == 'withaccess' ) {
2176 $accesskey = self
::accesskey( $name );
2177 if ( $accesskey !== false ) {
2178 // Should be build the same as in jquery.accessKeyLabel.js
2179 if ( $tooltip === false ||
$tooltip === '' ) {
2180 $tooltip = wfMessage( 'brackets', $accesskey )->text();
2182 $tooltip .= wfMessage( 'word-separator' )->text();
2183 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
2191 public static $accesskeycache;
2194 * Given the id of an interface element, constructs the appropriate
2195 * accesskey attribute from the system messages. (Note, this is usually
2196 * the id but isn't always, because sometimes the accesskey needs to go on
2197 * a different element than the id, for reverse-compatibility, etc.)
2199 * @param string $name Id of the element, minus prefixes.
2200 * @return string Contents of the accesskey attribute (which you must HTML-
2201 * escape), or false for no accesskey attribute
2203 public static function accesskey( $name ) {
2204 if ( isset( self
::$accesskeycache[$name] ) ) {
2205 return self
::$accesskeycache[$name];
2208 $message = wfMessage( "accesskey-$name" );
2210 if ( !$message->exists() ) {
2213 $accesskey = $message->plain();
2214 if ( $accesskey === '' ||
$accesskey === '-' ) {
2215 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2216 # attribute, but this is broken for accesskey: that might be a useful
2222 self
::$accesskeycache[$name] = $accesskey;
2223 return self
::$accesskeycache[$name];
2227 * Get a revision-deletion link, or disabled link, or nothing, depending
2228 * on user permissions & the settings on the revision.
2230 * Will use forward-compatible revision ID in the Special:RevDelete link
2231 * if possible, otherwise the timestamp-based ID which may break after
2235 * @param Revision $rev
2236 * @param Title $title
2237 * @return string HTML fragment
2239 public static function getRevDeleteLink( User
$user, Revision
$rev, Title
$title ) {
2240 $canHide = $user->isAllowed( 'deleterevision' );
2241 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2245 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
2246 return Linker
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2248 if ( $rev->getId() ) {
2249 // RevDelete links using revision ID are stable across
2250 // page deletion and undeletion; use when possible.
2252 'type' => 'revision',
2253 'target' => $title->getPrefixedDBkey(),
2254 'ids' => $rev->getId()
2257 // Older deleted entries didn't save a revision ID.
2258 // We have to refer to these by timestamp, ick!
2260 'type' => 'archive',
2261 'target' => $title->getPrefixedDBkey(),
2262 'ids' => $rev->getTimestamp()
2265 return Linker
::revDeleteLink( $query,
2266 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
2271 * Creates a (show/hide) link for deleting revisions/log entries
2273 * @param array $query Query parameters to be passed to link()
2274 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2275 * @param bool $delete Set to true to use (show/hide) rather than (show)
2277 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2278 * span to allow for customization of appearance with CSS
2280 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
2281 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
2282 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2283 $html = wfMessage( $msgKey )->escaped();
2284 $tag = $restricted ?
'strong' : 'span';
2285 $link = self
::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
2288 array( 'class' => 'mw-revdelundel-link' ),
2289 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2294 * Creates a dead (show/hide) link for deleting revisions/log entries
2296 * @param bool $delete Set to true to use (show/hide) rather than (show)
2298 * @return string HTML text wrapped in a span to allow for customization
2299 * of appearance with CSS
2301 public static function revDeleteLinkDisabled( $delete = true ) {
2302 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2303 $html = wfMessage( $msgKey )->escaped();
2304 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2305 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), $htmlParentheses );
2308 /* Deprecated methods */
2311 * Returns the attributes for the tooltip and access key.
2313 * @param string $name
2314 * @param array $msgParams Params for constructing the message
2318 public static function tooltipAndAccesskeyAttribs( $name, array $msgParams = array() ) {
2319 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2320 # no attribute" instead of "output '' as value for attribute", this
2321 # would be three lines.
2323 'title' => self
::titleAttrib( $name, 'withaccess', $msgParams ),
2324 'accesskey' => self
::accesskey( $name )
2326 if ( $attribs['title'] === false ) {
2327 unset( $attribs['title'] );
2329 if ( $attribs['accesskey'] === false ) {
2330 unset( $attribs['accesskey'] );
2336 * Returns raw bits of HTML, use titleAttrib()
2337 * @param string $name
2338 * @param array|null $options
2339 * @return null|string
2341 public static function tooltip( $name, $options = null ) {
2342 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2343 # no attribute" instead of "output '' as value for attribute", this
2344 # would be two lines.
2345 $tooltip = self
::titleAttrib( $name, $options );
2346 if ( $tooltip === false ) {
2349 return Xml
::expandAttributes( array(
2362 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2363 * into static calls to the new Linker for backwards compatibility.
2365 * @param string $fname Name of called method
2366 * @param array $args Arguments to the method
2369 public function __call( $fname, $args ) {
2370 return call_user_func_array( array( 'Linker', $fname ), $args );