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.
33 * Flags for userToolLinks()
35 const TOOL_LINKS_NOBLOCK
= 1;
36 const TOOL_LINKS_EMAIL
= 2;
39 * Get the appropriate HTML attributes to add to the "a" element of an ex-
40 * ternal link, as created by [wikisyntax].
42 * @param $class String: the contents of the class attribute; if an empty
43 * string is passed, which is the default value, defaults to 'external'.
45 * @deprecated since 1.18 Just pass the external class directly to something using Html::expandAttributes
47 static function getExternalLinkAttributes( $class = 'external' ) {
48 wfDeprecated( __METHOD__
, '1.18' );
49 return self
::getLinkAttributesInternal( '', $class );
53 * Get the appropriate HTML attributes to add to the "a" element of an in-
56 * @param $title String: the title text for the link, URL-encoded (???) but
58 * @param $unused String: unused
59 * @param $class String: the contents of the class attribute; if an empty
60 * string is passed, which is the default value, defaults to 'external'.
63 static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
66 # @todo FIXME: We have a whole bunch of handling here that doesn't happen in
67 # getExternalLinkAttributes, why?
68 $title = urldecode( $title );
69 $title = $wgContLang->checkTitleEncoding( $title );
70 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
72 return self
::getLinkAttributesInternal( $title, $class );
76 * Get the appropriate HTML attributes to add to the "a" element of an in-
79 * @param $title String: the title text for the link, URL-encoded (???) but
81 * @param $unused String: unused
82 * @param $class String: the contents of the class attribute, default none
85 static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
86 $title = urldecode( $title );
87 $title = str_replace( '_', ' ', $title );
88 return self
::getLinkAttributesInternal( $title, $class );
92 * Get the appropriate HTML attributes to add to the "a" element of an in-
93 * ternal link, given the Title object for the page we want to link to.
96 * @param $unused String: unused
97 * @param $class String: the contents of the class attribute, default none
98 * @param $title Mixed: optional (unescaped) string to use in the title
99 * attribute; if false, default to the name of the page we're linking to
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 $title string
113 * @param $class string
117 private static function getLinkAttributesInternal( $title, $class ) {
118 $title = htmlspecialchars( $title );
119 $class = htmlspecialchars( $class );
121 if ( $class != '' ) {
122 $r .= " class=\"$class\"";
124 if ( $title != '' ) {
125 $r .= " title=\"$title\"";
131 * Return the CSS colour of a known link
133 * @param $t Title object
134 * @param $threshold Integer: user defined threshold
135 * @return String: CSS class
137 public static function getLinkColour( $t, $threshold ) {
139 if ( $t->isRedirect() ) {
141 $colour = 'mw-redirect';
142 } elseif ( $threshold > 0 && $t->isContentPage() &&
143 $t->exists() && $t->getLength() < $threshold
152 * This function returns an HTML link to the given target. It serves a few
154 * 1) If $target is a Title, the correct URL to link to will be figured
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.
164 * You can call it using this if you want to keep compat with these:
165 * $linker = class_exists( 'DummyLinker' ) ? new DummyLinker() : new Linker();
166 * $linker->link( ... );
168 * @param $target Title Can currently only be a Title, but this may
169 * change to support Images, literal URLs, etc.
170 * @param $html string The HTML contents of the <a> element, i.e.,
171 * the link text. This is raw HTML and will not be escaped. If null,
172 * defaults to the prefixed text of the Title; or if the Title is just a
173 * fragment, the contents of the fragment.
174 * @param $customAttribs array A key => value array of extra HTML attri-
175 * butes, such as title and class. (href is ignored.) Classes will be
176 * merged with the default classes, while other attributes will replace
177 * default attributes. All passed attribute values will be HTML-escaped.
178 * A false attribute value means to suppress that attribute.
179 * @param $query array The query string to append to the URL
180 * you're linking to, in key => value array form. Query keys and values
181 * will be URL-encoded.
182 * @param $options string|array String or array of strings:
183 * 'known': Page is known to exist, so don't check if it does.
184 * 'broken': Page is known not to exist, so don't check if it does.
185 * 'noclasses': Don't add any classes automatically (includes "new",
186 * "stub", "mw-redirect", "extiw"). Only use the class attribute
187 * provided, if any, so you get a simple blue link with no funny i-
189 * 'forcearticlepath': Use the article path always, even with a querystring.
190 * Has compatibility issues on some setups, so avoid wherever possible.
191 * 'http': Force a full URL with http:// as the scheme.
192 * 'https': Force a full URL with https:// as the scheme.
193 * @return string HTML <a> attribute
195 public static function link(
196 $target, $html = null, $customAttribs = array(), $query = array(), $options = array()
198 wfProfileIn( __METHOD__
);
199 if ( !$target instanceof Title
) {
200 wfProfileOut( __METHOD__
);
201 return "<!-- ERROR -->$html";
204 if( is_string( $query ) ) {
205 // some functions withing core using this still hand over query strings
206 wfDeprecated( __METHOD__
. ' with parameter $query as string (should be array)', '1.20' );
207 $query = wfCgiToArray( $query );
209 $options = (array)$options;
211 $dummy = new DummyLinker
; // dummy linker instance for bc on the hooks
214 if ( !wfRunHooks( 'LinkBegin', array( $dummy, $target, &$html,
215 &$customAttribs, &$query, &$options, &$ret ) ) ) {
216 wfProfileOut( __METHOD__
);
220 # Normalize the Title if it's a special page
221 $target = self
::normaliseSpecialPage( $target );
223 # If we don't know whether the page exists, let's find out.
224 wfProfileIn( __METHOD__
. '-checkPageExistence' );
225 if ( !in_array( 'known', $options ) and !in_array( 'broken', $options ) ) {
226 if ( $target->isKnown() ) {
227 $options[] = 'known';
229 $options[] = 'broken';
232 wfProfileOut( __METHOD__
. '-checkPageExistence' );
235 if ( in_array( "forcearticlepath", $options ) && $query ) {
240 # Note: we want the href attribute first, for prettiness.
241 $attribs = array( 'href' => self
::linkUrl( $target, $query, $options ) );
242 if ( in_array( 'forcearticlepath', $options ) && $oldquery ) {
243 $attribs['href'] = wfAppendQuery( $attribs['href'], wfArrayToCgi( $oldquery ) );
246 $attribs = array_merge(
248 self
::linkAttribs( $target, $customAttribs, $options )
250 if ( is_null( $html ) ) {
251 $html = self
::linkText( $target );
255 if ( wfRunHooks( 'LinkEnd', array( $dummy, $target, $options, &$html, &$attribs, &$ret ) ) ) {
256 $ret = Html
::rawElement( 'a', $attribs, $html );
259 wfProfileOut( __METHOD__
);
264 * Identical to link(), except $options defaults to 'known'.
267 public static function linkKnown(
268 $target, $html = null, $customAttribs = array(),
269 $query = array(), $options = array( 'known', 'noclasses' ) )
271 return self
::link( $target, $html, $customAttribs, $query, $options );
275 * Returns the Url used to link to a Title
277 * @param $target Title
278 * @param $query Array: query parameters
279 * @param $options Array
282 private static function linkUrl( $target, $query, $options ) {
283 wfProfileIn( __METHOD__
);
284 # We don't want to include fragments for broken links, because they
285 # generally make no sense.
286 if ( in_array( 'broken', $options ) && $target->mFragment
!== '' ) {
287 $target = clone $target;
288 $target->mFragment
= '';
291 # If it's a broken link, add the appropriate query pieces, unless
292 # there's already an action specified, or unless 'edit' makes no sense
293 # (i.e., for a nonexistent special page).
294 if ( in_array( 'broken', $options ) && empty( $query['action'] )
295 && !$target->isSpecialPage() ) {
296 $query['action'] = 'edit';
297 $query['redlink'] = '1';
300 if ( in_array( 'http', $options ) ) {
302 } elseif ( in_array( 'https', $options ) ) {
303 $proto = PROTO_HTTPS
;
305 $proto = PROTO_RELATIVE
;
308 $ret = $target->getLinkURL( $query, false, $proto );
309 wfProfileOut( __METHOD__
);
314 * Returns the array of attributes used when linking to the Title $target
316 * @param $target Title
322 private static function linkAttribs( $target, $attribs, $options ) {
323 wfProfileIn( __METHOD__
);
327 if ( !in_array( 'noclasses', $options ) ) {
328 wfProfileIn( __METHOD__
. '-getClasses' );
329 # Now build the classes.
332 if ( in_array( 'broken', $options ) ) {
336 if ( $target->isExternal() ) {
337 $classes[] = 'extiw';
340 if ( !in_array( 'broken', $options ) ) { # Avoid useless calls to LinkCache (see r50387)
341 $colour = self
::getLinkColour( $target, $wgUser->getStubThreshold() );
342 if ( $colour !== '' ) {
343 $classes[] = $colour; # mw-redirect or stub
346 if ( $classes != array() ) {
347 $defaults['class'] = implode( ' ', $classes );
349 wfProfileOut( __METHOD__
. '-getClasses' );
352 # Get a default title attribute.
353 if ( $target->getPrefixedText() == '' ) {
354 # A link like [[#Foo]]. This used to mean an empty title
355 # attribute, but that's silly. Just don't output a title.
356 } elseif ( in_array( 'known', $options ) ) {
357 $defaults['title'] = $target->getPrefixedText();
359 $defaults['title'] = wfMessage( 'red-link-title', $target->getPrefixedText() )->text();
362 # Finally, merge the custom attribs with the default ones, and iterate
363 # over that, deleting all "false" attributes.
365 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
366 foreach ( $merged as $key => $val ) {
367 # A false value suppresses the attribute, and we don't want the
368 # href attribute to be overridden.
369 if ( $key != 'href' and $val !== false ) {
373 wfProfileOut( __METHOD__
);
378 * Default text of the links to the Title $target
380 * @param $target Title
384 private static function linkText( $target ) {
385 # We might be passed a non-Title by make*LinkObj(). Fail gracefully.
386 if ( !$target instanceof Title
) {
390 # If the target is just a fragment, with no title, we return the frag-
391 # ment text. Otherwise, we return the title text itself.
392 if ( $target->getPrefixedText() === '' && $target->getFragment() !== '' ) {
393 return htmlspecialchars( $target->getFragment() );
395 return htmlspecialchars( $target->getPrefixedText() );
399 * Generate either a normal exists-style link or a stub link, depending
400 * on the given page size.
402 * @param $size Integer
403 * @param $nt Title object.
404 * @param $text String
405 * @param $query String
406 * @param $trail String
407 * @param $prefix String
408 * @return string HTML of link
409 * @deprecated since 1.17
411 static function makeSizeLinkObj( $size, $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
413 wfDeprecated( __METHOD__
, '1.17' );
415 $threshold = $wgUser->getStubThreshold();
416 $colour = ( $size < $threshold ) ?
'stub' : '';
417 // @todo FIXME: Replace deprecated makeColouredLinkObj by link()
418 return self
::makeColouredLinkObj( $nt, $colour, $text, $query, $trail, $prefix );
422 * Make appropriate markup for a link to the current article. This is currently rendered
423 * as the bold link text. The calling sequence is the same as the other make*LinkObj static functions,
424 * despite $query not being used.
427 * @param $html String [optional]
428 * @param $query String [optional]
429 * @param $trail String [optional]
430 * @param $prefix String [optional]
435 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
437 $html = htmlspecialchars( $nt->getPrefixedText() );
439 list( $inside, $trail ) = self
::splitTrail( $trail );
440 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
444 * Get a message saying that an invalid title was encountered.
445 * This should be called after a method like Title::makeTitleSafe() returned
446 * a value indicating that the title object is invalid.
448 * @param $context IContextSource context to use to get the messages
449 * @param $namespace int Namespace number
450 * @param $title string Text of the title, without the namespace part
452 public static function getInvalidTitleDescription( IContextSource
$context, $namespace, $title ) {
455 // First we check whether the namespace exists or not.
456 if ( MWNamespace
::exists( $namespace ) ) {
457 if ( $namespace == NS_MAIN
) {
458 $name = $context->msg( 'blanknamespace' )->text();
460 $name = $wgContLang->getFormattedNsText( $namespace );
462 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
464 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
469 * @param $title Title
472 static function normaliseSpecialPage( Title
$title ) {
473 if ( $title->isSpecialPage() ) {
474 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
478 $ret = SpecialPage
::getTitleFor( $name, $subpage );
479 $ret->mFragment
= $title->getFragment();
487 * Returns the filename part of an url.
488 * Used as alternative text for external images.
494 private static function fnamePart( $url ) {
495 $basename = strrchr( $url, '/' );
496 if ( false === $basename ) {
499 $basename = substr( $basename, 1 );
505 * Return the code for images which were added via external links,
506 * via Parser::maybeMakeExternalImage().
513 public static function makeExternalImage( $url, $alt = '' ) {
515 $alt = self
::fnamePart( $url );
518 $success = wfRunHooks( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
520 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image with url {$url} and alt text {$alt} to {$img}\n", true );
523 return Html
::element( 'img',
530 * Given parameters derived from [[Image:Foo|options...]], generate the
531 * HTML that that syntax inserts in the page.
533 * @param $parser Parser object
534 * @param $title Title object of the file (not the currently viewed page)
535 * @param $file File object, or false if it doesn't exist
536 * @param $frameParams Array: associative array of parameters external to the media handler.
537 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
538 * will often be false.
539 * thumbnail If present, downscale and frame
540 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
541 * framed Shows image in original size in a frame
542 * frameless Downscale but don't frame
543 * upright If present, tweak default sizes for portrait orientation
544 * upright_factor Fudge factor for "upright" tweak (default 0.75)
545 * border If present, show a border around the image
546 * align Horizontal alignment (left, right, center, none)
547 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
548 * bottom, text-bottom)
549 * alt Alternate text for image (i.e. alt attribute). Plain text.
550 * class HTML for image classes. Plain text.
551 * caption HTML for image caption.
552 * link-url URL to link to
553 * link-title Title object to link to
554 * link-target Value for the target attribue, only with link-url
555 * no-link Boolean, suppress description link
557 * @param $handlerParams Array: associative array of media handler parameters, to be passed
558 * to transform(). Typical keys are "width" and "page".
559 * @param $time String: timestamp of the file, set as false for current
560 * @param $query String: query params for desc url
561 * @param $widthOption: Used by the parser to remember the user preference thumbnailsize
563 * @return String: HTML for an image, with links, wrappers, etc.
565 public static function makeImageLink( /*Parser*/ $parser, Title
$title, $file, $frameParams = array(),
566 $handlerParams = array(), $time = false, $query = "", $widthOption = null )
569 $dummy = new DummyLinker
;
570 if ( !wfRunHooks( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
571 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
575 if ( $file && !$file->allowInlineDisplay() ) {
576 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
577 return self
::link( $title );
582 $hp =& $handlerParams;
584 // Clean up parameters
585 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
586 if ( !isset( $fp['align'] ) ) {
589 if ( !isset( $fp['alt'] ) ) {
592 if ( !isset( $fp['title'] ) ) {
595 if ( !isset( $fp['class'] ) ) {
599 $prefix = $postfix = '';
601 if ( 'center' == $fp['align'] ) {
602 $prefix = '<div class="center">';
604 $fp['align'] = 'none';
606 if ( $file && !isset( $hp['width'] ) ) {
607 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
608 // If its a vector image, and user only specifies height
609 // we don't want it to be limited by its "normal" width.
610 global $wgSVGMaxSize;
611 $hp['width'] = $wgSVGMaxSize;
613 $hp['width'] = $file->getWidth( $page );
616 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['framed'] ) ||
isset( $fp['frameless'] ) ||
!$hp['width'] ) {
617 global $wgThumbLimits, $wgThumbUpright;
618 if ( !isset( $widthOption ) ||
!isset( $wgThumbLimits[$widthOption] ) ) {
619 $widthOption = User
::getDefaultOption( 'thumbsize' );
622 // Reduce width for upright images when parameter 'upright' is used
623 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
624 $fp['upright'] = $wgThumbUpright;
626 // For caching health: If width scaled down due to upright parameter, round to full __0 pixel to avoid the creation of a lot of odd thumbs
627 $prefWidth = isset( $fp['upright'] ) ?
628 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
629 $wgThumbLimits[$widthOption];
631 // Use width which is smaller: real image width or user preference width
632 // Unless image is scalable vector.
633 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
634 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
635 $hp['width'] = $prefWidth;
640 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
641 # Create a thumbnail. Alignment depends on the writing direction of
642 # the page content language (right-aligned for LTR languages,
643 # left-aligned for RTL languages)
645 # If a thumbnail width has not been provided, it is set
646 # to the default user option as specified in Language*.php
647 if ( $fp['align'] == '' ) {
648 if( $parser instanceof Parser
) {
649 $fp['align'] = $parser->getTargetLanguage()->alignEnd();
651 # backwards compatibility, remove with makeImageLink2()
653 $fp['align'] = $wgContLang->alignEnd();
656 return $prefix . self
::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
659 if ( $file && isset( $fp['frameless'] ) ) {
660 $srcWidth = $file->getWidth( $page );
661 # For "frameless" option: do not present an image bigger than the source (for bitmap-style images)
662 # This is the same behaviour as the "thumb" option does it already.
663 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
664 $hp['width'] = $srcWidth;
668 if ( $file && isset( $hp['width'] ) ) {
669 # Create a resized image, without the additional thumbnail features
670 $thumb = $file->transform( $hp );
676 $s = self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
680 'title' => $fp['title'],
681 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false,
682 'img-class' => $fp['class'] );
683 if ( isset( $fp['border'] ) ) {
684 $params['img-class'] .= ( $params['img-class'] !== '' ) ?
' thumbborder' : 'thumbborder';
686 $params = self
::getImageLinkMTOParams( $fp, $query, $parser ) +
$params;
688 $s = $thumb->toHtml( $params );
690 if ( $fp['align'] != '' ) {
691 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
693 return str_replace( "\n", ' ', $prefix . $s . $postfix );
697 * See makeImageLink()
698 * When this function is removed, remove if( $parser instanceof Parser ) check there too
699 * @deprecated since 1.20
701 public static function makeImageLink2( Title
$title, $file, $frameParams = array(),
702 $handlerParams = array(), $time = false, $query = "", $widthOption = null ) {
703 return self
::makeImageLink( null, $title, $file, $frameParams,
704 $handlerParams, $time, $query, $widthOption );
708 * Get the link parameters for MediaTransformOutput::toHtml() from given
709 * frame parameters supplied by the Parser.
710 * @param $frameParams array The frame parameters
711 * @param $query string An optional query string to add to description page links
714 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
715 $mtoParams = array();
716 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
717 $mtoParams['custom-url-link'] = $frameParams['link-url'];
718 if ( isset( $frameParams['link-target'] ) ) {
719 $mtoParams['custom-target-link'] = $frameParams['link-target'];
722 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
723 foreach ( $extLinkAttrs as $name => $val ) {
724 // Currently could include 'rel' and 'target'
725 $mtoParams['parser-extlink-'.$name] = $val;
728 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
729 $mtoParams['custom-title-link'] = self
::normaliseSpecialPage( $frameParams['link-title'] );
730 } elseif ( !empty( $frameParams['no-link'] ) ) {
733 $mtoParams['desc-link'] = true;
734 $mtoParams['desc-query'] = $query;
740 * Make HTML for a thumbnail including image, border and caption
741 * @param $title Title object
742 * @param $file File object or false if it doesn't exist
743 * @param $label String
745 * @param $align String
746 * @param $params Array
747 * @param $framed Boolean
748 * @param $manualthumb String
751 public static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt,
752 $align = 'right', $params = array(), $framed = false , $manualthumb = "" )
754 $frameParams = array(
760 $frameParams['framed'] = true;
762 if ( $manualthumb ) {
763 $frameParams['manualthumb'] = $manualthumb;
765 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
769 * @param $title Title
771 * @param array $frameParams
772 * @param array $handlerParams
774 * @param string $query
777 public static function makeThumbLink2( Title
$title, $file, $frameParams = array(),
778 $handlerParams = array(), $time = false, $query = "" )
780 global $wgStylePath, $wgContLang;
781 $exists = $file && $file->exists();
785 $hp =& $handlerParams;
787 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
788 if ( !isset( $fp['align'] ) ) $fp['align'] = 'right';
789 if ( !isset( $fp['alt'] ) ) $fp['alt'] = '';
790 if ( !isset( $fp['title'] ) ) $fp['title'] = '';
791 if ( !isset( $fp['caption'] ) ) $fp['caption'] = '';
793 if ( empty( $hp['width'] ) ) {
794 // Reduce width for upright images when parameter 'upright' is used
795 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
800 $outerWidth = $hp['width'] +
2;
802 if ( isset( $fp['manualthumb'] ) ) {
803 # Use manually specified thumbnail
804 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
805 if ( $manual_title ) {
806 $manual_img = wfFindFile( $manual_title );
808 $thumb = $manual_img->getUnscaledThumb( $hp );
813 } elseif ( isset( $fp['framed'] ) ) {
814 // Use image dimensions, don't scale
815 $thumb = $file->getUnscaledThumb( $hp );
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 behaviour
819 $srcWidth = $file->getWidth( $page );
820 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
821 $hp['width'] = $srcWidth;
823 $thumb = $file->transform( $hp );
827 $outerWidth = $thumb->getWidth() +
2;
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 );
838 $url = wfAppendQuery( $url, 'page=' . urlencode( $page ) );
841 $s = "<div class=\"thumb t{$fp['align']}\"><div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
843 $s .= self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
845 } elseif ( !$thumb ) {
846 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
851 'title' => $fp['title'],
852 'img-class' => ( isset( $fp['class'] ) && $fp['class'] !== '' ) ?
$fp['class'] . ' thumbimage' : 'thumbimage'
854 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
855 $s .= $thumb->toHtml( $params );
856 if ( isset( $fp['framed'] ) ) {
859 $zoomIcon = Html
::rawElement( 'div', array( 'class' => 'magnify' ),
860 Html
::rawElement( 'a', array(
862 'class' => 'internal',
863 'title' => wfMessage( 'thumbnail-more' )->text() ),
864 Html
::element( 'img', array(
865 'src' => $wgStylePath . '/common/images/magnify-clip' . ( $wgContLang->isRTL() ?
'-rtl' : '' ) . '.png',
871 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
872 return str_replace( "\n", ' ', $s );
876 * Make a "broken" link to an image
878 * @param $title Title object
879 * @param $label String: link label (plain text)
880 * @param $query String: query string
881 * @param $unused1 Unused parameter kept for b/c
882 * @param $unused2 Unused parameter kept for b/c
883 * @param $time Boolean: a file of a certain timestamp was requested
886 public static function makeBrokenImageLinkObj( $title, $label = '', $query = '', $unused1 = '', $unused2 = '', $time = false ) {
887 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
888 if ( ! $title instanceof Title
) {
889 return "<!-- ERROR -->" . htmlspecialchars( $label );
891 wfProfileIn( __METHOD__
);
892 if ( $label == '' ) {
893 $label = $title->getPrefixedText();
895 $encLabel = htmlspecialchars( $label );
896 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
898 if ( ( $wgUploadMissingFileUrl ||
$wgUploadNavigationUrl ||
$wgEnableUploads ) && !$currentExists ) {
899 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
902 wfProfileOut( __METHOD__
);
903 return self
::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
906 $href = self
::getUploadUrl( $title, $query );
908 wfProfileOut( __METHOD__
);
909 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
910 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
913 wfProfileOut( __METHOD__
);
914 return self
::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
919 * Get the URL to upload a certain file
921 * @param $destFile Title object of the file to upload
922 * @param $query String: urlencoded query string to prepend
923 * @return String: urlencoded URL
925 protected static function getUploadUrl( $destFile, $query = '' ) {
926 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
927 $q = 'wpDestFile=' . $destFile->getPartialUrl();
931 if ( $wgUploadMissingFileUrl ) {
932 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
933 } elseif( $wgUploadNavigationUrl ) {
934 return wfAppendQuery( $wgUploadNavigationUrl, $q );
936 $upload = SpecialPage
::getTitleFor( 'Upload' );
937 return $upload->getLocalUrl( $q );
942 * Create a direct link to a given uploaded file.
944 * @param $title Title object.
945 * @param $html String: pre-sanitized HTML
946 * @param $time string: MW timestamp of file creation time
947 * @return String: HTML
949 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
950 $img = wfFindFile( $title, array( 'time' => $time ) );
951 return self
::makeMediaLinkFile( $title, $img, $html );
955 * Create a direct link to a given uploaded file.
956 * This will make a broken link if $file is false.
958 * @param $title Title object.
959 * @param $file File|bool mixed File object or false
960 * @param $html String: pre-sanitized HTML
961 * @return String: HTML
963 * @todo Handle invalid or missing images better.
965 public static function makeMediaLinkFile( Title
$title, $file, $html = '' ) {
966 if ( $file && $file->exists() ) {
967 $url = $file->getURL();
970 $url = self
::getUploadUrl( $title );
973 $alt = htmlspecialchars( $title->getText(), ENT_QUOTES
);
977 $u = htmlspecialchars( $url );
978 return "<a href=\"{$u}\" class=\"$class\" title=\"{$alt}\">{$html}</a>";
982 * Make a link to a special page given its name and, optionally,
983 * a message key from the link text.
984 * Usage example: Linker::specialLink( 'Recentchanges' )
988 public static function specialLink( $name, $key = '' ) {
990 $key = strtolower( $name );
993 return self
::linkKnown( SpecialPage
::getTitleFor( $name ) , wfMessage( $key )->text() );
997 * Make an external link
998 * @param $url String: URL to link to
999 * @param $text String: text of link
1000 * @param $escape Boolean: do we escape the link text?
1001 * @param $linktype String: type of external link. Gets added to the classes
1002 * @param $attribs Array of extra attributes to <a>
1005 public static function makeExternalLink( $url, $text, $escape = true, $linktype = '', $attribs = array() ) {
1006 $class = "external";
1008 $class .= " $linktype";
1010 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1011 $class .= " {$attribs['class']}";
1013 $attribs['class'] = $class;
1016 $text = htmlspecialchars( $text );
1019 $success = wfRunHooks( 'LinkerMakeExternalLink',
1020 array( &$url, &$text, &$link, &$attribs, $linktype ) );
1022 wfDebug( "Hook LinkerMakeExternalLink changed the output of link with url {$url} and text {$text} to {$link}\n", true );
1025 $attribs['href'] = $url;
1026 return Html
::rawElement( 'a', $attribs, $text );
1030 * Make user link (or user contributions for unregistered users)
1031 * @param $userId Integer: user id in database.
1032 * @param $userName String: user name in database.
1033 * @param $altUserName String: text to display instead of the user name (optional)
1034 * @return String: HTML fragment
1035 * @since 1.19 Method exists for a long time. $altUserName was added in 1.19.
1037 public static function userLink( $userId, $userName, $altUserName = false ) {
1038 if ( $userId == 0 ) {
1039 $page = SpecialPage
::getTitleFor( 'Contributions', $userName );
1041 $page = Title
::makeTitle( NS_USER
, $userName );
1046 htmlspecialchars( $altUserName !== false ?
$altUserName : $userName ),
1047 array( 'class' => 'mw-userlink' )
1052 * Generate standard user tool links (talk, contributions, block link, etc.)
1054 * @param $userId Integer: user identifier
1055 * @param $userText String: user name or IP address
1056 * @param $redContribsWhenNoEdits Boolean: should the contributions link be
1057 * red if the user has no edits?
1058 * @param $flags Integer: customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK and Linker::TOOL_LINKS_EMAIL)
1059 * @param $edits Integer: user edit count (optional, for performance)
1060 * @return String: HTML fragment
1062 public static function userToolLinks(
1063 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1065 global $wgUser, $wgDisableAnonTalk, $wgLang;
1066 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1067 $blockable = !( $flags & self
::TOOL_LINKS_NOBLOCK
);
1068 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
&& $userId;
1072 $items[] = self
::userTalkLink( $userId, $userText );
1075 // check if the user has an edit
1077 if ( $redContribsWhenNoEdits ) {
1078 $count = !is_null( $edits ) ?
$edits : User
::edits( $userId );
1079 if ( $count == 0 ) {
1080 $attribs['class'] = 'new';
1083 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
1085 $items[] = self
::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1087 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1088 $items[] = self
::blockLink( $userId, $userText );
1091 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1092 $items[] = self
::emailLink( $userId, $userText );
1095 wfRunHooks( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1098 return wfMessage( 'word-separator' )->plain()
1099 . '<span class="mw-usertoollinks">'
1100 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1108 * Alias for userToolLinks( $userId, $userText, true );
1109 * @param $userId Integer: user identifier
1110 * @param $userText String: user name or IP address
1111 * @param $edits Integer: user edit count (optional, for performance)
1114 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1115 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
1120 * @param $userId Integer: user id in database.
1121 * @param $userText String: user name in database.
1122 * @return String: HTML fragment with user talk link
1124 public static function userTalkLink( $userId, $userText ) {
1125 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
1126 $userTalkLink = self
::link( $userTalkPage, wfMessage( 'talkpagelinktext' )->escaped() );
1127 return $userTalkLink;
1131 * @param $userId Integer: userid
1132 * @param $userText String: user name in database.
1133 * @return String: HTML fragment with block link
1135 public static function blockLink( $userId, $userText ) {
1136 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1137 $blockLink = self
::link( $blockPage, wfMessage( 'blocklink' )->escaped() );
1142 * @param $userId Integer: userid
1143 * @param $userText String: user name in database.
1144 * @return String: HTML fragment with e-mail user link
1146 public static function emailLink( $userId, $userText ) {
1147 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1148 $emailLink = self
::link( $emailPage, wfMessage( 'emaillink' )->escaped() );
1153 * Generate a user link if the current user is allowed to view it
1154 * @param $rev Revision object.
1155 * @param $isPublic Boolean: show only if all users can see it
1156 * @return String: HTML fragment
1158 public static function revUserLink( $rev, $isPublic = false ) {
1159 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1160 $link = wfMessage( 'rev-deleted-user' )->escaped();
1161 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1162 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1163 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1165 $link = wfMessage( 'rev-deleted-user' )->escaped();
1167 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1168 return '<span class="history-deleted">' . $link . '</span>';
1174 * Generate a user tool link cluster if the current user is allowed to view it
1175 * @param $rev Revision object.
1176 * @param $isPublic Boolean: show only if all users can see it
1177 * @return string HTML
1179 public static function revUserTools( $rev, $isPublic = false ) {
1180 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1181 $link = wfMessage( 'rev-deleted-user' )->escaped();
1182 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1183 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1184 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1185 $link = self
::userLink( $userId, $userText )
1186 . wfMessage( 'word-separator' )->plain()
1187 . self
::userToolLinks( $userId, $userText );
1189 $link = wfMessage( 'rev-deleted-user' )->escaped();
1191 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1192 return ' <span class="history-deleted">' . $link . '</span>';
1198 * This function is called by all recent changes variants, by the page history,
1199 * and by the user contributions list. It is responsible for formatting edit
1200 * comments. It escapes any HTML in the comment, but adds some CSS to format
1201 * auto-generated comments (from section editing) and formats [[wikilinks]].
1203 * @author Erik Moeller <moeller@scireview.de>
1205 * Note: there's not always a title to pass to this function.
1206 * Since you can't set a default parameter for a reference, I've turned it
1207 * temporarily to a value pass. Should be adjusted further. --brion
1209 * @param $comment String
1210 * @param $title Mixed: Title object (to generate link to the section in autocomment) or null
1211 * @param $local Boolean: whether section links should refer to local page
1212 * @return mixed|String
1214 public static function formatComment( $comment, $title = null, $local = false ) {
1215 wfProfileIn( __METHOD__
);
1217 # Sanitize text a bit:
1218 $comment = str_replace( "\n", " ", $comment );
1219 # Allow HTML entities (for bug 13815)
1220 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1222 # Render autocomments and make links:
1223 $comment = self
::formatAutocomments( $comment, $title, $local );
1224 $comment = self
::formatLinksInComment( $comment, $title, $local );
1226 wfProfileOut( __METHOD__
);
1233 static $autocommentTitle;
1234 static $autocommentLocal;
1237 * The pattern for autogen comments is / * foo * /, which makes for
1239 * We look for all comments, match any text before and after the comment,
1240 * add a separator where needed and format the comment itself with CSS
1241 * Called by Linker::formatComment.
1243 * @param $comment String: comment text
1244 * @param $title Title|null An optional title object used to links to sections
1245 * @param $local Boolean: whether section links should refer to local page
1246 * @return String: formatted comment
1248 private static function formatAutocomments( $comment, $title = null, $local = false ) {
1250 self
::$autocommentTitle = $title;
1251 self
::$autocommentLocal = $local;
1252 $comment = preg_replace_callback(
1253 '!(.*)/\*\s*(.*?)\s*\*/(.*)!',
1254 array( 'Linker', 'formatAutocommentsCallback' ),
1256 self
::$autocommentTitle = null;
1257 self
::$autocommentLocal = null;
1265 private static function formatAutocommentsCallback( $match ) {
1267 $title = self
::$autocommentTitle;
1268 $local = self
::$autocommentLocal;
1274 wfRunHooks( 'FormatAutocomments', array( &$comment, $pre, $auto, $post, $title, $local ) );
1275 if ( $comment === null ) {
1280 # Remove links that a user may have manually put in the autosummary
1281 # This could be improved by copying as much of Parser::stripSectionName as desired.
1282 $section = str_replace( '[[:', '', $section );
1283 $section = str_replace( '[[', '', $section );
1284 $section = str_replace( ']]', '', $section );
1286 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1288 $sectionTitle = Title
::newFromText( '#' . $section );
1290 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1291 $title->getDBkey(), $section );
1293 if ( $sectionTitle ) {
1294 $link = self
::link( $sectionTitle,
1295 $wgLang->getArrow(), array(), array(),
1302 # written summary $presep autocomment (summary /* section */)
1303 $pre .= wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1306 # autocomment $postsep written summary (/* section */ summary)
1307 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1309 $auto = '<span class="autocomment">' . $auto . '</span>';
1310 $comment = $pre . $link . $wgLang->getDirMark() . '<span dir="auto">' . $auto . $post . '</span>';
1318 static $commentContextTitle;
1319 static $commentLocal;
1322 * Formats wiki links and media links in text; all other wiki formatting
1325 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1326 * @param $comment String: text to format links in
1327 * @param $title Title|null An optional title object used to links to sections
1328 * @param $local Boolean: whether section links should refer to local page
1331 public static function formatLinksInComment( $comment, $title = null, $local = false ) {
1332 self
::$commentContextTitle = $title;
1333 self
::$commentLocal = $local;
1334 $html = preg_replace_callback(
1335 '/\[\[:?(.*?)(\|(.*?))*\]\]([^[]*)/',
1336 array( 'Linker', 'formatLinksInCommentCallback' ),
1338 self
::$commentContextTitle = null;
1339 self
::$commentLocal = null;
1347 protected static function formatLinksInCommentCallback( $match ) {
1350 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1351 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1353 $comment = $match[0];
1355 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1356 if ( strpos( $match[1], '%' ) !== false ) {
1357 $match[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $match[1] ) );
1360 # Handle link renaming [[foo|text]] will show link as "text"
1361 if ( $match[3] != "" ) {
1366 $submatch = array();
1368 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1369 # Media link; trail not supported.
1370 $linkRegexp = '/\[\[(.*?)\]\]/';
1371 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1373 $thelink = self
::makeMediaLinkObj( $title, $text );
1376 # Other kind of link
1377 if ( preg_match( $wgContLang->linkTrail(), $match[4], $submatch ) ) {
1378 $trail = $submatch[1];
1382 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1383 if ( isset( $match[1][0] ) && $match[1][0] == ':' )
1384 $match[1] = substr( $match[1], 1 );
1385 list( $inside, $trail ) = self
::splitTrail( $trail );
1388 $linkTarget = self
::normalizeSubpageLink( self
::$commentContextTitle,
1389 $match[1], $linkText );
1391 $target = Title
::newFromText( $linkTarget );
1393 if ( $target->getText() == '' && $target->getInterwiki() === ''
1394 && !self
::$commentLocal && self
::$commentContextTitle )
1396 $newTarget = clone ( self
::$commentContextTitle );
1397 $newTarget->setFragment( '#' . $target->getFragment() );
1398 $target = $newTarget;
1400 $thelink = self
::link(
1407 // If the link is still valid, go ahead and replace it in!
1408 $comment = preg_replace( $linkRegexp, StringUtils
::escapeRegexReplacement( $thelink ), $comment, 1 );
1415 * @param $contextTitle Title
1420 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1423 # :Foobar -- override special treatment of prefix (images, language links)
1424 # /Foobar -- convert to CurrentPage/Foobar
1425 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1426 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1427 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1429 wfProfileIn( __METHOD__
);
1430 $ret = $target; # default return value is no change
1432 # Some namespaces don't allow subpages,
1433 # so only perform processing if subpages are allowed
1434 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1435 $hash = strpos( $target, '#' );
1436 if ( $hash !== false ) {
1437 $suffix = substr( $target, $hash );
1438 $target = substr( $target, 0, $hash );
1443 $target = trim( $target );
1444 # Look at the first character
1445 if ( $target != '' && $target[0] === '/' ) {
1446 # / at end means we don't want the slash to be shown
1448 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1449 if ( $trailingSlashes ) {
1450 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1452 $noslash = substr( $target, 1 );
1455 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1456 if ( $text === '' ) {
1457 $text = $target . $suffix;
1458 } # this might be changed for ugliness reasons
1460 # check for .. subpage backlinks
1462 $nodotdot = $target;
1463 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1465 $nodotdot = substr( $nodotdot, 3 );
1467 if ( $dotdotcount > 0 ) {
1468 $exploded = explode( '/', $contextTitle->GetPrefixedText() );
1469 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1470 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1471 # / at the end means don't show full path
1472 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1473 $nodotdot = substr( $nodotdot, 0, -1 );
1474 if ( $text === '' ) {
1475 $text = $nodotdot . $suffix;
1478 $nodotdot = trim( $nodotdot );
1479 if ( $nodotdot != '' ) {
1480 $ret .= '/' . $nodotdot;
1488 wfProfileOut( __METHOD__
);
1493 * Wrap a comment in standard punctuation and formatting if
1494 * it's non-empty, otherwise return empty string.
1496 * @param $comment String
1497 * @param $title Mixed: Title object (to generate link to section in autocomment) or null
1498 * @param $local Boolean: whether section links should refer to local page
1502 public static function commentBlock( $comment, $title = null, $local = false ) {
1503 // '*' used to be the comment inserted by the software way back
1504 // in antiquity in case none was provided, here for backwards
1505 // compatability, acc. to brion -ævar
1506 if ( $comment == '' ||
$comment == '*' ) {
1509 $formatted = self
::formatComment( $comment, $title, $local );
1510 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1511 return " <span class=\"comment\">$formatted</span>";
1516 * Wrap and format the given revision's comment block, if the current
1517 * user is allowed to view it.
1519 * @param $rev Revision object
1520 * @param $local Boolean: whether section links should refer to local page
1521 * @param $isPublic Boolean: show only if all users can see it
1522 * @return String: HTML fragment
1524 public static function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1525 if ( $rev->getRawComment() == "" ) {
1528 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1529 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1530 } elseif ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1531 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1532 $rev->getTitle(), $local );
1534 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1536 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1537 return " <span class=\"history-deleted\">$block</span>";
1546 public static function formatRevisionSize( $size ) {
1548 $stxt = wfMessage( 'historyempty' )->escaped();
1550 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1551 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1553 return "<span class=\"history-size\">$stxt</span>";
1557 * Add another level to the Table of Contents
1561 public static function tocIndent() {
1566 * Finish one or more sublevels on the Table of Contents
1570 public static function tocUnindent( $level ) {
1571 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1575 * parameter level defines if we are on an indentation level
1579 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1580 $classes = "toclevel-$level";
1581 if ( $sectionIndex !== false ) {
1582 $classes .= " tocsection-$sectionIndex";
1584 return "\n<li class=\"$classes\"><a href=\"#" .
1585 $anchor . '"><span class="tocnumber">' .
1586 $tocnumber . '</span> <span class="toctext">' .
1587 $tocline . '</span></a>';
1591 * End a Table Of Contents line.
1592 * tocUnindent() will be used instead if we're ending a line below
1596 public static function tocLineEnd() {
1601 * Wraps the TOC in a table and provides the hide/collapse javascript.
1603 * @param $toc String: html of the Table Of Contents
1604 * @param $lang String|Language|false: Language for the toc title, defaults to user language
1605 * @return String: full html of the TOC
1607 public static function tocList( $toc, $lang = false ) {
1608 $lang = wfGetLangObj( $lang );
1609 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1612 '<table id="toc" class="toc"><tr><td>'
1613 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1615 . "</ul>\n</td></tr></table>\n";
1619 * Generate a table of contents from a section tree
1622 * @param $tree array Return value of ParserOutput::getSections()
1623 * @return String: HTML fragment
1625 public static function generateTOC( $tree ) {
1628 foreach ( $tree as $section ) {
1629 if ( $section['toclevel'] > $lastLevel )
1630 $toc .= self
::tocIndent();
1631 elseif ( $section['toclevel'] < $lastLevel )
1632 $toc .= self
::tocUnindent(
1633 $lastLevel - $section['toclevel'] );
1635 $toc .= self
::tocLineEnd();
1637 $toc .= self
::tocLine( $section['anchor'],
1638 $section['line'], $section['number'],
1639 $section['toclevel'], $section['index'] );
1640 $lastLevel = $section['toclevel'];
1642 $toc .= self
::tocLineEnd();
1643 return self
::tocList( $toc );
1647 * Create a headline for content
1649 * @param $level Integer: the level of the headline (1-6)
1650 * @param $attribs String: any attributes for the headline, starting with
1651 * a space and ending with '>'
1652 * This *must* be at least '>' for no attribs
1653 * @param $anchor String: the anchor to give the headline (the bit after the #)
1654 * @param $html String: html for the text of the header
1655 * @param $link String: HTML to add for the section edit link
1656 * @param $legacyAnchor Mixed: a second, optional anchor to give for
1657 * backward compatibility (false to omit)
1659 * @return String: HTML headline
1661 public static function makeHeadline( $level, $attribs, $anchor, $html, $link, $legacyAnchor = false ) {
1662 $ret = "<h$level$attribs"
1664 . " <span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1666 if ( $legacyAnchor !== false ) {
1667 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1673 * Split a link trail, return the "inside" portion and the remainder of the trail
1674 * as a two-element array
1677 static function splitTrail( $trail ) {
1679 $regex = $wgContLang->linkTrail();
1681 if ( $trail !== '' ) {
1683 if ( preg_match( $regex, $trail, $m ) ) {
1688 return array( $inside, $trail );
1692 * Generate a rollback link for a given revision. Currently it's the
1693 * caller's responsibility to ensure that the revision is the top one. If
1694 * it's not, of course, the user will get an error message.
1696 * If the calling page is called with the parameter &bot=1, all rollback
1697 * links also get that parameter. It causes the edit itself and the rollback
1698 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1699 * changes, so this allows sysops to combat a busy vandal without bothering
1702 * @param $rev Revision object
1703 * @param $context IContextSource context to use or null for the main context.
1706 public static function generateRollback( $rev, IContextSource
$context = null ) {
1707 if ( $context === null ) {
1708 $context = RequestContext
::getMain();
1711 return '<span class="mw-rollback-link">'
1712 . $context->msg( 'brackets' )->rawParams(
1713 self
::buildRollbackLink( $rev, $context ) )->plain()
1718 * Build a raw rollback link, useful for collections of "tool" links
1720 * @param $rev Revision object
1721 * @param $context IContextSource context to use or null for the main context.
1722 * @return String: HTML fragment
1724 public static function buildRollbackLink( $rev, IContextSource
$context = null ) {
1725 global $wgShowRollbackEditCount, $wgMiserMode;
1727 // To config which pages are effected by miser mode
1728 $disableRollbackEditCountSpecialPage = array( 'Recentchanges', 'Watchlist' );
1730 if ( $context === null ) {
1731 $context = RequestContext
::getMain();
1734 $title = $rev->getTitle();
1736 'action' => 'rollback',
1737 'from' => $rev->getUserText(),
1738 'token' => $context->getUser()->getEditToken( array( $title->getPrefixedText(), $rev->getUserText() ) ),
1740 if ( $context->getRequest()->getBool( 'bot' ) ) {
1741 $query['bot'] = '1';
1742 $query['hidediff'] = '1'; // bug 15999
1745 $disableRollbackEditCount = false;
1746 if( $wgMiserMode ) {
1747 foreach( $disableRollbackEditCountSpecialPage as $specialPage ) {
1748 if( $context->getTitle()->isSpecial( $specialPage ) ) {
1749 $disableRollbackEditCount = true;
1755 if( !$disableRollbackEditCount && is_int( $wgShowRollbackEditCount ) && $wgShowRollbackEditCount > 0 ) {
1756 $dbr = wfGetDB( DB_SLAVE
);
1758 // Up to the value of $wgShowRollbackEditCount revisions are counted
1759 $res = $dbr->select( 'revision',
1760 array( 'rev_id', 'rev_user_text' ),
1761 // $rev->getPage() returns null sometimes
1762 array( 'rev_page' => $rev->getTitle()->getArticleID() ),
1764 array( 'USE INDEX' => 'page_timestamp',
1765 'ORDER BY' => 'rev_timestamp DESC',
1766 'LIMIT' => $wgShowRollbackEditCount +
1 )
1770 while( $row = $dbr->fetchObject( $res ) ) {
1771 if( $rev->getUserText() != $row->rev_user_text
) {
1777 if( $editCount > $wgShowRollbackEditCount ) {
1778 $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )->numParams( $wgShowRollbackEditCount )->parse();
1780 $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1786 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1788 array( 'known', 'noclasses' )
1793 $context->msg( 'rollbacklink' )->escaped(),
1794 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1796 array( 'known', 'noclasses' )
1802 * Returns HTML for the "templates used on this page" list.
1804 * @param $templates Array of templates from Article::getUsedTemplate
1806 * @param $preview Boolean: whether this is for a preview
1807 * @param $section Boolean: whether this is for a section edit
1808 * @return String: HTML output
1810 public static function formatTemplates( $templates, $preview = false, $section = false ) {
1811 wfProfileIn( __METHOD__
);
1814 if ( count( $templates ) > 0 ) {
1815 # Do a batch existence check
1816 $batch = new LinkBatch
;
1817 foreach ( $templates as $title ) {
1818 $batch->addObj( $title );
1822 # Construct the HTML
1823 $outText = '<div class="mw-templatesUsedExplanation">';
1825 $outText .= wfMessage( 'templatesusedpreview' )->numParams( count( $templates ) )
1827 } elseif ( $section ) {
1828 $outText .= wfMessage( 'templatesusedsection' )->numParams( count( $templates ) )
1831 $outText .= wfMessage( 'templatesused' )->numParams( count( $templates ) )
1834 $outText .= "</div><ul>\n";
1836 usort( $templates, 'Title::compare' );
1837 foreach ( $templates as $titleObj ) {
1838 $r = $titleObj->getRestrictions( 'edit' );
1839 if ( in_array( 'sysop', $r ) ) {
1840 $protected = wfMessage( 'template-protected' )->parse();
1841 } elseif ( in_array( 'autoconfirmed', $r ) ) {
1842 $protected = wfMessage( 'template-semiprotected' )->parse();
1846 if ( $titleObj->quickUserCan( 'edit' ) ) {
1847 $editLink = self
::link(
1849 wfMessage( 'editlink' )->text(),
1851 array( 'action' => 'edit' )
1854 $editLink = self
::link(
1856 wfMessage( 'viewsourcelink' )->text(),
1858 array( 'action' => 'edit' )
1861 $outText .= '<li>' . self
::link( $titleObj ) . ' (' . $editLink . ') ' . $protected . '</li>';
1863 $outText .= '</ul>';
1865 wfProfileOut( __METHOD__
);
1870 * Returns HTML for the "hidden categories on this page" list.
1872 * @param $hiddencats Array of hidden categories from Article::getHiddenCategories
1874 * @return String: HTML output
1876 public static function formatHiddenCategories( $hiddencats ) {
1877 wfProfileIn( __METHOD__
);
1880 if ( count( $hiddencats ) > 0 ) {
1881 # Construct the HTML
1882 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1883 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
1884 $outText .= "</div><ul>\n";
1886 foreach ( $hiddencats as $titleObj ) {
1887 $outText .= '<li>' . self
::link( $titleObj, null, array(), array(), 'known' ) . "</li>\n"; # If it's hidden, it must exist - no need to check with a LinkBatch
1889 $outText .= '</ul>';
1891 wfProfileOut( __METHOD__
);
1896 * Format a size in bytes for output, using an appropriate
1897 * unit (B, KB, MB or GB) according to the magnitude in question
1899 * @param $size int Size to format
1902 public static function formatSize( $size ) {
1904 return htmlspecialchars( $wgLang->formatSize( $size ) );
1908 * Given the id of an interface element, constructs the appropriate title
1909 * attribute from the system messages. (Note, this is usually the id but
1910 * isn't always, because sometimes the accesskey needs to go on a different
1911 * element than the id, for reverse-compatibility, etc.)
1913 * @param $name String: id of the element, minus prefixes.
1914 * @param $options Mixed: null or the string 'withaccess' to add an access-
1916 * @return String: contents of the title attribute (which you must HTML-
1917 * escape), or false for no title attribute
1919 public static function titleAttrib( $name, $options = null ) {
1920 wfProfileIn( __METHOD__
);
1922 $message = wfMessage( "tooltip-$name" );
1924 if ( !$message->exists() ) {
1927 $tooltip = $message->text();
1928 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1929 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1930 # Message equal to '-' means suppress it.
1931 if ( $tooltip == '-' ) {
1936 if ( $options == 'withaccess' ) {
1937 $accesskey = self
::accesskey( $name );
1938 if ( $accesskey !== false ) {
1939 if ( $tooltip === false ||
$tooltip === '' ) {
1940 $tooltip = "[$accesskey]";
1942 $tooltip .= " [$accesskey]";
1947 wfProfileOut( __METHOD__
);
1951 static $accesskeycache;
1954 * Given the id of an interface element, constructs the appropriate
1955 * accesskey attribute from the system messages. (Note, this is usually
1956 * the id but isn't always, because sometimes the accesskey needs to go on
1957 * a different element than the id, for reverse-compatibility, etc.)
1959 * @param $name String: id of the element, minus prefixes.
1960 * @return String: contents of the accesskey attribute (which you must HTML-
1961 * escape), or false for no accesskey attribute
1963 public static function accesskey( $name ) {
1964 if ( isset( self
::$accesskeycache[$name] ) ) {
1965 return self
::$accesskeycache[$name];
1967 wfProfileIn( __METHOD__
);
1969 $message = wfMessage( "accesskey-$name" );
1971 if ( !$message->exists() ) {
1974 $accesskey = $message->plain();
1975 if ( $accesskey === '' ||
$accesskey === '-' ) {
1976 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
1977 # attribute, but this is broken for accesskey: that might be a useful
1983 wfProfileOut( __METHOD__
);
1984 return self
::$accesskeycache[$name] = $accesskey;
1988 * Get a revision-deletion link, or disabled link, or nothing, depending
1989 * on user permissions & the settings on the revision.
1991 * Will use forward-compatible revision ID in the Special:RevDelete link
1992 * if possible, otherwise the timestamp-based ID which may break after
1996 * @param Revision $rev
1997 * @param Revision $title
1998 * @return string HTML fragment
2000 public static function getRevDeleteLink( User
$user, Revision
$rev, Title
$title ) {
2001 $canHide = $user->isAllowed( 'deleterevision' );
2002 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2006 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
2007 return Linker
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2009 if ( $rev->getId() ) {
2010 // RevDelete links using revision ID are stable across
2011 // page deletion and undeletion; use when possible.
2013 'type' => 'revision',
2014 'target' => $title->getPrefixedDBkey(),
2015 'ids' => $rev->getId()
2018 // Older deleted entries didn't save a revision ID.
2019 // We have to refer to these by timestamp, ick!
2021 'type' => 'archive',
2022 'target' => $title->getPrefixedDBkey(),
2023 'ids' => $rev->getTimestamp()
2026 return Linker
::revDeleteLink( $query,
2027 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
2032 * Creates a (show/hide) link for deleting revisions/log entries
2034 * @param $query Array: query parameters to be passed to link()
2035 * @param $restricted Boolean: set to true to use a "<strong>" instead of a "<span>"
2036 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2038 * @return String: HTML "<a>" link to Special:Revisiondelete, wrapped in a
2039 * span to allow for customization of appearance with CSS
2041 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
2042 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
2043 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2044 $html = wfMessage( $msgKey )->escaped();
2045 $tag = $restricted ?
'strong' : 'span';
2046 $link = self
::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
2047 return Xml
::tags( $tag, array( 'class' => 'mw-revdelundel-link' ), wfMessage( 'parentheses' )->rawParams( $link )->escaped() );
2051 * Creates a dead (show/hide) link for deleting revisions/log entries
2053 * @param $delete Boolean: set to true to use (show/hide) rather than (show)
2055 * @return string HTML text wrapped in a span to allow for customization
2056 * of appearance with CSS
2058 public static function revDeleteLinkDisabled( $delete = true ) {
2059 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2060 $html = wfMessage( $msgKey )->escaped();
2061 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2062 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), $htmlParentheses );
2065 /* Deprecated methods */
2068 * @deprecated since 1.16 Use link()
2070 * This function is a shortcut to makeBrokenLinkObj(Title::newFromText($title),...). Do not call
2071 * it if you already have a title object handy. See makeBrokenLinkObj for further documentation.
2073 * @param $title String: The text of the title
2074 * @param $text String: Link text
2075 * @param $query String: Optional query part
2076 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
2077 * be included in the link text. Other characters will be appended after
2078 * the end of the link.
2081 static function makeBrokenLink( $title, $text = '', $query = '', $trail = '' ) {
2082 wfDeprecated( __METHOD__
, '1.16' );
2084 $nt = Title
::newFromText( $title );
2085 if ( $nt instanceof Title
) {
2086 return self
::makeBrokenLinkObj( $nt, $text, $query, $trail );
2088 wfDebug( 'Invalid title passed to self::makeBrokenLink(): "' . $title . "\"\n" );
2089 return $text == '' ?
$title : $text;
2094 * @deprecated since 1.16 Use link()
2096 * Make a link for a title which may or may not be in the database. If you need to
2097 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
2098 * call to this will result in a DB query.
2100 * @param $nt Title: the title object to make the link from, e.g. from
2101 * Title::newFromText.
2102 * @param $text String: link text
2103 * @param $query String: optional query part
2104 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2105 * be included in the link text. Other characters will be appended after
2106 * the end of the link.
2107 * @param $prefix String: optional prefix. As trail, only before instead of after.
2110 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
2111 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
2113 wfProfileIn( __METHOD__
);
2114 $query = wfCgiToArray( $query );
2115 list( $inside, $trail ) = self
::splitTrail( $trail );
2116 if ( $text === '' ) {
2117 $text = self
::linkText( $nt );
2120 $ret = self
::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
2122 wfProfileOut( __METHOD__
);
2127 * @deprecated since 1.16 Use link()
2129 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
2130 * it doesn't have to do a database query. It's also valid for interwiki titles and special
2133 * @param $title Title object of target page
2134 * @param $text String: text to replace the title
2135 * @param $query String: link target
2136 * @param $trail String: text after link
2137 * @param $prefix String: text before link text
2138 * @param $aprops String: extra attributes to the a-element
2139 * @param $style String: style to apply - if empty, use getInternalLinkAttributesObj instead
2140 * @return string the a-element
2142 static function makeKnownLinkObj(
2143 $title, $text = '', $query = '', $trail = '', $prefix = '' , $aprops = '', $style = ''
2145 # wfDeprecated( __METHOD__, '1.16' ); // See r105985 and it's revert. Somewhere still used.
2147 wfProfileIn( __METHOD__
);
2149 if ( $text == '' ) {
2150 $text = self
::linkText( $title );
2152 $attribs = Sanitizer
::mergeAttributes(
2153 Sanitizer
::decodeTagAttributes( $aprops ),
2154 Sanitizer
::decodeTagAttributes( $style )
2156 $query = wfCgiToArray( $query );
2157 list( $inside, $trail ) = self
::splitTrail( $trail );
2159 $ret = self
::link( $title, "$prefix$text$inside", $attribs, $query,
2160 array( 'known', 'noclasses' ) ) . $trail;
2162 wfProfileOut( __METHOD__
);
2167 * @deprecated since 1.16 Use link()
2169 * Make a red link to the edit page of a given title.
2171 * @param $title Title object of the target page
2172 * @param $text String: Link text
2173 * @param $query String: Optional query part
2174 * @param $trail String: Optional trail. Alphabetic characters at the start of this string will
2175 * be included in the link text. Other characters will be appended after
2176 * the end of the link.
2177 * @param $prefix String: Optional prefix
2180 static function makeBrokenLinkObj( $title, $text = '', $query = '', $trail = '', $prefix = '' ) {
2181 wfDeprecated( __METHOD__
, '1.16' );
2183 wfProfileIn( __METHOD__
);
2185 list( $inside, $trail ) = self
::splitTrail( $trail );
2186 if ( $text === '' ) {
2187 $text = self
::linkText( $title );
2190 $ret = self
::link( $title, "$prefix$text$inside", array(),
2191 wfCgiToArray( $query ), 'broken' ) . $trail;
2193 wfProfileOut( __METHOD__
);
2198 * @deprecated since 1.16 Use link()
2200 * Make a coloured link.
2202 * @param $nt Title object of the target page
2203 * @param $colour Integer: colour of the link
2204 * @param $text String: link text
2205 * @param $query String: optional query part
2206 * @param $trail String: optional trail. Alphabetic characters at the start of this string will
2207 * be included in the link text. Other characters will be appended after
2208 * the end of the link.
2209 * @param $prefix String: Optional prefix
2212 static function makeColouredLinkObj( $nt, $colour, $text = '', $query = '', $trail = '', $prefix = '' ) {
2213 wfDeprecated( __METHOD__
, '1.16' );
2215 if ( $colour != '' ) {
2216 $style = self
::getInternalLinkAttributesObj( $nt, $text, $colour );
2220 return self
::makeKnownLinkObj( $nt, $text, $query, $trail, $prefix, '', $style );
2224 * Returns the attributes for the tooltip and access key.
2227 public static function tooltipAndAccesskeyAttribs( $name ) {
2228 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2229 # no attribute" instead of "output '' as value for attribute", this
2230 # would be three lines.
2232 'title' => self
::titleAttrib( $name, 'withaccess' ),
2233 'accesskey' => self
::accesskey( $name )
2235 if ( $attribs['title'] === false ) {
2236 unset( $attribs['title'] );
2238 if ( $attribs['accesskey'] === false ) {
2239 unset( $attribs['accesskey'] );
2245 * Returns raw bits of HTML, use titleAttrib()
2246 * @return null|string
2248 public static function tooltip( $name, $options = null ) {
2249 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2250 # no attribute" instead of "output '' as value for attribute", this
2251 # would be two lines.
2252 $tooltip = self
::titleAttrib( $name, $options );
2253 if ( $tooltip === false ) {
2256 return Xml
::expandAttributes( array(
2268 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2269 * into static calls to the new Linker for backwards compatibility.
2271 * @param $fname String Name of called method
2272 * @param $args Array Arguments to the method
2275 public function __call( $fname, $args ) {
2276 return call_user_func_array( array( 'Linker', $fname ), $args );