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 $defaults['title'] = wfMessage( 'red-link-title', $target->getPrefixedText() )->text();
352 # Finally, merge the custom attribs with the default ones, and iterate
353 # over that, deleting all "false" attributes.
355 $merged = Sanitizer
::mergeAttributes( $defaults, $attribs );
356 foreach ( $merged as $key => $val ) {
357 # A false value suppresses the attribute, and we don't want the
358 # href attribute to be overridden.
359 if ( $key != 'href' && $val !== false ) {
367 * Default text of the links to the Title $target
369 * @param Title $target
373 private static function linkText( $target ) {
374 if ( !$target instanceof Title
) {
375 wfWarn( __METHOD__
. ': Requires $target to be a Title object.' );
378 // If the target is just a fragment, with no title, we return the fragment
379 // text. Otherwise, we return the title text itself.
380 if ( $target->getPrefixedText() === '' && $target->hasFragment() ) {
381 return htmlspecialchars( $target->getFragment() );
384 return htmlspecialchars( $target->getPrefixedText() );
388 * Make appropriate markup for a link to the current article. This is
389 * currently rendered as the bold link text. The calling sequence is the
390 * same as the other make*LinkObj static functions, despite $query not
394 * @param string $html [optional]
395 * @param string $query [optional]
396 * @param string $trail [optional]
397 * @param string $prefix [optional]
401 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
402 $ret = "<strong class=\"selflink\">{$prefix}{$html}</strong>{$trail}";
403 if ( !Hooks
::run( 'SelfLinkBegin', array( $nt, &$html, &$trail, &$prefix, &$ret ) ) ) {
408 $html = htmlspecialchars( $nt->getPrefixedText() );
410 list( $inside, $trail ) = self
::splitTrail( $trail );
411 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
415 * Get a message saying that an invalid title was encountered.
416 * This should be called after a method like Title::makeTitleSafe() returned
417 * a value indicating that the title object is invalid.
419 * @param IContextSource $context Context to use to get the messages
420 * @param int $namespace Namespace number
421 * @param string $title Text of the title, without the namespace part
424 public static function getInvalidTitleDescription( IContextSource
$context, $namespace, $title ) {
427 // First we check whether the namespace exists or not.
428 if ( MWNamespace
::exists( $namespace ) ) {
429 if ( $namespace == NS_MAIN
) {
430 $name = $context->msg( 'blanknamespace' )->text();
432 $name = $wgContLang->getFormattedNsText( $namespace );
434 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
436 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
441 * @param Title $title
444 static function normaliseSpecialPage( Title
$title ) {
445 if ( $title->isSpecialPage() ) {
446 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $title->getDBkey() );
450 $ret = SpecialPage
::getTitleFor( $name, $subpage, $title->getFragment() );
458 * Returns the filename part of an url.
459 * Used as alternative text for external images.
465 private static function fnamePart( $url ) {
466 $basename = strrchr( $url, '/' );
467 if ( false === $basename ) {
470 $basename = substr( $basename, 1 );
476 * Return the code for images which were added via external links,
477 * via Parser::maybeMakeExternalImage().
484 public static function makeExternalImage( $url, $alt = '' ) {
486 $alt = self
::fnamePart( $url );
489 $success = Hooks
::run( 'LinkerMakeExternalImage', array( &$url, &$alt, &$img ) );
491 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
492 . "with url {$url} and alt text {$alt} to {$img}\n", true );
495 return Html
::element( 'img',
502 * Given parameters derived from [[Image:Foo|options...]], generate the
503 * HTML that that syntax inserts in the page.
505 * @param Parser $parser
506 * @param Title $title Title object of the file (not the currently viewed page)
507 * @param File $file File object, or false if it doesn't exist
508 * @param array $frameParams Associative array of parameters external to the media handler.
509 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
510 * will often be false.
511 * thumbnail If present, downscale and frame
512 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
513 * framed Shows image in original size in a frame
514 * frameless Downscale but don't frame
515 * upright If present, tweak default sizes for portrait orientation
516 * upright_factor Fudge factor for "upright" tweak (default 0.75)
517 * border If present, show a border around the image
518 * align Horizontal alignment (left, right, center, none)
519 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
520 * bottom, text-bottom)
521 * alt Alternate text for image (i.e. alt attribute). Plain text.
522 * class HTML for image classes. Plain text.
523 * caption HTML for image caption.
524 * link-url URL to link to
525 * link-title Title object to link to
526 * link-target Value for the target attribute, only with link-url
527 * no-link Boolean, suppress description link
529 * @param array $handlerParams Associative array of media handler parameters, to be passed
530 * to transform(). Typical keys are "width" and "page".
531 * @param string|bool $time Timestamp of the file, set as false for current
532 * @param string $query Query params for desc url
533 * @param int|null $widthOption Used by the parser to remember the user preference thumbnailsize
535 * @return string HTML for an image, with links, wrappers, etc.
537 public static function makeImageLink( Parser
$parser, Title
$title,
538 $file, $frameParams = array(), $handlerParams = array(), $time = false,
539 $query = "", $widthOption = null
542 $dummy = new DummyLinker
;
543 if ( !Hooks
::run( 'ImageBeforeProduceHTML', array( &$dummy, &$title,
544 &$file, &$frameParams, &$handlerParams, &$time, &$res ) ) ) {
548 if ( $file && !$file->allowInlineDisplay() ) {
549 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
550 return self
::link( $title );
555 $hp =& $handlerParams;
557 // Clean up parameters
558 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
559 if ( !isset( $fp['align'] ) ) {
562 if ( !isset( $fp['alt'] ) ) {
565 if ( !isset( $fp['title'] ) ) {
568 if ( !isset( $fp['class'] ) ) {
572 $prefix = $postfix = '';
574 if ( 'center' == $fp['align'] ) {
575 $prefix = '<div class="center">';
577 $fp['align'] = 'none';
579 if ( $file && !isset( $hp['width'] ) ) {
580 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
581 // If its a vector image, and user only specifies height
582 // we don't want it to be limited by its "normal" width.
583 global $wgSVGMaxSize;
584 $hp['width'] = $wgSVGMaxSize;
586 $hp['width'] = $file->getWidth( $page );
589 if ( isset( $fp['thumbnail'] )
590 ||
isset( $fp['manualthumb'] )
591 ||
isset( $fp['framed'] )
592 ||
isset( $fp['frameless'] )
595 global $wgThumbLimits, $wgThumbUpright;
597 if ( $widthOption === null ||
!isset( $wgThumbLimits[$widthOption] ) ) {
598 $widthOption = User
::getDefaultOption( 'thumbsize' );
601 // Reduce width for upright images when parameter 'upright' is used
602 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
603 $fp['upright'] = $wgThumbUpright;
606 // For caching health: If width scaled down due to upright
607 // parameter, round to full __0 pixel to avoid the creation of a
608 // lot of odd thumbs.
609 $prefWidth = isset( $fp['upright'] ) ?
610 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
611 $wgThumbLimits[$widthOption];
613 // Use width which is smaller: real image width or user preference width
614 // Unless image is scalable vector.
615 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
616 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
617 $hp['width'] = $prefWidth;
622 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
623 # Create a thumbnail. Alignment depends on the writing direction of
624 # the page content language (right-aligned for LTR languages,
625 # left-aligned for RTL languages)
626 # If a thumbnail width has not been provided, it is set
627 # to the default user option as specified in Language*.php
628 if ( $fp['align'] == '' ) {
629 $fp['align'] = $parser->getTargetLanguage()->alignEnd();
631 return $prefix . self
::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
634 if ( $file && isset( $fp['frameless'] ) ) {
635 $srcWidth = $file->getWidth( $page );
636 # For "frameless" option: do not present an image bigger than the
637 # source (for bitmap-style images). This is the same behavior as the
638 # "thumb" option does it already.
639 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
640 $hp['width'] = $srcWidth;
644 if ( $file && isset( $hp['width'] ) ) {
645 # Create a resized image, without the additional thumbnail features
646 $thumb = $file->transform( $hp );
652 $s = self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
654 self
::processResponsiveImages( $file, $thumb, $hp );
657 'title' => $fp['title'],
658 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false,
659 'img-class' => $fp['class'] );
660 if ( isset( $fp['border'] ) ) {
661 $params['img-class'] .= ( $params['img-class'] !== '' ?
' ' : '' ) . 'thumbborder';
663 $params = self
::getImageLinkMTOParams( $fp, $query, $parser ) +
$params;
665 $s = $thumb->toHtml( $params );
667 if ( $fp['align'] != '' ) {
668 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
670 return str_replace( "\n", ' ', $prefix . $s . $postfix );
674 * See makeImageLink()
675 * When this function is removed, remove if( $parser instanceof Parser ) check there too
676 * @deprecated since 1.20
678 public static function makeImageLink2( Title
$title, $file, $frameParams = array(),
679 $handlerParams = array(), $time = false, $query = "", $widthOption = null ) {
680 return self
::makeImageLink( null, $title, $file, $frameParams,
681 $handlerParams, $time, $query, $widthOption );
685 * Get the link parameters for MediaTransformOutput::toHtml() from given
686 * frame parameters supplied by the Parser.
687 * @param array $frameParams The frame parameters
688 * @param string $query An optional query string to add to description page links
689 * @param Parser|null $parser
692 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
693 $mtoParams = array();
694 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
695 $mtoParams['custom-url-link'] = $frameParams['link-url'];
696 if ( isset( $frameParams['link-target'] ) ) {
697 $mtoParams['custom-target-link'] = $frameParams['link-target'];
700 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
701 foreach ( $extLinkAttrs as $name => $val ) {
702 // Currently could include 'rel' and 'target'
703 $mtoParams['parser-extlink-' . $name] = $val;
706 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
707 $mtoParams['custom-title-link'] = self
::normaliseSpecialPage( $frameParams['link-title'] );
708 } elseif ( !empty( $frameParams['no-link'] ) ) {
711 $mtoParams['desc-link'] = true;
712 $mtoParams['desc-query'] = $query;
718 * Make HTML for a thumbnail including image, border and caption
719 * @param Title $title
720 * @param File|bool $file File object or false if it doesn't exist
721 * @param string $label
723 * @param string $align
724 * @param array $params
725 * @param bool $framed
726 * @param string $manualthumb
729 public static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt,
730 $align = 'right', $params = array(), $framed = false, $manualthumb = ""
732 $frameParams = array(
738 $frameParams['framed'] = true;
740 if ( $manualthumb ) {
741 $frameParams['manualthumb'] = $manualthumb;
743 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
747 * @param Title $title
749 * @param array $frameParams
750 * @param array $handlerParams
752 * @param string $query
755 public static function makeThumbLink2( Title
$title, $file, $frameParams = array(),
756 $handlerParams = array(), $time = false, $query = ""
758 $exists = $file && $file->exists();
762 $hp =& $handlerParams;
764 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
765 if ( !isset( $fp['align'] ) ) {
766 $fp['align'] = 'right';
768 if ( !isset( $fp['alt'] ) ) {
771 if ( !isset( $fp['title'] ) ) {
774 if ( !isset( $fp['caption'] ) ) {
778 if ( empty( $hp['width'] ) ) {
779 // Reduce width for upright images when parameter 'upright' is used
780 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
784 $manualthumb = false;
787 $outerWidth = $hp['width'] +
2;
789 if ( isset( $fp['manualthumb'] ) ) {
790 # Use manually specified thumbnail
791 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
792 if ( $manual_title ) {
793 $manual_img = wfFindFile( $manual_title );
795 $thumb = $manual_img->getUnscaledThumb( $hp );
801 } elseif ( isset( $fp['framed'] ) ) {
802 // Use image dimensions, don't scale
803 $thumb = $file->getUnscaledThumb( $hp );
806 # Do not present an image bigger than the source, for bitmap-style images
807 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
808 $srcWidth = $file->getWidth( $page );
809 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
810 $hp['width'] = $srcWidth;
812 $thumb = $file->transform( $hp );
816 $outerWidth = $thumb->getWidth() +
2;
818 $outerWidth = $hp['width'] +
2;
822 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
823 # So we don't need to pass it here in $query. However, the URL for the
824 # zoom icon still needs it, so we make a unique query for it. See bug 14771
825 $url = $title->getLocalURL( $query );
827 $url = wfAppendQuery( $url, array( 'page' => $page ) );
830 && !isset( $fp['link-title'] )
831 && !isset( $fp['link-url'] )
832 && !isset( $fp['no-link'] ) ) {
833 $fp['link-url'] = $url;
836 $s = "<div class=\"thumb t{$fp['align']}\">"
837 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
840 $s .= self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
842 } elseif ( !$thumb ) {
843 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
846 if ( !$noscale && !$manualthumb ) {
847 self
::processResponsiveImages( $file, $thumb, $hp );
851 'title' => $fp['title'],
852 'img-class' => ( isset( $fp['class'] ) && $fp['class'] !== ''
854 : '' ) . 'thumbimage'
856 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
857 $s .= $thumb->toHtml( $params );
858 if ( isset( $fp['framed'] ) ) {
861 $zoomIcon = Html
::rawElement( 'div', array( 'class' => 'magnify' ),
862 Html
::rawElement( 'a', array(
864 'class' => 'internal',
865 'title' => wfMessage( 'thumbnail-more' )->text() ),
869 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
870 return str_replace( "\n", ' ', $s );
874 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
878 * @param MediaTransformOutput $thumb
879 * @param array $hp Image parameters
881 public static function processResponsiveImages( $file, $thumb, $hp ) {
882 global $wgResponsiveImages;
883 if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
885 $hp15['width'] = round( $hp['width'] * 1.5 );
887 $hp20['width'] = $hp['width'] * 2;
888 if ( isset( $hp['height'] ) ) {
889 $hp15['height'] = round( $hp['height'] * 1.5 );
890 $hp20['height'] = $hp['height'] * 2;
893 $thumb15 = $file->transform( $hp15 );
894 $thumb20 = $file->transform( $hp20 );
895 if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
896 $thumb->responsiveUrls
['1.5'] = $thumb15->getUrl();
898 if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
899 $thumb->responsiveUrls
['2'] = $thumb20->getUrl();
905 * Make a "broken" link to an image
907 * @param Title $title
908 * @param string $label Link label (plain text)
909 * @param string $query Query string
910 * @param string $unused1 Unused parameter kept for b/c
911 * @param string $unused2 Unused parameter kept for b/c
912 * @param bool $time A file of a certain timestamp was requested
915 public static function makeBrokenImageLinkObj( $title, $label = '',
916 $query = '', $unused1 = '', $unused2 = '', $time = false
918 if ( !$title instanceof Title
) {
919 wfWarn( __METHOD__
. ': Requires $title to be a Title object.' );
920 return "<!-- ERROR -->" . htmlspecialchars( $label );
923 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
924 if ( $label == '' ) {
925 $label = $title->getPrefixedText();
927 $encLabel = htmlspecialchars( $label );
928 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
930 if ( ( $wgUploadMissingFileUrl ||
$wgUploadNavigationUrl ||
$wgEnableUploads )
933 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
936 return self
::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
939 $href = self
::getUploadUrl( $title, $query );
941 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
942 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
946 return self
::linkKnown( $title, $encLabel, array(), wfCgiToArray( $query ) );
950 * Get the URL to upload a certain file
952 * @param Title $destFile Title object of the file to upload
953 * @param string $query Urlencoded query string to prepend
954 * @return string Urlencoded URL
956 protected static function getUploadUrl( $destFile, $query = '' ) {
957 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
958 $q = 'wpDestFile=' . $destFile->getPartialURL();
959 if ( $query != '' ) {
963 if ( $wgUploadMissingFileUrl ) {
964 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
965 } elseif ( $wgUploadNavigationUrl ) {
966 return wfAppendQuery( $wgUploadNavigationUrl, $q );
968 $upload = SpecialPage
::getTitleFor( 'Upload' );
969 return $upload->getLocalURL( $q );
974 * Create a direct link to a given uploaded file.
976 * @param Title $title
977 * @param string $html Pre-sanitized HTML
978 * @param string $time MW timestamp of file creation time
979 * @return string HTML
981 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
982 $img = wfFindFile( $title, array( 'time' => $time ) );
983 return self
::makeMediaLinkFile( $title, $img, $html );
987 * Create a direct link to a given uploaded file.
988 * This will make a broken link if $file is false.
990 * @param Title $title
991 * @param File|bool $file File object or false
992 * @param string $html Pre-sanitized HTML
993 * @return string HTML
995 * @todo Handle invalid or missing images better.
997 public static function makeMediaLinkFile( Title
$title, $file, $html = '' ) {
998 if ( $file && $file->exists() ) {
999 $url = $file->getURL();
1000 $class = 'internal';
1002 $url = self
::getUploadUrl( $title );
1006 $alt = $title->getText();
1007 if ( $html == '' ) {
1018 if ( !Hooks
::run( 'LinkerMakeMediaLinkFile',
1019 array( $title, $file, &$html, &$attribs, &$ret ) ) ) {
1020 wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
1021 . "with url {$url} and text {$html} to {$ret}\n", true );
1025 return Html
::rawElement( 'a', $attribs, $html );
1029 * Make a link to a special page given its name and, optionally,
1030 * a message key from the link text.
1031 * Usage example: Linker::specialLink( 'Recentchanges' )
1033 * @param string $name
1034 * @param string $key
1037 public static function specialLink( $name, $key = '' ) {
1039 $key = strtolower( $name );
1042 return self
::linkKnown( SpecialPage
::getTitleFor( $name ), wfMessage( $key )->text() );
1046 * Make an external link
1047 * @param string $url URL to link to
1048 * @param string $text Text of link
1049 * @param bool $escape Do we escape the link text?
1050 * @param string $linktype Type of external link. Gets added to the classes
1051 * @param array $attribs Array of extra attributes to <a>
1052 * @param Title|null $title Title object used for title specific link attributes
1055 public static function makeExternalLink( $url, $text, $escape = true,
1056 $linktype = '', $attribs = array(), $title = null
1059 $class = "external";
1061 $class .= " $linktype";
1063 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
1064 $class .= " {$attribs['class']}";
1066 $attribs['class'] = $class;
1069 $text = htmlspecialchars( $text );
1075 $attribs['rel'] = Parser
::getExternalLinkRel( $url, $title );
1077 $success = Hooks
::run( 'LinkerMakeExternalLink',
1078 array( &$url, &$text, &$link, &$attribs, $linktype ) );
1080 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
1081 . "with url {$url} and text {$text} to {$link}\n", true );
1084 $attribs['href'] = $url;
1085 return Html
::rawElement( 'a', $attribs, $text );
1089 * Make user link (or user contributions for unregistered users)
1090 * @param int $userId User id in database.
1091 * @param string $userName User name in database.
1092 * @param string $altUserName Text to display instead of the user name (optional)
1093 * @return string HTML fragment
1094 * @since 1.19 Method exists for a long time. $altUserName was added in 1.19.
1096 public static function userLink( $userId, $userName, $altUserName = false ) {
1097 $classes = 'mw-userlink';
1098 if ( $userId == 0 ) {
1099 $page = SpecialPage
::getTitleFor( 'Contributions', $userName );
1100 if ( $altUserName === false ) {
1101 $altUserName = IP
::prettifyIP( $userName );
1103 $classes .= ' mw-anonuserlink'; // Separate link class for anons (bug 43179)
1105 $page = Title
::makeTitle( NS_USER
, $userName );
1110 htmlspecialchars( $altUserName !== false ?
$altUserName : $userName ),
1111 array( 'class' => $classes )
1116 * Generate standard user tool links (talk, contributions, block link, etc.)
1118 * @param int $userId User identifier
1119 * @param string $userText User name or IP address
1120 * @param bool $redContribsWhenNoEdits Should the contributions link be
1121 * red if the user has no edits?
1122 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
1123 * and Linker::TOOL_LINKS_EMAIL).
1124 * @param int $edits User edit count (optional, for performance)
1125 * @return string HTML fragment
1127 public static function userToolLinks(
1128 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1130 global $wgUser, $wgDisableAnonTalk, $wgLang;
1131 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1132 $blockable = !( $flags & self
::TOOL_LINKS_NOBLOCK
);
1133 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
&& $userId;
1137 $items[] = self
::userTalkLink( $userId, $userText );
1140 // check if the user has an edit
1142 if ( $redContribsWhenNoEdits ) {
1143 if ( intval( $edits ) === 0 && $edits !== 0 ) {
1144 $user = User
::newFromId( $userId );
1145 $edits = $user->getEditCount();
1147 if ( $edits === 0 ) {
1148 $attribs['class'] = 'new';
1151 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
1153 $items[] = self
::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1155 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1156 $items[] = self
::blockLink( $userId, $userText );
1159 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1160 $items[] = self
::emailLink( $userId, $userText );
1163 Hooks
::run( 'UserToolLinksEdit', array( $userId, $userText, &$items ) );
1166 return wfMessage( 'word-separator' )->escaped()
1167 . '<span class="mw-usertoollinks">'
1168 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1176 * Alias for userToolLinks( $userId, $userText, true );
1177 * @param int $userId User identifier
1178 * @param string $userText User name or IP address
1179 * @param int $edits User edit count (optional, for performance)
1182 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1183 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
1187 * @param int $userId User id in database.
1188 * @param string $userText User name in database.
1189 * @return string HTML fragment with user talk link
1191 public static function userTalkLink( $userId, $userText ) {
1192 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
1193 $userTalkLink = self
::link( $userTalkPage, wfMessage( 'talkpagelinktext' )->escaped() );
1194 return $userTalkLink;
1198 * @param int $userId Userid
1199 * @param string $userText User name in database.
1200 * @return string HTML fragment with block link
1202 public static function blockLink( $userId, $userText ) {
1203 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1204 $blockLink = self
::link( $blockPage, wfMessage( 'blocklink' )->escaped() );
1209 * @param int $userId Userid
1210 * @param string $userText User name in database.
1211 * @return string HTML fragment with e-mail user link
1213 public static function emailLink( $userId, $userText ) {
1214 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1215 $emailLink = self
::link( $emailPage, wfMessage( 'emaillink' )->escaped() );
1220 * Generate a user link if the current user is allowed to view it
1221 * @param Revision $rev
1222 * @param bool $isPublic Show only if all users can see it
1223 * @return string HTML fragment
1225 public static function revUserLink( $rev, $isPublic = false ) {
1226 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1227 $link = wfMessage( 'rev-deleted-user' )->escaped();
1228 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1229 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1230 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1232 $link = wfMessage( 'rev-deleted-user' )->escaped();
1234 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1235 return '<span class="history-deleted">' . $link . '</span>';
1241 * Generate a user tool link cluster if the current user is allowed to view it
1242 * @param Revision $rev
1243 * @param bool $isPublic Show only if all users can see it
1244 * @return string HTML
1246 public static function revUserTools( $rev, $isPublic = false ) {
1247 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1248 $link = wfMessage( 'rev-deleted-user' )->escaped();
1249 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1250 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1251 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1252 $link = self
::userLink( $userId, $userText )
1253 . self
::userToolLinks( $userId, $userText );
1255 $link = wfMessage( 'rev-deleted-user' )->escaped();
1257 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1258 return ' <span class="history-deleted">' . $link . '</span>';
1264 * This function is called by all recent changes variants, by the page history,
1265 * and by the user contributions list. It is responsible for formatting edit
1266 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1267 * auto-generated comments (from section editing) and formats [[wikilinks]].
1269 * @author Erik Moeller <moeller@scireview.de>
1271 * Note: there's not always a title to pass to this function.
1272 * Since you can't set a default parameter for a reference, I've turned it
1273 * temporarily to a value pass. Should be adjusted further. --brion
1275 * @param string $comment
1276 * @param Title|null $title Title object (to generate link to the section in autocomment)
1278 * @param bool $local Whether section links should refer to local page
1279 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1280 * For use with external changes.
1282 * @return mixed|string
1284 public static function formatComment(
1285 $comment, $title = null, $local = false, $wikiId = null
1287 # Sanitize text a bit:
1288 $comment = str_replace( "\n", " ", $comment );
1289 # Allow HTML entities (for bug 13815)
1290 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1292 # Render autocomments and make links:
1293 $comment = self
::formatAutocomments( $comment, $title, $local, $wikiId );
1294 $comment = self
::formatLinksInComment( $comment, $title, $local, $wikiId );
1300 * Converts autogenerated comments in edit summaries into section links.
1302 * The pattern for autogen comments is / * foo * /, which makes for
1304 * We look for all comments, match any text before and after the comment,
1305 * add a separator where needed and format the comment itself with CSS
1306 * Called by Linker::formatComment.
1308 * @param string $comment Comment text
1309 * @param Title|null $title An optional title object used to links to sections
1310 * @param bool $local Whether section links should refer to local page
1311 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1312 * as used by WikiMap.
1314 * @return string Formatted comment (wikitext)
1316 private static function formatAutocomments(
1317 $comment, $title = null, $local = false, $wikiId = null
1319 // @todo $append here is something of a hack to preserve the status
1320 // quo. Someone who knows more about bidi and such should decide
1321 // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1322 // wiki, both when autocomments exist and when they don't, and
1323 // (2) what markup will make that actually happen.
1325 $comment = preg_replace_callback(
1326 // To detect the presence of content before or after the
1327 // auto-comment, we use capturing groups inside optional zero-width
1328 // assertions. But older versions of PCRE can't directly make
1329 // zero-width assertions optional, so wrap them in a non-capturing
1331 '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1332 function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1335 // Ensure all match positions are defined
1336 $match +
= array( '', '', '', '' );
1338 $pre = $match[1] !== '';
1340 $post = $match[3] !== '';
1344 'FormatAutocomments',
1345 array( &$comment, $pre, $auto, $post, $title, $local, $wikiId )
1348 if ( $comment === null ) {
1352 # Remove links that a user may have manually put in the autosummary
1353 # This could be improved by copying as much of Parser::stripSectionName as desired.
1354 $section = str_replace( '[[:', '', $section );
1355 $section = str_replace( '[[', '', $section );
1356 $section = str_replace( ']]', '', $section );
1358 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1360 $sectionTitle = Title
::newFromText( '#' . $section );
1362 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1363 $title->getDBkey(), $section );
1365 if ( $sectionTitle ) {
1366 $link = Linker
::makeCommentLink( $sectionTitle, $wgLang->getArrow(), $wikiId, 'noclasses' );
1372 # written summary $presep autocomment (summary /* section */)
1373 $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1376 # autocomment $postsep written summary (/* section */ summary)
1377 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1379 $auto = '<span class="autocomment">' . $auto . '</span>';
1380 $comment = $pre . $link . $wgLang->getDirMark()
1381 . '<span dir="auto">' . $auto;
1382 $append .= '</span>';
1388 return $comment . $append;
1392 * Formats wiki links and media links in text; all other wiki formatting
1395 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1396 * @param string $comment Text to format links in
1397 * @param Title|null $title An optional title object used to links to sections
1398 * @param bool $local Whether section links should refer to local page
1399 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1400 * as used by WikiMap.
1404 public static function formatLinksInComment(
1405 $comment, $title = null, $local = false, $wikiId = null
1407 return preg_replace_callback(
1410 :? # ignore optional leading colon
1411 ([^\]|]+) # 1. link target; page names cannot include ] or |
1413 # 2. a pipe-separated substring; only the last is captured
1414 # Stop matching at | and ]] without relying on backtracking.
1418 ([^[]*) # 3. link trail (the text up until the next link)
1420 function ( $match ) use ( $title, $local, $wikiId ) {
1423 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1424 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1426 $comment = $match[0];
1428 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1429 if ( strpos( $match[1], '%' ) !== false ) {
1431 rawurldecode( $match[1] ),
1432 array( '<' => '<', '>' => '>' )
1436 # Handle link renaming [[foo|text]] will show link as "text"
1437 if ( $match[2] != "" ) {
1442 $submatch = array();
1444 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1445 # Media link; trail not supported.
1446 $linkRegexp = '/\[\[(.*?)\]\]/';
1447 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1449 $thelink = Linker
::makeMediaLinkObj( $title, $text );
1452 # Other kind of link
1453 if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1454 $trail = $submatch[1];
1458 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1459 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1460 $match[1] = substr( $match[1], 1 );
1462 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1465 $linkTarget = Linker
::normalizeSubpageLink( $title, $match[1], $linkText );
1467 $target = Title
::newFromText( $linkTarget );
1469 if ( $target->getText() == '' && !$target->isExternal()
1470 && !$local && $title
1472 $newTarget = clone $title;
1473 $newTarget->setFragment( '#' . $target->getFragment() );
1474 $target = $newTarget;
1477 $thelink = Linker
::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1481 // If the link is still valid, go ahead and replace it in!
1482 $comment = preg_replace(
1484 StringUtils
::escapeRegexReplacement( $thelink ),
1497 * Generates a link to the given Title
1499 * @note This is only public for technical reasons. It's not intended for use outside Linker.
1501 * @param Title $title
1502 * @param string $text
1503 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1504 * as used by WikiMap.
1505 * @param string|string[] $options See the $options parameter in Linker::link.
1507 * @return string HTML link
1509 public static function makeCommentLink(
1510 Title
$title, $text, $wikiId = null, $options = array()
1512 if ( $wikiId !== null && !$title->isExternal() ) {
1513 $link = Linker
::makeExternalLink(
1514 WikiMap
::getForeignURL(
1516 $title->getPrefixedText(),
1517 $title->getFragment()
1520 /* escape = */ false // Already escaped
1523 $link = Linker
::link( $title, $text, array(), array(), $options );
1530 * @param Title $contextTitle
1531 * @param string $target
1532 * @param string $text
1535 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1538 # :Foobar -- override special treatment of prefix (images, language links)
1539 # /Foobar -- convert to CurrentPage/Foobar
1540 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1541 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1542 # ../Foobar -- convert to CurrentPage/Foobar,
1543 # (from CurrentPage/CurrentSubPage)
1544 # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1545 # (from CurrentPage/CurrentSubPage)
1547 $ret = $target; # default return value is no change
1549 # Some namespaces don't allow subpages,
1550 # so only perform processing if subpages are allowed
1551 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1552 $hash = strpos( $target, '#' );
1553 if ( $hash !== false ) {
1554 $suffix = substr( $target, $hash );
1555 $target = substr( $target, 0, $hash );
1560 $target = trim( $target );
1561 # Look at the first character
1562 if ( $target != '' && $target[0] === '/' ) {
1563 # / at end means we don't want the slash to be shown
1565 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1566 if ( $trailingSlashes ) {
1567 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1569 $noslash = substr( $target, 1 );
1572 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1573 if ( $text === '' ) {
1574 $text = $target . $suffix;
1575 } # this might be changed for ugliness reasons
1577 # check for .. subpage backlinks
1579 $nodotdot = $target;
1580 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1582 $nodotdot = substr( $nodotdot, 3 );
1584 if ( $dotdotcount > 0 ) {
1585 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1586 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1587 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1588 # / at the end means don't show full path
1589 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1590 $nodotdot = rtrim( $nodotdot, '/' );
1591 if ( $text === '' ) {
1592 $text = $nodotdot . $suffix;
1595 $nodotdot = trim( $nodotdot );
1596 if ( $nodotdot != '' ) {
1597 $ret .= '/' . $nodotdot;
1609 * Wrap a comment in standard punctuation and formatting if
1610 * it's non-empty, otherwise return empty string.
1612 * @param string $comment
1613 * @param Title|null $title Title object (to generate link to section in autocomment) or null
1614 * @param bool $local Whether section links should refer to local page
1615 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1616 * For use with external changes.
1620 public static function commentBlock(
1621 $comment, $title = null, $local = false, $wikiId = null
1623 // '*' used to be the comment inserted by the software way back
1624 // in antiquity in case none was provided, here for backwards
1625 // compatibility, acc. to brion -ævar
1626 if ( $comment == '' ||
$comment == '*' ) {
1629 $formatted = self
::formatComment( $comment, $title, $local, $wikiId );
1630 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1631 return " <span class=\"comment\">$formatted</span>";
1636 * Wrap and format the given revision's comment block, if the current
1637 * user is allowed to view it.
1639 * @param Revision $rev
1640 * @param bool $local Whether section links should refer to local page
1641 * @param bool $isPublic Show only if all users can see it
1642 * @return string HTML fragment
1644 public static function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1645 if ( $rev->getComment( Revision
::RAW
) == "" ) {
1648 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1649 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1650 } elseif ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1651 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1652 $rev->getTitle(), $local );
1654 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1656 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1657 return " <span class=\"history-deleted\">$block</span>";
1666 public static function formatRevisionSize( $size ) {
1668 $stxt = wfMessage( 'historyempty' )->escaped();
1670 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1671 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1673 return "<span class=\"history-size\">$stxt</span>";
1677 * Add another level to the Table of Contents
1681 public static function tocIndent() {
1686 * Finish one or more sublevels on the Table of Contents
1691 public static function tocUnindent( $level ) {
1692 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1696 * parameter level defines if we are on an indentation level
1698 * @param string $anchor
1699 * @param string $tocline
1700 * @param string $tocnumber
1701 * @param string $level
1702 * @param string|bool $sectionIndex
1705 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1706 $classes = "toclevel-$level";
1707 if ( $sectionIndex !== false ) {
1708 $classes .= " tocsection-$sectionIndex";
1710 return "\n<li class=\"$classes\"><a href=\"#" .
1711 $anchor . '"><span class="tocnumber">' .
1712 $tocnumber . '</span> <span class="toctext">' .
1713 $tocline . '</span></a>';
1717 * End a Table Of Contents line.
1718 * tocUnindent() will be used instead if we're ending a line below
1722 public static function tocLineEnd() {
1727 * Wraps the TOC in a table and provides the hide/collapse javascript.
1729 * @param string $toc Html of the Table Of Contents
1730 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1731 * @return string Full html of the TOC
1733 public static function tocList( $toc, $lang = false ) {
1734 $lang = wfGetLangObj( $lang );
1735 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1737 return '<div id="toc" class="toc">'
1738 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1740 . "</ul>\n</div>\n";
1744 * Generate a table of contents from a section tree.
1746 * @param array $tree Return value of ParserOutput::getSections()
1747 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1748 * @return string HTML fragment
1750 public static function generateTOC( $tree, $lang = false ) {
1753 foreach ( $tree as $section ) {
1754 if ( $section['toclevel'] > $lastLevel ) {
1755 $toc .= self
::tocIndent();
1756 } elseif ( $section['toclevel'] < $lastLevel ) {
1757 $toc .= self
::tocUnindent(
1758 $lastLevel - $section['toclevel'] );
1760 $toc .= self
::tocLineEnd();
1763 $toc .= self
::tocLine( $section['anchor'],
1764 $section['line'], $section['number'],
1765 $section['toclevel'], $section['index'] );
1766 $lastLevel = $section['toclevel'];
1768 $toc .= self
::tocLineEnd();
1769 return self
::tocList( $toc, $lang );
1773 * Create a headline for content
1775 * @param int $level The level of the headline (1-6)
1776 * @param string $attribs Any attributes for the headline, starting with
1777 * a space and ending with '>'
1778 * This *must* be at least '>' for no attribs
1779 * @param string $anchor The anchor to give the headline (the bit after the #)
1780 * @param string $html Html for the text of the header
1781 * @param string $link HTML to add for the section edit link
1782 * @param bool|string $legacyAnchor A second, optional anchor to give for
1783 * backward compatibility (false to omit)
1785 * @return string HTML headline
1787 public static function makeHeadline( $level, $attribs, $anchor, $html,
1788 $link, $legacyAnchor = false
1790 $ret = "<h$level$attribs"
1791 . "<span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1794 if ( $legacyAnchor !== false ) {
1795 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1801 * Split a link trail, return the "inside" portion and the remainder of the trail
1802 * as a two-element array
1803 * @param string $trail
1806 static function splitTrail( $trail ) {
1808 $regex = $wgContLang->linkTrail();
1810 if ( $trail !== '' ) {
1812 if ( preg_match( $regex, $trail, $m ) ) {
1817 return array( $inside, $trail );
1821 * Generate a rollback link for a given revision. Currently it's the
1822 * caller's responsibility to ensure that the revision is the top one. If
1823 * it's not, of course, the user will get an error message.
1825 * If the calling page is called with the parameter &bot=1, all rollback
1826 * links also get that parameter. It causes the edit itself and the rollback
1827 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1828 * changes, so this allows sysops to combat a busy vandal without bothering
1831 * If the option verify is set this function will return the link only in case the
1832 * revision can be reverted. Please note that due to performance limitations
1833 * it might be assumed that a user isn't the only contributor of a page while
1834 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1835 * work if $wgShowRollbackEditCount is disabled, so this can only function
1836 * as an additional check.
1838 * If the option noBrackets is set the rollback link wont be enclosed in []
1840 * @param Revision $rev
1841 * @param IContextSource $context Context to use or null for the main context.
1842 * @param array $options
1845 public static function generateRollback( $rev, IContextSource
$context = null,
1846 $options = array( 'verify' )
1848 if ( $context === null ) {
1849 $context = RequestContext
::getMain();
1853 if ( in_array( 'verify', $options ) ) {
1854 $editCount = self
::getRollbackEditCount( $rev, true );
1855 if ( $editCount === false ) {
1860 $inner = self
::buildRollbackLink( $rev, $context, $editCount );
1862 if ( !in_array( 'noBrackets', $options ) ) {
1863 $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1866 return '<span class="mw-rollback-link">' . $inner . '</span>';
1870 * This function will return the number of revisions which a rollback
1871 * would revert and, if $verify is set it will verify that a revision
1872 * can be reverted (that the user isn't the only contributor and the
1873 * revision we might rollback to isn't deleted). These checks can only
1874 * function as an additional check as this function only checks against
1875 * the last $wgShowRollbackEditCount edits.
1877 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1878 * is set and the user is the only contributor of the page.
1880 * @param Revision $rev
1881 * @param bool $verify Try to verify that this revision can really be rolled back
1882 * @return int|bool|null
1884 public static function getRollbackEditCount( $rev, $verify ) {
1885 global $wgShowRollbackEditCount;
1886 if ( !is_int( $wgShowRollbackEditCount ) ||
!$wgShowRollbackEditCount > 0 ) {
1887 // Nothing has happened, indicate this by returning 'null'
1891 $dbr = wfGetDB( DB_SLAVE
);
1893 // Up to the value of $wgShowRollbackEditCount revisions are counted
1894 $res = $dbr->select(
1896 array( 'rev_user_text', 'rev_deleted' ),
1897 // $rev->getPage() returns null sometimes
1898 array( 'rev_page' => $rev->getTitle()->getArticleID() ),
1901 'USE INDEX' => array( 'revision' => 'page_timestamp' ),
1902 'ORDER BY' => 'rev_timestamp DESC',
1903 'LIMIT' => $wgShowRollbackEditCount +
1
1909 foreach ( $res as $row ) {
1910 if ( $rev->getUserText( Revision
::RAW
) != $row->rev_user_text
) {
1912 ( $row->rev_deleted
& Revision
::DELETED_TEXT
1913 ||
$row->rev_deleted
& Revision
::DELETED_USER
1915 // If the user or the text of the revision we might rollback
1916 // to is deleted in some way we can't rollback. Similar to
1917 // the sanity checks in WikiPage::commitRollback.
1926 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1927 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1928 // and there weren't any other revisions. That means that the current user is the only
1929 // editor, so we can't rollback
1936 * Build a raw rollback link, useful for collections of "tool" links
1938 * @param Revision $rev
1939 * @param IContextSource|null $context Context to use or null for the main context.
1940 * @param int $editCount Number of edits that would be reverted
1941 * @return string HTML fragment
1943 public static function buildRollbackLink( $rev, IContextSource
$context = null,
1946 global $wgShowRollbackEditCount, $wgMiserMode;
1948 // To config which pages are affected by miser mode
1949 $disableRollbackEditCountSpecialPage = array( 'Recentchanges', 'Watchlist' );
1951 if ( $context === null ) {
1952 $context = RequestContext
::getMain();
1955 $title = $rev->getTitle();
1957 'action' => 'rollback',
1958 'from' => $rev->getUserText(),
1959 'token' => $context->getUser()->getEditToken( array(
1960 $title->getPrefixedText(),
1964 if ( $context->getRequest()->getBool( 'bot' ) ) {
1965 $query['bot'] = '1';
1966 $query['hidediff'] = '1'; // bug 15999
1969 $disableRollbackEditCount = false;
1970 if ( $wgMiserMode ) {
1971 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1972 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1973 $disableRollbackEditCount = true;
1979 if ( !$disableRollbackEditCount
1980 && is_int( $wgShowRollbackEditCount )
1981 && $wgShowRollbackEditCount > 0
1983 if ( !is_numeric( $editCount ) ) {
1984 $editCount = self
::getRollbackEditCount( $rev, false );
1987 if ( $editCount > $wgShowRollbackEditCount ) {
1988 $editCount_output = $context->msg( 'rollbacklinkcount-morethan' )
1989 ->numParams( $wgShowRollbackEditCount )->parse();
1991 $editCount_output = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1997 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
1999 array( 'known', 'noclasses' )
2004 $context->msg( 'rollbacklink' )->escaped(),
2005 array( 'title' => $context->msg( 'tooltip-rollback' )->text() ),
2007 array( 'known', 'noclasses' )
2013 * Returns HTML for the "templates used on this page" list.
2015 * Make an HTML list of templates, and then add a "More..." link at
2016 * the bottom. If $more is null, do not add a "More..." link. If $more
2017 * is a Title, make a link to that title and use it. If $more is a string,
2018 * directly paste it in as the link (escaping needs to be done manually).
2019 * Finally, if $more is a Message, call toString().
2021 * @param array $templates Array of templates from Article::getUsedTemplate or similar
2022 * @param bool $preview Whether this is for a preview
2023 * @param bool $section Whether this is for a section edit
2024 * @param Title|Message|string|null $more An escaped link for "More..." of the templates
2025 * @return string HTML output
2027 public static function formatTemplates( $templates, $preview = false,
2028 $section = false, $more = null
2033 if ( count( $templates ) > 0 ) {
2034 # Do a batch existence check
2035 $batch = new LinkBatch
;
2036 foreach ( $templates as $title ) {
2037 $batch->addObj( $title );
2041 # Construct the HTML
2042 $outText = '<div class="mw-templatesUsedExplanation">';
2044 $outText .= wfMessage( 'templatesusedpreview' )->numParams( count( $templates ) )
2046 } elseif ( $section ) {
2047 $outText .= wfMessage( 'templatesusedsection' )->numParams( count( $templates ) )
2050 $outText .= wfMessage( 'templatesused' )->numParams( count( $templates ) )
2053 $outText .= "</div><ul>\n";
2055 usort( $templates, 'Title::compare' );
2056 foreach ( $templates as $titleObj ) {
2058 $restrictions = $titleObj->getRestrictions( 'edit' );
2059 if ( $restrictions ) {
2060 // Check backwards-compatible messages
2062 if ( $restrictions === array( 'sysop' ) ) {
2063 $msg = wfMessage( 'template-protected' );
2064 } elseif ( $restrictions === array( 'autoconfirmed' ) ) {
2065 $msg = wfMessage( 'template-semiprotected' );
2067 if ( $msg && !$msg->isDisabled() ) {
2068 $protected = $msg->parse();
2070 // Construct the message from restriction-level-*
2071 // e.g. restriction-level-sysop, restriction-level-autoconfirmed
2073 foreach ( $restrictions as $r ) {
2074 $msgs[] = wfMessage( "restriction-level-$r" )->parse();
2076 $protected = wfMessage( 'parentheses' )
2077 ->rawParams( $wgLang->commaList( $msgs ) )->escaped();
2080 if ( $titleObj->quickUserCan( 'edit' ) ) {
2081 $editLink = self
::link(
2083 wfMessage( 'editlink' )->escaped(),
2085 array( 'action' => 'edit' )
2088 $editLink = self
::link(
2090 wfMessage( 'viewsourcelink' )->escaped(),
2092 array( 'action' => 'edit' )
2095 $outText .= '<li>' . self
::link( $titleObj )
2096 . wfMessage( 'word-separator' )->escaped()
2097 . wfMessage( 'parentheses' )->rawParams( $editLink )->escaped()
2098 . wfMessage( 'word-separator' )->escaped()
2099 . $protected . '</li>';
2102 if ( $more instanceof Title
) {
2103 $outText .= '<li>' . self
::link( $more, wfMessage( 'moredotdotdot' ) ) . '</li>';
2104 } elseif ( $more ) {
2105 $outText .= "<li>$more</li>";
2108 $outText .= '</ul>';
2114 * Returns HTML for the "hidden categories on this page" list.
2116 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
2118 * @return string HTML output
2120 public static function formatHiddenCategories( $hiddencats ) {
2123 if ( count( $hiddencats ) > 0 ) {
2124 # Construct the HTML
2125 $outText = '<div class="mw-hiddenCategoriesExplanation">';
2126 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
2127 $outText .= "</div><ul>\n";
2129 foreach ( $hiddencats as $titleObj ) {
2130 # If it's hidden, it must exist - no need to check with a LinkBatch
2132 . self
::link( $titleObj, null, array(), array(), 'known' )
2135 $outText .= '</ul>';
2141 * Format a size in bytes for output, using an appropriate
2142 * unit (B, KB, MB or GB) according to the magnitude in question
2144 * @param int $size Size to format
2147 public static function formatSize( $size ) {
2149 return htmlspecialchars( $wgLang->formatSize( $size ) );
2153 * Given the id of an interface element, constructs the appropriate title
2154 * attribute from the system messages. (Note, this is usually the id but
2155 * isn't always, because sometimes the accesskey needs to go on a different
2156 * element than the id, for reverse-compatibility, etc.)
2158 * @param string $name Id of the element, minus prefixes.
2159 * @param string|null $options Null or the string 'withaccess' to add an access-
2161 * @return string Contents of the title attribute (which you must HTML-
2162 * escape), or false for no title attribute
2164 public static function titleAttrib( $name, $options = null ) {
2166 $message = wfMessage( "tooltip-$name" );
2168 if ( !$message->exists() ) {
2171 $tooltip = $message->text();
2172 # Compatibility: formerly some tooltips had [alt-.] hardcoded
2173 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2174 # Message equal to '-' means suppress it.
2175 if ( $tooltip == '-' ) {
2180 if ( $options == 'withaccess' ) {
2181 $accesskey = self
::accesskey( $name );
2182 if ( $accesskey !== false ) {
2183 // Should be build the same as in jquery.accessKeyLabel.js
2184 if ( $tooltip === false ||
$tooltip === '' ) {
2185 $tooltip = wfMessage( 'brackets', $accesskey )->text();
2187 $tooltip .= wfMessage( 'word-separator' )->text();
2188 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
2196 public static $accesskeycache;
2199 * Given the id of an interface element, constructs the appropriate
2200 * accesskey attribute from the system messages. (Note, this is usually
2201 * the id but isn't always, because sometimes the accesskey needs to go on
2202 * a different element than the id, for reverse-compatibility, etc.)
2204 * @param string $name Id of the element, minus prefixes.
2205 * @return string Contents of the accesskey attribute (which you must HTML-
2206 * escape), or false for no accesskey attribute
2208 public static function accesskey( $name ) {
2209 if ( isset( self
::$accesskeycache[$name] ) ) {
2210 return self
::$accesskeycache[$name];
2213 $message = wfMessage( "accesskey-$name" );
2215 if ( !$message->exists() ) {
2218 $accesskey = $message->plain();
2219 if ( $accesskey === '' ||
$accesskey === '-' ) {
2220 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2221 # attribute, but this is broken for accesskey: that might be a useful
2227 self
::$accesskeycache[$name] = $accesskey;
2228 return self
::$accesskeycache[$name];
2232 * Get a revision-deletion link, or disabled link, or nothing, depending
2233 * on user permissions & the settings on the revision.
2235 * Will use forward-compatible revision ID in the Special:RevDelete link
2236 * if possible, otherwise the timestamp-based ID which may break after
2240 * @param Revision $rev
2241 * @param Title $title
2242 * @return string HTML fragment
2244 public static function getRevDeleteLink( User
$user, Revision
$rev, Title
$title ) {
2245 $canHide = $user->isAllowed( 'deleterevision' );
2246 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2250 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
2251 return Linker
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2253 if ( $rev->getId() ) {
2254 // RevDelete links using revision ID are stable across
2255 // page deletion and undeletion; use when possible.
2257 'type' => 'revision',
2258 'target' => $title->getPrefixedDBkey(),
2259 'ids' => $rev->getId()
2262 // Older deleted entries didn't save a revision ID.
2263 // We have to refer to these by timestamp, ick!
2265 'type' => 'archive',
2266 'target' => $title->getPrefixedDBkey(),
2267 'ids' => $rev->getTimestamp()
2270 return Linker
::revDeleteLink( $query,
2271 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
2276 * Creates a (show/hide) link for deleting revisions/log entries
2278 * @param array $query Query parameters to be passed to link()
2279 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2280 * @param bool $delete Set to true to use (show/hide) rather than (show)
2282 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2283 * span to allow for customization of appearance with CSS
2285 public static function revDeleteLink( $query = array(), $restricted = false, $delete = true ) {
2286 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
2287 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2288 $html = wfMessage( $msgKey )->escaped();
2289 $tag = $restricted ?
'strong' : 'span';
2290 $link = self
::link( $sp, $html, array(), $query, array( 'known', 'noclasses' ) );
2293 array( 'class' => 'mw-revdelundel-link' ),
2294 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2299 * Creates a dead (show/hide) link for deleting revisions/log entries
2301 * @param bool $delete Set to true to use (show/hide) rather than (show)
2303 * @return string HTML text wrapped in a span to allow for customization
2304 * of appearance with CSS
2306 public static function revDeleteLinkDisabled( $delete = true ) {
2307 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2308 $html = wfMessage( $msgKey )->escaped();
2309 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2310 return Xml
::tags( 'span', array( 'class' => 'mw-revdelundel-link' ), $htmlParentheses );
2313 /* Deprecated methods */
2316 * @deprecated since 1.16 Use link(); warnings since 1.21
2318 * Make a link for a title which may or may not be in the database. If you need to
2319 * call this lots of times, pre-fill the link cache with a LinkBatch, otherwise each
2320 * call to this will result in a DB query.
2322 * @param Title $nt The title object to make the link from, e.g. from Title::newFromText.
2323 * @param string $text Link text
2324 * @param string $query Optional query part
2325 * @param string $trail Optional trail. Alphabetic characters at the start of this string will
2326 * be included in the link text. Other characters will be appended after
2327 * the end of the link.
2328 * @param string $prefix Optional prefix. As trail, only before instead of after.
2331 static function makeLinkObj( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
2332 wfDeprecated( __METHOD__
, '1.21' );
2334 $query = wfCgiToArray( $query );
2335 list( $inside, $trail ) = self
::splitTrail( $trail );
2336 if ( $text === '' ) {
2337 $text = self
::linkText( $nt );
2340 $ret = self
::link( $nt, "$prefix$text$inside", array(), $query ) . $trail;
2346 * @deprecated since 1.16 Use link(); warnings since 1.21
2348 * Make a link for a title which definitely exists. This is faster than makeLinkObj because
2349 * it doesn't have to do a database query. It's also valid for interwiki titles and special
2352 * @param Title $title Title object of target page
2353 * @param string $text Text to replace the title
2354 * @param string $query Link target
2355 * @param string $trail Text after link
2356 * @param string $prefix Text before link text
2357 * @param string $aprops Extra attributes to the a-element
2358 * @param string $style Style to apply - if empty, use getInternalLinkAttributesObj instead
2359 * @return string The a-element
2361 static function makeKnownLinkObj(
2362 $title, $text = '', $query = '', $trail = '', $prefix = '', $aprops = '', $style = ''
2364 wfDeprecated( __METHOD__
, '1.21' );
2366 if ( $text == '' ) {
2367 $text = self
::linkText( $title );
2369 $attribs = Sanitizer
::mergeAttributes(
2370 Sanitizer
::decodeTagAttributes( $aprops ),
2371 Sanitizer
::decodeTagAttributes( $style )
2373 $query = wfCgiToArray( $query );
2374 list( $inside, $trail ) = self
::splitTrail( $trail );
2376 $ret = self
::link( $title, "$prefix$text$inside", $attribs, $query,
2377 array( 'known', 'noclasses' ) ) . $trail;
2383 * Returns the attributes for the tooltip and access key.
2384 * @param string $name
2387 public static function tooltipAndAccesskeyAttribs( $name ) {
2388 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2389 # no attribute" instead of "output '' as value for attribute", this
2390 # would be three lines.
2392 'title' => self
::titleAttrib( $name, 'withaccess' ),
2393 'accesskey' => self
::accesskey( $name )
2395 if ( $attribs['title'] === false ) {
2396 unset( $attribs['title'] );
2398 if ( $attribs['accesskey'] === false ) {
2399 unset( $attribs['accesskey'] );
2405 * Returns raw bits of HTML, use titleAttrib()
2406 * @param string $name
2407 * @param array|null $options
2408 * @return null|string
2410 public static function tooltip( $name, $options = null ) {
2411 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2412 # no attribute" instead of "output '' as value for attribute", this
2413 # would be two lines.
2414 $tooltip = self
::titleAttrib( $name, $options );
2415 if ( $tooltip === false ) {
2418 return Xml
::expandAttributes( array(
2431 * Use PHP's magic __call handler to transform instance calls to a dummy instance
2432 * into static calls to the new Linker for backwards compatibility.
2434 * @param string $fname Name of called method
2435 * @param array $args Arguments to the method
2438 public function __call( $fname, $args ) {
2439 return call_user_func_array( array( 'Linker', $fname ), $args );