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
22 use MediaWiki\Linker\LinkTarget
;
23 use MediaWiki\MediaWikiServices
;
26 * Some internal bits split of from Skin.php. These functions are used
27 * for primarily page content: links, embedded images, table of contents. Links
28 * are also used in the skin.
30 * @todo turn this into a legacy interface for HtmlPageLinkRenderer and similar services.
36 * Flags for userToolLinks()
38 const TOOL_LINKS_NOBLOCK
= 1;
39 const TOOL_LINKS_EMAIL
= 2;
42 * This function returns an HTML link to the given target. It serves a few
44 * 1) If $target is a Title, the correct URL to link to will be figured
46 * 2) It automatically adds the usual classes for various types of link
47 * targets: "new" for red links, "stub" for short articles, etc.
48 * 3) It escapes all attribute values safely so there's no risk of XSS.
49 * 4) It provides a default tooltip if the target is a Title (the page
50 * name of the target).
51 * link() replaces the old functions in the makeLink() family.
53 * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
54 * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
56 * @param LinkTarget $target Can currently only be a LinkTarget, but this may
57 * change to support Images, literal URLs, etc.
58 * @param string $html The HTML contents of the <a> element, i.e.,
59 * the link text. This is raw HTML and will not be escaped. If null,
60 * defaults to the prefixed text of the Title; or if the Title is just a
61 * fragment, the contents of the fragment.
62 * @param array $customAttribs A key => value array of extra HTML attributes,
63 * such as title and class. (href is ignored.) Classes will be
64 * merged with the default classes, while other attributes will replace
65 * default attributes. All passed attribute values will be HTML-escaped.
66 * A false attribute value means to suppress that attribute.
67 * @param array $query The query string to append to the URL
68 * you're linking to, in key => value array form. Query keys and values
69 * will be URL-encoded.
70 * @param string|array $options String or array of strings:
71 * 'known': Page is known to exist, so don't check if it does.
72 * 'broken': Page is known not to exist, so don't check if it does.
73 * 'noclasses': Don't add any classes automatically (includes "new",
74 * "stub", "mw-redirect", "extiw"). Only use the class attribute
75 * provided, if any, so you get a simple blue link with no funny i-
77 * 'forcearticlepath': Use the article path always, even with a querystring.
78 * Has compatibility issues on some setups, so avoid wherever possible.
79 * 'http': Force a full URL with http:// as the scheme.
80 * 'https': Force a full URL with https:// as the scheme.
81 * 'stubThreshold' => (int): Stub threshold to use when determining link classes.
82 * @return string HTML <a> attribute
84 public static function link(
85 $target, $html = null, $customAttribs = [], $query = [], $options = []
87 if ( !$target instanceof LinkTarget
) {
88 wfWarn( __METHOD__
. ': Requires $target to be a LinkTarget object.', 2 );
89 return "<!-- ERROR -->$html";
92 if ( is_string( $query ) ) {
93 // some functions withing core using this still hand over query strings
94 wfDeprecated( __METHOD__
. ' with parameter $query as string (should be array)', '1.20' );
95 $query = wfCgiToArray( $query );
98 $services = MediaWikiServices
::getInstance();
99 $options = (array)$options;
101 // Custom options, create new LinkRenderer
102 if ( !isset( $options['stubThreshold'] ) ) {
103 $defaultLinkRenderer = $services->getLinkRenderer();
104 $options['stubThreshold'] = $defaultLinkRenderer->getStubThreshold();
106 $linkRenderer = $services->getLinkRendererFactory()
107 ->createFromLegacyOptions( $options );
109 $linkRenderer = $services->getLinkRenderer();
112 if ( $html !== null ) {
113 $text = new HtmlArmor( $html );
115 $text = $html; // null
117 if ( in_array( 'known', $options, true ) ) {
118 return $linkRenderer->makeKnownLink( $target, $text, $customAttribs, $query );
119 } elseif ( in_array( 'broken', $options, true ) ) {
120 return $linkRenderer->makeBrokenLink( $target, $text, $customAttribs, $query );
121 } elseif ( in_array( 'noclasses', $options, true ) ) {
122 return $linkRenderer->makePreloadedLink( $target, $text, '', $customAttribs, $query );
124 return $linkRenderer->makeLink( $target, $text, $customAttribs, $query );
129 * Identical to link(), except $options defaults to 'known'.
132 * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
134 * @param Title $target
135 * @param string $html
136 * @param array $customAttribs
137 * @param array $query
138 * @param string|array $options
141 public static function linkKnown(
142 $target, $html = null, $customAttribs = [],
143 $query = [], $options = [ 'known' ]
145 return self
::link( $target, $html, $customAttribs, $query, $options );
149 * Make appropriate markup for a link to the current article. This is since
150 * MediaWiki 1.29.0 rendered as an <a> tag without an href and with a class
151 * showing the link text. The calling sequence is the same as for the other
152 * make*LinkObj static functions, but $query is not used.
156 * @param string $html [optional]
157 * @param string $query [optional]
158 * @param string $trail [optional]
159 * @param string $prefix [optional]
163 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
164 $ret = "<a class=\"mw-selflink selflink\">{$prefix}{$html}</a>{$trail}";
165 if ( !Hooks
::run( 'SelfLinkBegin', [ $nt, &$html, &$trail, &$prefix, &$ret ] ) ) {
170 $html = htmlspecialchars( $nt->getPrefixedText() );
172 list( $inside, $trail ) = self
::splitTrail( $trail );
173 return "<a class=\"mw-selflink selflink\">{$prefix}{$html}{$inside}</a>{$trail}";
177 * Get a message saying that an invalid title was encountered.
178 * This should be called after a method like Title::makeTitleSafe() returned
179 * a value indicating that the title object is invalid.
181 * @param IContextSource $context Context to use to get the messages
182 * @param int $namespace Namespace number
183 * @param string $title Text of the title, without the namespace part
186 public static function getInvalidTitleDescription( IContextSource
$context, $namespace, $title ) {
189 // First we check whether the namespace exists or not.
190 if ( MWNamespace
::exists( $namespace ) ) {
191 if ( $namespace == NS_MAIN
) {
192 $name = $context->msg( 'blanknamespace' )->text();
194 $name = $wgContLang->getFormattedNsText( $namespace );
196 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
198 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
204 * @param LinkTarget $target
207 public static function normaliseSpecialPage( LinkTarget
$target ) {
208 if ( $target->getNamespace() == NS_SPECIAL
&& !$target->isExternal() ) {
209 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $target->getDBkey() );
213 $ret = SpecialPage
::getTitleValueFor( $name, $subpage, $target->getFragment() );
221 * Returns the filename part of an url.
222 * Used as alternative text for external images.
228 private static function fnamePart( $url ) {
229 $basename = strrchr( $url, '/' );
230 if ( false === $basename ) {
233 $basename = substr( $basename, 1 );
239 * Return the code for images which were added via external links,
240 * via Parser::maybeMakeExternalImage().
248 public static function makeExternalImage( $url, $alt = '' ) {
250 $alt = self
::fnamePart( $url );
253 $success = Hooks
::run( 'LinkerMakeExternalImage', [ &$url, &$alt, &$img ] );
255 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
256 . "with url {$url} and alt text {$alt} to {$img}\n", true );
259 return Html
::element( 'img',
266 * Given parameters derived from [[Image:Foo|options...]], generate the
267 * HTML that that syntax inserts in the page.
269 * @param Parser $parser
270 * @param Title $title Title object of the file (not the currently viewed page)
271 * @param File $file File object, or false if it doesn't exist
272 * @param array $frameParams Associative array of parameters external to the media handler.
273 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
274 * will often be false.
275 * thumbnail If present, downscale and frame
276 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
277 * framed Shows image in original size in a frame
278 * frameless Downscale but don't frame
279 * upright If present, tweak default sizes for portrait orientation
280 * upright_factor Fudge factor for "upright" tweak (default 0.75)
281 * border If present, show a border around the image
282 * align Horizontal alignment (left, right, center, none)
283 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
284 * bottom, text-bottom)
285 * alt Alternate text for image (i.e. alt attribute). Plain text.
286 * class HTML for image classes. Plain text.
287 * caption HTML for image caption.
288 * link-url URL to link to
289 * link-title Title object to link to
290 * link-target Value for the target attribute, only with link-url
291 * no-link Boolean, suppress description link
293 * @param array $handlerParams Associative array of media handler parameters, to be passed
294 * to transform(). Typical keys are "width" and "page".
295 * @param string|bool $time Timestamp of the file, set as false for current
296 * @param string $query Query params for desc url
297 * @param int|null $widthOption Used by the parser to remember the user preference thumbnailsize
299 * @return string HTML for an image, with links, wrappers, etc.
301 public static function makeImageLink( Parser
$parser, Title
$title,
302 $file, $frameParams = [], $handlerParams = [], $time = false,
303 $query = "", $widthOption = null
306 $dummy = new DummyLinker
;
307 if ( !Hooks
::run( 'ImageBeforeProduceHTML', [ &$dummy, &$title,
308 &$file, &$frameParams, &$handlerParams, &$time, &$res ] ) ) {
312 if ( $file && !$file->allowInlineDisplay() ) {
313 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
314 return self
::link( $title );
317 // Clean up parameters
318 $page = $handlerParams['page'] ??
false;
319 if ( !isset( $frameParams['align'] ) ) {
320 $frameParams['align'] = '';
322 if ( !isset( $frameParams['alt'] ) ) {
323 $frameParams['alt'] = '';
325 if ( !isset( $frameParams['title'] ) ) {
326 $frameParams['title'] = '';
328 if ( !isset( $frameParams['class'] ) ) {
329 $frameParams['class'] = '';
332 $prefix = $postfix = '';
334 if ( 'center' == $frameParams['align'] ) {
335 $prefix = '<div class="center">';
337 $frameParams['align'] = 'none';
339 if ( $file && !isset( $handlerParams['width'] ) ) {
340 if ( isset( $handlerParams['height'] ) && $file->isVectorized() ) {
341 // If its a vector image, and user only specifies height
342 // we don't want it to be limited by its "normal" width.
343 global $wgSVGMaxSize;
344 $handlerParams['width'] = $wgSVGMaxSize;
346 $handlerParams['width'] = $file->getWidth( $page );
349 if ( isset( $frameParams['thumbnail'] )
350 ||
isset( $frameParams['manualthumb'] )
351 ||
isset( $frameParams['framed'] )
352 ||
isset( $frameParams['frameless'] )
353 ||
!$handlerParams['width']
355 global $wgThumbLimits, $wgThumbUpright;
357 if ( $widthOption === null ||
!isset( $wgThumbLimits[$widthOption] ) ) {
358 $widthOption = User
::getDefaultOption( 'thumbsize' );
361 // Reduce width for upright images when parameter 'upright' is used
362 if ( isset( $frameParams['upright'] ) && $frameParams['upright'] == 0 ) {
363 $frameParams['upright'] = $wgThumbUpright;
366 // For caching health: If width scaled down due to upright
367 // parameter, round to full __0 pixel to avoid the creation of a
368 // lot of odd thumbs.
369 $prefWidth = isset( $frameParams['upright'] ) ?
370 round( $wgThumbLimits[$widthOption] * $frameParams['upright'], -1 ) :
371 $wgThumbLimits[$widthOption];
373 // Use width which is smaller: real image width or user preference width
374 // Unless image is scalable vector.
375 if ( !isset( $handlerParams['height'] ) && ( $handlerParams['width'] <= 0 ||
376 $prefWidth < $handlerParams['width'] ||
$file->isVectorized() ) ) {
377 $handlerParams['width'] = $prefWidth;
382 if ( isset( $frameParams['thumbnail'] ) ||
isset( $frameParams['manualthumb'] )
383 ||
isset( $frameParams['framed'] )
385 # Create a thumbnail. Alignment depends on the writing direction of
386 # the page content language (right-aligned for LTR languages,
387 # left-aligned for RTL languages)
388 # If a thumbnail width has not been provided, it is set
389 # to the default user option as specified in Language*.php
390 if ( $frameParams['align'] == '' ) {
391 $frameParams['align'] = $parser->getTargetLanguage()->alignEnd();
394 self
::makeThumbLink2( $title, $file, $frameParams, $handlerParams, $time, $query ) .
398 if ( $file && isset( $frameParams['frameless'] ) ) {
399 $srcWidth = $file->getWidth( $page );
400 # For "frameless" option: do not present an image bigger than the
401 # source (for bitmap-style images). This is the same behavior as the
402 # "thumb" option does it already.
403 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
404 $handlerParams['width'] = $srcWidth;
408 if ( $file && isset( $handlerParams['width'] ) ) {
409 # Create a resized image, without the additional thumbnail features
410 $thumb = $file->transform( $handlerParams );
416 $s = self
::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
418 self
::processResponsiveImages( $file, $thumb, $handlerParams );
420 'alt' => $frameParams['alt'],
421 'title' => $frameParams['title'],
422 'valign' => $frameParams['valign'] ??
false,
423 'img-class' => $frameParams['class'] ];
424 if ( isset( $frameParams['border'] ) ) {
425 $params['img-class'] .= ( $params['img-class'] !== '' ?
' ' : '' ) . 'thumbborder';
427 $params = self
::getImageLinkMTOParams( $frameParams, $query, $parser ) +
$params;
429 $s = $thumb->toHtml( $params );
431 if ( $frameParams['align'] != '' ) {
432 $s = "<div class=\"float{$frameParams['align']}\">{$s}</div>";
434 return str_replace( "\n", ' ', $prefix . $s . $postfix );
438 * Get the link parameters for MediaTransformOutput::toHtml() from given
439 * frame parameters supplied by the Parser.
440 * @param array $frameParams The frame parameters
441 * @param string $query An optional query string to add to description page links
442 * @param Parser|null $parser
445 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
447 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
448 $mtoParams['custom-url-link'] = $frameParams['link-url'];
449 if ( isset( $frameParams['link-target'] ) ) {
450 $mtoParams['custom-target-link'] = $frameParams['link-target'];
453 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
454 foreach ( $extLinkAttrs as $name => $val ) {
455 // Currently could include 'rel' and 'target'
456 $mtoParams['parser-extlink-' . $name] = $val;
459 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
460 $mtoParams['custom-title-link'] = Title
::newFromLinkTarget(
461 self
::normaliseSpecialPage( $frameParams['link-title'] )
463 } elseif ( !empty( $frameParams['no-link'] ) ) {
466 $mtoParams['desc-link'] = true;
467 $mtoParams['desc-query'] = $query;
473 * Make HTML for a thumbnail including image, border and caption
474 * @param Title $title
475 * @param File|bool $file File object or false if it doesn't exist
476 * @param string $label
478 * @param string $align
479 * @param array $params
480 * @param bool $framed
481 * @param string $manualthumb
484 public static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt = '',
485 $align = 'right', $params = [], $framed = false, $manualthumb = ""
493 $frameParams['framed'] = true;
495 if ( $manualthumb ) {
496 $frameParams['manualthumb'] = $manualthumb;
498 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
502 * @param Title $title
504 * @param array $frameParams
505 * @param array $handlerParams
507 * @param string $query
510 public static function makeThumbLink2( Title
$title, $file, $frameParams = [],
511 $handlerParams = [], $time = false, $query = ""
513 $exists = $file && $file->exists();
515 $page = $handlerParams['page'] ??
false;
516 if ( !isset( $frameParams['align'] ) ) {
517 $frameParams['align'] = 'right';
519 if ( !isset( $frameParams['alt'] ) ) {
520 $frameParams['alt'] = '';
522 if ( !isset( $frameParams['title'] ) ) {
523 $frameParams['title'] = '';
525 if ( !isset( $frameParams['caption'] ) ) {
526 $frameParams['caption'] = '';
529 if ( empty( $handlerParams['width'] ) ) {
530 // Reduce width for upright images when parameter 'upright' is used
531 $handlerParams['width'] = isset( $frameParams['upright'] ) ?
130 : 180;
535 $manualthumb = false;
538 $outerWidth = $handlerParams['width'] +
2;
540 if ( isset( $frameParams['manualthumb'] ) ) {
541 # Use manually specified thumbnail
542 $manual_title = Title
::makeTitleSafe( NS_FILE
, $frameParams['manualthumb'] );
543 if ( $manual_title ) {
544 $manual_img = wfFindFile( $manual_title );
546 $thumb = $manual_img->getUnscaledThumb( $handlerParams );
552 } elseif ( isset( $frameParams['framed'] ) ) {
553 // Use image dimensions, don't scale
554 $thumb = $file->getUnscaledThumb( $handlerParams );
557 # Do not present an image bigger than the source, for bitmap-style images
558 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
559 $srcWidth = $file->getWidth( $page );
560 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
561 $handlerParams['width'] = $srcWidth;
563 $thumb = $file->transform( $handlerParams );
567 $outerWidth = $thumb->getWidth() +
2;
569 $outerWidth = $handlerParams['width'] +
2;
573 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
574 # So we don't need to pass it here in $query. However, the URL for the
575 # zoom icon still needs it, so we make a unique query for it. See T16771
576 $url = $title->getLocalURL( $query );
578 $url = wfAppendQuery( $url, [ 'page' => $page ] );
581 && !isset( $frameParams['link-title'] )
582 && !isset( $frameParams['link-url'] )
583 && !isset( $frameParams['no-link'] ) ) {
584 $frameParams['link-url'] = $url;
587 $s = "<div class=\"thumb t{$frameParams['align']}\">"
588 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
591 $s .= self
::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
593 } elseif ( !$thumb ) {
594 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
597 if ( !$noscale && !$manualthumb ) {
598 self
::processResponsiveImages( $file, $thumb, $handlerParams );
601 'alt' => $frameParams['alt'],
602 'title' => $frameParams['title'],
603 'img-class' => ( isset( $frameParams['class'] ) && $frameParams['class'] !== ''
604 ?
$frameParams['class'] . ' '
605 : '' ) . 'thumbimage'
607 $params = self
::getImageLinkMTOParams( $frameParams, $query ) +
$params;
608 $s .= $thumb->toHtml( $params );
609 if ( isset( $frameParams['framed'] ) ) {
612 $zoomIcon = Html
::rawElement( 'div', [ 'class' => 'magnify' ],
613 Html
::rawElement( 'a', [
615 'class' => 'internal',
616 'title' => wfMessage( 'thumbnail-more' )->text() ],
620 $s .= ' <div class="thumbcaption">' . $zoomIcon . $frameParams['caption'] . "</div></div></div>";
621 return str_replace( "\n", ' ', $s );
625 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
629 * @param MediaTransformOutput $thumb
630 * @param array $hp Image parameters
632 public static function processResponsiveImages( $file, $thumb, $hp ) {
633 global $wgResponsiveImages;
634 if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
636 $hp15['width'] = round( $hp['width'] * 1.5 );
638 $hp20['width'] = $hp['width'] * 2;
639 if ( isset( $hp['height'] ) ) {
640 $hp15['height'] = round( $hp['height'] * 1.5 );
641 $hp20['height'] = $hp['height'] * 2;
644 $thumb15 = $file->transform( $hp15 );
645 $thumb20 = $file->transform( $hp20 );
646 if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
647 $thumb->responsiveUrls
['1.5'] = $thumb15->getUrl();
649 if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
650 $thumb->responsiveUrls
['2'] = $thumb20->getUrl();
656 * Make a "broken" link to an image
659 * @param Title $title
660 * @param string $label Link label (plain text)
661 * @param string $query Query string
662 * @param string $unused1 Unused parameter kept for b/c
663 * @param string $unused2 Unused parameter kept for b/c
664 * @param bool $time A file of a certain timestamp was requested
667 public static function makeBrokenImageLinkObj( $title, $label = '',
668 $query = '', $unused1 = '', $unused2 = '', $time = false
670 if ( !$title instanceof Title
) {
671 wfWarn( __METHOD__
. ': Requires $title to be a Title object.' );
672 return "<!-- ERROR -->" . htmlspecialchars( $label );
675 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
676 if ( $label == '' ) {
677 $label = $title->getPrefixedText();
679 $encLabel = htmlspecialchars( $label );
680 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
682 if ( ( $wgUploadMissingFileUrl ||
$wgUploadNavigationUrl ||
$wgEnableUploads )
685 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
688 // We already know it's a redirect, so mark it
693 [ 'class' => 'mw-redirect' ],
694 wfCgiToArray( $query ),
695 [ 'known', 'noclasses' ]
699 $href = self
::getUploadUrl( $title, $query );
701 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
702 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
706 return self
::link( $title, $encLabel, [], wfCgiToArray( $query ), [ 'known', 'noclasses' ] );
710 * Get the URL to upload a certain file
713 * @param Title $destFile Title object of the file to upload
714 * @param string $query Urlencoded query string to prepend
715 * @return string Urlencoded URL
717 protected static function getUploadUrl( $destFile, $query = '' ) {
718 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
719 $q = 'wpDestFile=' . $destFile->getPartialURL();
720 if ( $query != '' ) {
724 if ( $wgUploadMissingFileUrl ) {
725 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
726 } elseif ( $wgUploadNavigationUrl ) {
727 return wfAppendQuery( $wgUploadNavigationUrl, $q );
729 $upload = SpecialPage
::getTitleFor( 'Upload' );
730 return $upload->getLocalURL( $q );
735 * Create a direct link to a given uploaded file.
738 * @param Title $title
739 * @param string $html Pre-sanitized HTML
740 * @param string $time MW timestamp of file creation time
741 * @return string HTML
743 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
744 $img = wfFindFile( $title, [ 'time' => $time ] );
745 return self
::makeMediaLinkFile( $title, $img, $html );
749 * Create a direct link to a given uploaded file.
750 * This will make a broken link if $file is false.
753 * @param Title $title
754 * @param File|bool $file File object or false
755 * @param string $html Pre-sanitized HTML
756 * @return string HTML
758 * @todo Handle invalid or missing images better.
760 public static function makeMediaLinkFile( Title
$title, $file, $html = '' ) {
761 if ( $file && $file->exists() ) {
762 $url = $file->getUrl();
765 $url = self
::getUploadUrl( $title );
769 $alt = $title->getText();
781 if ( !Hooks
::run( 'LinkerMakeMediaLinkFile',
782 [ $title, $file, &$html, &$attribs, &$ret ] ) ) {
783 wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
784 . "with url {$url} and text {$html} to {$ret}\n", true );
788 return Html
::rawElement( 'a', $attribs, $html );
792 * Make a link to a special page given its name and, optionally,
793 * a message key from the link text.
794 * Usage example: Linker::specialLink( 'Recentchanges' )
797 * @param string $name
801 public static function specialLink( $name, $key = '' ) {
803 $key = strtolower( $name );
806 return self
::linkKnown( SpecialPage
::getTitleFor( $name ), wfMessage( $key )->escaped() );
810 * Make an external link
811 * @since 1.16.3. $title added in 1.21
812 * @param string $url URL to link to
813 * @param string $text Text of link
814 * @param bool $escape Do we escape the link text?
815 * @param string $linktype Type of external link. Gets added to the classes
816 * @param array $attribs Array of extra attributes to <a>
817 * @param Title|null $title Title object used for title specific link attributes
820 public static function makeExternalLink( $url, $text, $escape = true,
821 $linktype = '', $attribs = [], $title = null
826 $class .= " $linktype";
828 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
829 $class .= " {$attribs['class']}";
831 $attribs['class'] = $class;
834 $text = htmlspecialchars( $text );
840 $newRel = Parser
::getExternalLinkRel( $url, $title );
841 if ( !isset( $attribs['rel'] ) ||
$attribs['rel'] === '' ) {
842 $attribs['rel'] = $newRel;
843 } elseif ( $newRel !== '' ) {
844 // Merge the rel attributes.
845 $newRels = explode( ' ', $newRel );
846 $oldRels = explode( ' ', $attribs['rel'] );
847 $combined = array_unique( array_merge( $newRels, $oldRels ) );
848 $attribs['rel'] = implode( ' ', $combined );
851 $success = Hooks
::run( 'LinkerMakeExternalLink',
852 [ &$url, &$text, &$link, &$attribs, $linktype ] );
854 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
855 . "with url {$url} and text {$text} to {$link}\n", true );
858 $attribs['href'] = $url;
859 return Html
::rawElement( 'a', $attribs, $text );
863 * Make user link (or user contributions for unregistered users)
864 * @param int $userId User id in database.
865 * @param string $userName User name in database.
866 * @param string $altUserName Text to display instead of the user name (optional)
867 * @return string HTML fragment
868 * @since 1.16.3. $altUserName was added in 1.19.
870 public static function userLink( $userId, $userName, $altUserName = false ) {
871 $classes = 'mw-userlink';
873 if ( $userId == 0 ) {
874 $page = ExternalUserNames
::getUserLinkTitle( $userName );
876 if ( ExternalUserNames
::isExternal( $userName ) ) {
877 $classes .= ' mw-extuserlink';
878 } elseif ( $altUserName === false ) {
879 $altUserName = IP
::prettifyIP( $userName );
881 $classes .= ' mw-anonuserlink'; // Separate link class for anons (T45179)
883 $page = Title
::makeTitle( NS_USER
, $userName );
886 // Wrap the output with <bdi> tags for directionality isolation
888 '<bdi>' . htmlspecialchars( $altUserName !== false ?
$altUserName : $userName ) . '</bdi>';
891 ? self
::link( $page, $linkText, [ 'class' => $classes ] )
892 : Html
::rawElement( 'span', [ 'class' => $classes ], $linkText );
896 * Generate standard user tool links (talk, contributions, block link, etc.)
899 * @param int $userId User identifier
900 * @param string $userText User name or IP address
901 * @param bool $redContribsWhenNoEdits Should the contributions link be
902 * red if the user has no edits?
903 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
904 * and Linker::TOOL_LINKS_EMAIL).
905 * @param int $edits User edit count (optional, for performance)
906 * @return string HTML fragment
908 public static function userToolLinks(
909 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
911 global $wgUser, $wgDisableAnonTalk, $wgLang;
912 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
913 $blockable = !( $flags & self
::TOOL_LINKS_NOBLOCK
);
914 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
&& $userId;
916 if ( $userId == 0 && ExternalUserNames
::isExternal( $userText ) ) {
917 // No tools for an external user
923 $items[] = self
::userTalkLink( $userId, $userText );
926 // check if the user has an edit
928 $attribs['class'] = 'mw-usertoollinks-contribs';
929 if ( $redContribsWhenNoEdits ) {
930 if ( intval( $edits ) === 0 && $edits !== 0 ) {
931 $user = User
::newFromId( $userId );
932 $edits = $user->getEditCount();
934 if ( $edits === 0 ) {
935 $attribs['class'] .= ' new';
938 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
940 $items[] = self
::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
942 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
943 $items[] = self
::blockLink( $userId, $userText );
946 if ( $addEmailLink && $wgUser->canSendEmail() ) {
947 $items[] = self
::emailLink( $userId, $userText );
950 Hooks
::run( 'UserToolLinksEdit', [ $userId, $userText, &$items ] );
953 return wfMessage( 'word-separator' )->escaped()
954 . '<span class="mw-usertoollinks">'
955 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
963 * Alias for userToolLinks( $userId, $userText, true );
965 * @param int $userId User identifier
966 * @param string $userText User name or IP address
967 * @param int $edits User edit count (optional, for performance)
970 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
971 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
976 * @param int $userId User id in database.
977 * @param string $userText User name in database.
978 * @return string HTML fragment with user talk link
980 public static function userTalkLink( $userId, $userText ) {
981 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
982 $moreLinkAttribs['class'] = 'mw-usertoollinks-talk';
983 $userTalkLink = self
::link( $userTalkPage,
984 wfMessage( 'talkpagelinktext' )->escaped(),
986 return $userTalkLink;
992 * @param string $userText User name in database.
993 * @return string HTML fragment with block link
995 public static function blockLink( $userId, $userText ) {
996 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
997 $moreLinkAttribs['class'] = 'mw-usertoollinks-block';
998 $blockLink = self
::link( $blockPage,
999 wfMessage( 'blocklink' )->escaped(),
1005 * @param int $userId
1006 * @param string $userText User name in database.
1007 * @return string HTML fragment with e-mail user link
1009 public static function emailLink( $userId, $userText ) {
1010 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1011 $moreLinkAttribs['class'] = 'mw-usertoollinks-mail';
1012 $emailLink = self
::link( $emailPage,
1013 wfMessage( 'emaillink' )->escaped(),
1019 * Generate a user link if the current user is allowed to view it
1021 * @param Revision $rev
1022 * @param bool $isPublic Show only if all users can see it
1023 * @return string HTML fragment
1025 public static function revUserLink( $rev, $isPublic = false ) {
1026 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1027 $link = wfMessage( 'rev-deleted-user' )->escaped();
1028 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1029 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1030 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1032 $link = wfMessage( 'rev-deleted-user' )->escaped();
1034 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1035 return '<span class="history-deleted">' . $link . '</span>';
1041 * Generate a user tool link cluster if the current user is allowed to view it
1043 * @param Revision $rev
1044 * @param bool $isPublic Show only if all users can see it
1045 * @return string HTML
1047 public static function revUserTools( $rev, $isPublic = false ) {
1048 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1049 $link = wfMessage( 'rev-deleted-user' )->escaped();
1050 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1051 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1052 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1053 $link = self
::userLink( $userId, $userText )
1054 . self
::userToolLinks( $userId, $userText );
1056 $link = wfMessage( 'rev-deleted-user' )->escaped();
1058 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1059 return ' <span class="history-deleted">' . $link . '</span>';
1065 * This function is called by all recent changes variants, by the page history,
1066 * and by the user contributions list. It is responsible for formatting edit
1067 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1068 * auto-generated comments (from section editing) and formats [[wikilinks]].
1070 * @author Erik Moeller <moeller@scireview.de>
1071 * @since 1.16.3. $wikiId added in 1.26
1073 * Note: there's not always a title to pass to this function.
1074 * Since you can't set a default parameter for a reference, I've turned it
1075 * temporarily to a value pass. Should be adjusted further. --brion
1077 * @param string $comment
1078 * @param Title|null $title Title object (to generate link to the section in autocomment)
1080 * @param bool $local Whether section links should refer to local page
1081 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1082 * For use with external changes.
1084 * @return mixed|string
1086 public static function formatComment(
1087 $comment, $title = null, $local = false, $wikiId = null
1089 # Sanitize text a bit:
1090 $comment = str_replace( "\n", " ", $comment );
1091 # Allow HTML entities (for T15815)
1092 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1094 # Render autocomments and make links:
1095 $comment = self
::formatAutocomments( $comment, $title, $local, $wikiId );
1096 $comment = self
::formatLinksInComment( $comment, $title, $local, $wikiId );
1102 * Converts autogenerated comments in edit summaries into section links.
1104 * The pattern for autogen comments is / * foo * /, which makes for
1106 * We look for all comments, match any text before and after the comment,
1107 * add a separator where needed and format the comment itself with CSS
1108 * Called by Linker::formatComment.
1110 * @param string $comment Comment text
1111 * @param Title|null $title An optional title object used to links to sections
1112 * @param bool $local Whether section links should refer to local page
1113 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1114 * as used by WikiMap.
1116 * @return string Formatted comment (wikitext)
1118 private static function formatAutocomments(
1119 $comment, $title = null, $local = false, $wikiId = null
1121 // @todo $append here is something of a hack to preserve the status
1122 // quo. Someone who knows more about bidi and such should decide
1123 // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1124 // wiki, both when autocomments exist and when they don't, and
1125 // (2) what markup will make that actually happen.
1127 $comment = preg_replace_callback(
1128 // To detect the presence of content before or after the
1129 // auto-comment, we use capturing groups inside optional zero-width
1130 // assertions. But older versions of PCRE can't directly make
1131 // zero-width assertions optional, so wrap them in a non-capturing
1133 '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1134 function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1137 // Ensure all match positions are defined
1138 $match +
= [ '', '', '', '' ];
1140 $pre = $match[1] !== '';
1142 $post = $match[3] !== '';
1146 'FormatAutocomments',
1147 [ &$comment, $pre, $auto, $post, $title, $local, $wikiId ]
1150 if ( $comment === null ) {
1154 # Remove links that a user may have manually put in the autosummary
1155 # This could be improved by copying as much of Parser::stripSectionName as desired.
1156 $section = str_replace( '[[:', '', $section );
1157 $section = str_replace( '[[', '', $section );
1158 $section = str_replace( ']]', '', $section );
1160 $section = substr( Parser
::guessSectionNameFromStrippedText( $section ), 1 );
1162 $sectionTitle = Title
::makeTitleSafe( NS_MAIN
, '', $section );
1164 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1165 $title->getDBkey(), $section );
1167 if ( $sectionTitle ) {
1168 $link = Linker
::makeCommentLink( $sectionTitle, $wgLang->getArrow(), $wikiId, 'noclasses' );
1174 # written summary $presep autocomment (summary /* section */)
1175 $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1178 # autocomment $postsep written summary (/* section */ summary)
1179 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1181 $auto = '<span class="autocomment">' . $auto . '</span>';
1182 $comment = $pre . $link . $wgLang->getDirMark()
1183 . '<span dir="auto">' . $auto;
1184 $append .= '</span>';
1190 return $comment . $append;
1194 * Formats wiki links and media links in text; all other wiki formatting
1197 * @since 1.16.3. $wikiId added in 1.26
1198 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1200 * @param string $comment Text to format links in. WARNING! Since the output of this
1201 * function is html, $comment must be sanitized for use as html. You probably want
1202 * to pass $comment through Sanitizer::escapeHtmlAllowEntities() before calling
1204 * @param Title|null $title An optional title object used to links to sections
1205 * @param bool $local Whether section links should refer to local page
1206 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1207 * as used by WikiMap.
1211 public static function formatLinksInComment(
1212 $comment, $title = null, $local = false, $wikiId = null
1214 return preg_replace_callback(
1217 :? # ignore optional leading colon
1218 ([^\]|]+) # 1. link target; page names cannot include ] or |
1221 # Stop matching at ]] without relying on backtracking.
1225 ([^[]*) # 3. link trail (the text up until the next link)
1227 function ( $match ) use ( $title, $local, $wikiId ) {
1230 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1231 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1233 $comment = $match[0];
1235 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1236 if ( strpos( $match[1], '%' ) !== false ) {
1238 rawurldecode( $match[1] ),
1239 [ '<' => '<', '>' => '>' ]
1243 # Handle link renaming [[foo|text]] will show link as "text"
1244 if ( $match[2] != "" ) {
1251 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1252 # Media link; trail not supported.
1253 $linkRegexp = '/\[\[(.*?)\]\]/';
1254 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1256 $thelink = Linker
::makeMediaLinkObj( $title, $text );
1259 # Other kind of link
1260 # Make sure its target is non-empty
1261 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1262 $match[1] = substr( $match[1], 1 );
1264 if ( $match[1] !== false && $match[1] !== '' ) {
1265 if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1266 $trail = $submatch[1];
1270 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1271 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1274 $linkTarget = Linker
::normalizeSubpageLink( $title, $match[1], $linkText );
1276 $target = Title
::newFromText( $linkTarget );
1278 if ( $target->getText() == '' && !$target->isExternal()
1279 && !$local && $title
1281 $target = $title->createFragmentTarget( $target->getFragment() );
1284 $thelink = Linker
::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1289 // If the link is still valid, go ahead and replace it in!
1290 $comment = preg_replace(
1292 StringUtils
::escapeRegexReplacement( $thelink ),
1305 * Generates a link to the given Title
1307 * @note This is only public for technical reasons. It's not intended for use outside Linker.
1309 * @param LinkTarget $linkTarget
1310 * @param string $text
1311 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1312 * as used by WikiMap.
1313 * @param string|string[] $options See the $options parameter in Linker::link.
1315 * @return string HTML link
1317 public static function makeCommentLink(
1318 LinkTarget
$linkTarget, $text, $wikiId = null, $options = []
1320 if ( $wikiId !== null && !$linkTarget->isExternal() ) {
1321 $link = self
::makeExternalLink(
1322 WikiMap
::getForeignURL(
1324 $linkTarget->getNamespace() === 0
1325 ?
$linkTarget->getDBkey()
1326 : MWNamespace
::getCanonicalName( $linkTarget->getNamespace() ) . ':'
1327 . $linkTarget->getDBkey(),
1328 $linkTarget->getFragment()
1331 /* escape = */ false // Already escaped
1334 $link = self
::link( $linkTarget, $text, [], [], $options );
1341 * @param Title $contextTitle
1342 * @param string $target
1343 * @param string &$text
1346 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1349 # :Foobar -- override special treatment of prefix (images, language links)
1350 # /Foobar -- convert to CurrentPage/Foobar
1351 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1352 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1353 # ../Foobar -- convert to CurrentPage/Foobar,
1354 # (from CurrentPage/CurrentSubPage)
1355 # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1356 # (from CurrentPage/CurrentSubPage)
1358 $ret = $target; # default return value is no change
1360 # Some namespaces don't allow subpages,
1361 # so only perform processing if subpages are allowed
1362 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1363 $hash = strpos( $target, '#' );
1364 if ( $hash !== false ) {
1365 $suffix = substr( $target, $hash );
1366 $target = substr( $target, 0, $hash );
1371 $target = trim( $target );
1372 # Look at the first character
1373 if ( $target != '' && $target[0] === '/' ) {
1374 # / at end means we don't want the slash to be shown
1376 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1377 if ( $trailingSlashes ) {
1378 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1380 $noslash = substr( $target, 1 );
1383 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1384 if ( $text === '' ) {
1385 $text = $target . $suffix;
1386 } # this might be changed for ugliness reasons
1388 # check for .. subpage backlinks
1390 $nodotdot = $target;
1391 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1393 $nodotdot = substr( $nodotdot, 3 );
1395 if ( $dotdotcount > 0 ) {
1396 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1397 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1398 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1399 # / at the end means don't show full path
1400 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1401 $nodotdot = rtrim( $nodotdot, '/' );
1402 if ( $text === '' ) {
1403 $text = $nodotdot . $suffix;
1406 $nodotdot = trim( $nodotdot );
1407 if ( $nodotdot != '' ) {
1408 $ret .= '/' . $nodotdot;
1420 * Wrap a comment in standard punctuation and formatting if
1421 * it's non-empty, otherwise return empty string.
1423 * @since 1.16.3. $wikiId added in 1.26
1424 * @param string $comment
1425 * @param Title|null $title Title object (to generate link to section in autocomment) or null
1426 * @param bool $local Whether section links should refer to local page
1427 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1428 * For use with external changes.
1432 public static function commentBlock(
1433 $comment, $title = null, $local = false, $wikiId = null
1435 // '*' used to be the comment inserted by the software way back
1436 // in antiquity in case none was provided, here for backwards
1437 // compatibility, acc. to brion -ævar
1438 if ( $comment == '' ||
$comment == '*' ) {
1441 $formatted = self
::formatComment( $comment, $title, $local, $wikiId );
1442 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1443 return " <span class=\"comment\">$formatted</span>";
1448 * Wrap and format the given revision's comment block, if the current
1449 * user is allowed to view it.
1452 * @param Revision $rev
1453 * @param bool $local Whether section links should refer to local page
1454 * @param bool $isPublic Show only if all users can see it
1455 * @return string HTML fragment
1457 public static function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1458 if ( $rev->getComment( Revision
::RAW
) == "" ) {
1461 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1462 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1463 } elseif ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1464 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1465 $rev->getTitle(), $local );
1467 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1469 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1470 return " <span class=\"history-deleted\">$block</span>";
1480 public static function formatRevisionSize( $size ) {
1482 $stxt = wfMessage( 'historyempty' )->escaped();
1484 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1485 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1487 return "<span class=\"history-size\">$stxt</span>";
1491 * Add another level to the Table of Contents
1496 public static function tocIndent() {
1501 * Finish one or more sublevels on the Table of Contents
1507 public static function tocUnindent( $level ) {
1508 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1512 * parameter level defines if we are on an indentation level
1515 * @param string $anchor
1516 * @param string $tocline
1517 * @param string $tocnumber
1518 * @param string $level
1519 * @param string|bool $sectionIndex
1522 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1523 $classes = "toclevel-$level";
1524 if ( $sectionIndex !== false ) {
1525 $classes .= " tocsection-$sectionIndex";
1528 // \n<li class="$classes"><a href="#$anchor"><span class="tocnumber">
1529 // $tocnumber</span> <span class="toctext">$tocline</span></a>
1530 return "\n" . Html
::openElement( 'li', [ 'class' => $classes ] )
1531 . Html
::rawElement( 'a',
1532 [ 'href' => "#$anchor" ],
1533 Html
::element( 'span', [ 'class' => 'tocnumber' ], $tocnumber )
1535 . Html
::rawElement( 'span', [ 'class' => 'toctext' ], $tocline )
1540 * End a Table Of Contents line.
1541 * tocUnindent() will be used instead if we're ending a line below
1546 public static function tocLineEnd() {
1551 * Wraps the TOC in a table and provides the hide/collapse javascript.
1554 * @param string $toc Html of the Table Of Contents
1555 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1556 * @return string Full html of the TOC
1558 public static function tocList( $toc, $lang = false ) {
1559 $lang = wfGetLangObj( $lang );
1560 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1562 return '<div id="toc" class="toc">'
1563 . Html
::openElement( 'div', [
1564 'class' => 'toctitle',
1565 'lang' => $lang->getHtmlCode(),
1566 'dir' => $lang->getDir(),
1568 . '<h2>' . $title . "</h2></div>\n"
1570 . "</ul>\n</div>\n";
1574 * Generate a table of contents from a section tree.
1576 * @since 1.16.3. $lang added in 1.17
1577 * @param array $tree Return value of ParserOutput::getSections()
1578 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1579 * @return string HTML fragment
1581 public static function generateTOC( $tree, $lang = false ) {
1584 foreach ( $tree as $section ) {
1585 if ( $section['toclevel'] > $lastLevel ) {
1586 $toc .= self
::tocIndent();
1587 } elseif ( $section['toclevel'] < $lastLevel ) {
1588 $toc .= self
::tocUnindent(
1589 $lastLevel - $section['toclevel'] );
1591 $toc .= self
::tocLineEnd();
1594 $toc .= self
::tocLine( $section['anchor'],
1595 $section['line'], $section['number'],
1596 $section['toclevel'], $section['index'] );
1597 $lastLevel = $section['toclevel'];
1599 $toc .= self
::tocLineEnd();
1600 return self
::tocList( $toc, $lang );
1604 * Create a headline for content
1607 * @param int $level The level of the headline (1-6)
1608 * @param string $attribs Any attributes for the headline, starting with
1609 * a space and ending with '>'
1610 * This *must* be at least '>' for no attribs
1611 * @param string $anchor The anchor to give the headline (the bit after the #)
1612 * @param string $html HTML for the text of the header
1613 * @param string $link HTML to add for the section edit link
1614 * @param string|bool $fallbackAnchor A second, optional anchor to give for
1615 * backward compatibility (false to omit)
1617 * @return string HTML headline
1619 public static function makeHeadline( $level, $attribs, $anchor, $html,
1620 $link, $fallbackAnchor = false
1622 $anchorEscaped = htmlspecialchars( $anchor );
1624 if ( $fallbackAnchor !== false && $fallbackAnchor !== $anchor ) {
1625 $fallbackAnchor = htmlspecialchars( $fallbackAnchor );
1626 $fallback = "<span id=\"$fallbackAnchor\"></span>";
1628 $ret = "<h$level$attribs"
1629 . "$fallback<span class=\"mw-headline\" id=\"$anchorEscaped\">$html</span>"
1637 * Split a link trail, return the "inside" portion and the remainder of the trail
1638 * as a two-element array
1639 * @param string $trail
1642 static function splitTrail( $trail ) {
1644 $regex = $wgContLang->linkTrail();
1646 if ( $trail !== '' ) {
1648 if ( preg_match( $regex, $trail, $m ) ) {
1653 return [ $inside, $trail ];
1657 * Generate a rollback link for a given revision. Currently it's the
1658 * caller's responsibility to ensure that the revision is the top one. If
1659 * it's not, of course, the user will get an error message.
1661 * If the calling page is called with the parameter &bot=1, all rollback
1662 * links also get that parameter. It causes the edit itself and the rollback
1663 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1664 * changes, so this allows sysops to combat a busy vandal without bothering
1667 * If the option verify is set this function will return the link only in case the
1668 * revision can be reverted. Please note that due to performance limitations
1669 * it might be assumed that a user isn't the only contributor of a page while
1670 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1671 * work if $wgShowRollbackEditCount is disabled, so this can only function
1672 * as an additional check.
1674 * If the option noBrackets is set the rollback link wont be enclosed in "[]".
1676 * @since 1.16.3. $context added in 1.20. $options added in 1.21
1678 * @param Revision $rev
1679 * @param IContextSource $context Context to use or null for the main context.
1680 * @param array $options
1683 public static function generateRollback( $rev, IContextSource
$context = null,
1684 $options = [ 'verify' ]
1686 if ( $context === null ) {
1687 $context = RequestContext
::getMain();
1691 if ( in_array( 'verify', $options, true ) ) {
1692 $editCount = self
::getRollbackEditCount( $rev, true );
1693 if ( $editCount === false ) {
1698 $inner = self
::buildRollbackLink( $rev, $context, $editCount );
1700 if ( !in_array( 'noBrackets', $options, true ) ) {
1701 $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1704 return '<span class="mw-rollback-link">' . $inner . '</span>';
1708 * This function will return the number of revisions which a rollback
1709 * would revert and, if $verify is set it will verify that a revision
1710 * can be reverted (that the user isn't the only contributor and the
1711 * revision we might rollback to isn't deleted). These checks can only
1712 * function as an additional check as this function only checks against
1713 * the last $wgShowRollbackEditCount edits.
1715 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1716 * is set and the user is the only contributor of the page.
1718 * @param Revision $rev
1719 * @param bool $verify Try to verify that this revision can really be rolled back
1720 * @return int|bool|null
1722 public static function getRollbackEditCount( $rev, $verify ) {
1723 global $wgShowRollbackEditCount;
1724 if ( !is_int( $wgShowRollbackEditCount ) ||
!$wgShowRollbackEditCount > 0 ) {
1725 // Nothing has happened, indicate this by returning 'null'
1729 $dbr = wfGetDB( DB_REPLICA
);
1731 // Up to the value of $wgShowRollbackEditCount revisions are counted
1732 $revQuery = Revision
::getQueryInfo();
1733 $res = $dbr->select(
1734 $revQuery['tables'],
1735 [ 'rev_user_text' => $revQuery['fields']['rev_user_text'], 'rev_deleted' ],
1736 // $rev->getPage() returns null sometimes
1737 [ 'rev_page' => $rev->getTitle()->getArticleID() ],
1740 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
1741 'ORDER BY' => 'rev_timestamp DESC',
1742 'LIMIT' => $wgShowRollbackEditCount +
1
1749 foreach ( $res as $row ) {
1750 if ( $rev->getUserText( Revision
::RAW
) != $row->rev_user_text
) {
1752 ( $row->rev_deleted
& Revision
::DELETED_TEXT
1753 ||
$row->rev_deleted
& Revision
::DELETED_USER
1755 // If the user or the text of the revision we might rollback
1756 // to is deleted in some way we can't rollback. Similar to
1757 // the sanity checks in WikiPage::commitRollback.
1766 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1767 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1768 // and there weren't any other revisions. That means that the current user is the only
1769 // editor, so we can't rollback
1776 * Build a raw rollback link, useful for collections of "tool" links
1778 * @since 1.16.3. $context added in 1.20. $editCount added in 1.21
1779 * @param Revision $rev
1780 * @param IContextSource|null $context Context to use or null for the main context.
1781 * @param int $editCount Number of edits that would be reverted
1782 * @return string HTML fragment
1784 public static function buildRollbackLink( $rev, IContextSource
$context = null,
1787 global $wgShowRollbackEditCount, $wgMiserMode;
1789 // To config which pages are affected by miser mode
1790 $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
1792 if ( $context === null ) {
1793 $context = RequestContext
::getMain();
1796 $title = $rev->getTitle();
1798 'action' => 'rollback',
1799 'from' => $rev->getUserText(),
1800 'token' => $context->getUser()->getEditToken( 'rollback' ),
1803 'data-mw' => 'interface',
1804 'title' => $context->msg( 'tooltip-rollback' )->text(),
1806 $options = [ 'known', 'noclasses' ];
1808 if ( $context->getRequest()->getBool( 'bot' ) ) {
1809 $query['bot'] = '1';
1810 $query['hidediff'] = '1'; // T17999
1813 $disableRollbackEditCount = false;
1814 if ( $wgMiserMode ) {
1815 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1816 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1817 $disableRollbackEditCount = true;
1823 if ( !$disableRollbackEditCount
1824 && is_int( $wgShowRollbackEditCount )
1825 && $wgShowRollbackEditCount > 0
1827 if ( !is_numeric( $editCount ) ) {
1828 $editCount = self
::getRollbackEditCount( $rev, false );
1831 if ( $editCount > $wgShowRollbackEditCount ) {
1832 $html = $context->msg( 'rollbacklinkcount-morethan' )
1833 ->numParams( $wgShowRollbackEditCount )->parse();
1835 $html = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1838 return self
::link( $title, $html, $attrs, $query, $options );
1840 $html = $context->msg( 'rollbacklink' )->escaped();
1841 return self
::link( $title, $html, $attrs, $query, $options );
1846 * @deprecated since 1.28, use TemplatesOnThisPageFormatter directly
1848 * Returns HTML for the "templates used on this page" list.
1850 * Make an HTML list of templates, and then add a "More..." link at
1851 * the bottom. If $more is null, do not add a "More..." link. If $more
1852 * is a Title, make a link to that title and use it. If $more is a string,
1853 * directly paste it in as the link (escaping needs to be done manually).
1854 * Finally, if $more is a Message, call toString().
1856 * @since 1.16.3. $more added in 1.21
1857 * @param Title[] $templates Array of templates
1858 * @param bool $preview Whether this is for a preview
1859 * @param bool $section Whether this is for a section edit
1860 * @param Title|Message|string|null $more An escaped link for "More..." of the templates
1861 * @return string HTML output
1863 public static function formatTemplates( $templates, $preview = false,
1864 $section = false, $more = null
1866 wfDeprecated( __METHOD__
, '1.28' );
1871 } elseif ( $section ) {
1875 if ( $more instanceof Message
) {
1876 $more = $more->toString();
1879 $formatter = new TemplatesOnThisPageFormatter(
1880 RequestContext
::getMain(),
1881 MediaWikiServices
::getInstance()->getLinkRenderer()
1883 return $formatter->format( $templates, $type, $more );
1887 * Returns HTML for the "hidden categories on this page" list.
1890 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1892 * @return string HTML output
1894 public static function formatHiddenCategories( $hiddencats ) {
1896 if ( count( $hiddencats ) > 0 ) {
1897 # Construct the HTML
1898 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1899 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
1900 $outText .= "</div><ul>\n";
1902 foreach ( $hiddencats as $titleObj ) {
1903 # If it's hidden, it must exist - no need to check with a LinkBatch
1905 . self
::link( $titleObj, null, [], [], 'known' )
1908 $outText .= '</ul>';
1914 * @deprecated since 1.28, use Language::formatSize() directly
1916 * Format a size in bytes for output, using an appropriate
1917 * unit (B, KB, MB or GB) according to the magnitude in question
1920 * @param int $size Size to format
1923 public static function formatSize( $size ) {
1924 wfDeprecated( __METHOD__
, '1.28' );
1927 return htmlspecialchars( $wgLang->formatSize( $size ) );
1931 * Given the id of an interface element, constructs the appropriate title
1932 * attribute from the system messages. (Note, this is usually the id but
1933 * isn't always, because sometimes the accesskey needs to go on a different
1934 * element than the id, for reverse-compatibility, etc.)
1936 * @since 1.16.3 $msgParams added in 1.27
1937 * @param string $name Id of the element, minus prefixes.
1938 * @param string|array|null $options Null, string or array with some of the following options:
1939 * - 'withaccess' to add an access-key hint
1940 * - 'nonexisting' to add an accessibility hint that page does not exist
1941 * @param array $msgParams Parameters to pass to the message
1943 * @return string Contents of the title attribute (which you must HTML-
1944 * escape), or false for no title attribute
1946 public static function titleAttrib( $name, $options = null, array $msgParams = [] ) {
1947 $message = wfMessage( "tooltip-$name", $msgParams );
1948 if ( !$message->exists() ) {
1951 $tooltip = $message->text();
1952 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1953 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1954 # Message equal to '-' means suppress it.
1955 if ( $tooltip == '-' ) {
1960 $options = (array)$options;
1962 if ( in_array( 'nonexisting', $options ) ) {
1963 $tooltip = wfMessage( 'red-link-title', $tooltip ?
: '' )->text();
1965 if ( in_array( 'withaccess', $options ) ) {
1966 $accesskey = self
::accesskey( $name );
1967 if ( $accesskey !== false ) {
1968 // Should be build the same as in jquery.accessKeyLabel.js
1969 if ( $tooltip === false ||
$tooltip === '' ) {
1970 $tooltip = wfMessage( 'brackets', $accesskey )->text();
1972 $tooltip .= wfMessage( 'word-separator' )->text();
1973 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
1981 public static $accesskeycache;
1984 * Given the id of an interface element, constructs the appropriate
1985 * accesskey attribute from the system messages. (Note, this is usually
1986 * the id but isn't always, because sometimes the accesskey needs to go on
1987 * a different element than the id, for reverse-compatibility, etc.)
1990 * @param string $name Id of the element, minus prefixes.
1991 * @return string Contents of the accesskey attribute (which you must HTML-
1992 * escape), or false for no accesskey attribute
1994 public static function accesskey( $name ) {
1995 if ( isset( self
::$accesskeycache[$name] ) ) {
1996 return self
::$accesskeycache[$name];
1999 $message = wfMessage( "accesskey-$name" );
2001 if ( !$message->exists() ) {
2004 $accesskey = $message->plain();
2005 if ( $accesskey === '' ||
$accesskey === '-' ) {
2006 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2007 # attribute, but this is broken for accesskey: that might be a useful
2013 self
::$accesskeycache[$name] = $accesskey;
2014 return self
::$accesskeycache[$name];
2018 * Get a revision-deletion link, or disabled link, or nothing, depending
2019 * on user permissions & the settings on the revision.
2021 * Will use forward-compatible revision ID in the Special:RevDelete link
2022 * if possible, otherwise the timestamp-based ID which may break after
2026 * @param Revision $rev
2027 * @param Title $title
2028 * @return string HTML fragment
2030 public static function getRevDeleteLink( User
$user, Revision
$rev, Title
$title ) {
2031 $canHide = $user->isAllowed( 'deleterevision' );
2032 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2036 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
2037 return self
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2039 if ( $rev->getId() ) {
2040 // RevDelete links using revision ID are stable across
2041 // page deletion and undeletion; use when possible.
2043 'type' => 'revision',
2044 'target' => $title->getPrefixedDBkey(),
2045 'ids' => $rev->getId()
2048 // Older deleted entries didn't save a revision ID.
2049 // We have to refer to these by timestamp, ick!
2051 'type' => 'archive',
2052 'target' => $title->getPrefixedDBkey(),
2053 'ids' => $rev->getTimestamp()
2056 return self
::revDeleteLink( $query,
2057 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
2062 * Creates a (show/hide) link for deleting revisions/log entries
2064 * @param array $query Query parameters to be passed to link()
2065 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2066 * @param bool $delete Set to true to use (show/hide) rather than (show)
2068 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2069 * span to allow for customization of appearance with CSS
2071 public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2072 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
2073 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2074 $html = wfMessage( $msgKey )->escaped();
2075 $tag = $restricted ?
'strong' : 'span';
2076 $link = self
::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2079 [ 'class' => 'mw-revdelundel-link' ],
2080 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2085 * Creates a dead (show/hide) link for deleting revisions/log entries
2088 * @param bool $delete Set to true to use (show/hide) rather than (show)
2090 * @return string HTML text wrapped in a span to allow for customization
2091 * of appearance with CSS
2093 public static function revDeleteLinkDisabled( $delete = true ) {
2094 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2095 $html = wfMessage( $msgKey )->escaped();
2096 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2097 return Xml
::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2101 * Returns the attributes for the tooltip and access key.
2103 * @since 1.16.3. $msgParams introduced in 1.27
2104 * @param string $name
2105 * @param array $msgParams Params for constructing the message
2106 * @param string|array|null $options Options to be passed to titleAttrib.
2108 * @see Linker::titleAttrib for what options could be passed to $options.
2112 public static function tooltipAndAccesskeyAttribs(
2114 array $msgParams = [],
2117 $options = (array)$options;
2118 $options[] = 'withaccess';
2121 'title' => self
::titleAttrib( $name, $options, $msgParams ),
2122 'accesskey' => self
::accesskey( $name )
2124 if ( $attribs['title'] === false ) {
2125 unset( $attribs['title'] );
2127 if ( $attribs['accesskey'] === false ) {
2128 unset( $attribs['accesskey'] );
2134 * Returns raw bits of HTML, use titleAttrib()
2136 * @param string $name
2137 * @param array|null $options
2138 * @return null|string
2140 public static function tooltip( $name, $options = null ) {
2141 $tooltip = self
::titleAttrib( $name, $options );
2142 if ( $tooltip === false ) {
2145 return Xml
::expandAttributes( [