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 LinkTarget, 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 LinkTarget (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 LinkTarget; or if the LinkTarget 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 );
118 if ( in_array( 'known', $options, true ) ) {
119 return $linkRenderer->makeKnownLink( $target, $text, $customAttribs, $query );
122 if ( in_array( 'broken', $options, true ) ) {
123 return $linkRenderer->makeBrokenLink( $target, $text, $customAttribs, $query );
126 if ( in_array( 'noclasses', $options, true ) ) {
127 return $linkRenderer->makePreloadedLink( $target, $text, '', $customAttribs, $query );
130 return $linkRenderer->makeLink( $target, $text, $customAttribs, $query );
134 * Identical to link(), except $options defaults to 'known'.
137 * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
139 * @param LinkTarget $target
140 * @param string $html
141 * @param array $customAttribs
142 * @param array $query
143 * @param string|array $options
146 public static function linkKnown(
147 $target, $html = null, $customAttribs = [],
148 $query = [], $options = [ 'known' ]
150 return self
::link( $target, $html, $customAttribs, $query, $options );
154 * Make appropriate markup for a link to the current article. This is since
155 * MediaWiki 1.29.0 rendered as an <a> tag without an href and with a class
156 * showing the link text. The calling sequence is the same as for the other
157 * make*LinkObj static functions, but $query is not used.
160 * @param LinkTarget $nt
161 * @param string $html [optional]
162 * @param string $query [optional]
163 * @param string $trail [optional]
164 * @param string $prefix [optional]
168 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
169 $nt = Title
::newFromLinkTarget( $nt );
170 $ret = "<a class=\"mw-selflink selflink\">{$prefix}{$html}</a>{$trail}";
171 if ( !Hooks
::run( 'SelfLinkBegin', [ $nt, &$html, &$trail, &$prefix, &$ret ] ) ) {
176 $html = htmlspecialchars( $nt->getPrefixedText() );
178 list( $inside, $trail ) = self
::splitTrail( $trail );
179 return "<a class=\"mw-selflink selflink\">{$prefix}{$html}{$inside}</a>{$trail}";
183 * Get a message saying that an invalid title was encountered.
184 * This should be called after a method like Title::makeTitleSafe() returned
185 * a value indicating that the title object is invalid.
187 * @param IContextSource $context Context to use to get the messages
188 * @param int $namespace Namespace number
189 * @param string $title Text of the title, without the namespace part
192 public static function getInvalidTitleDescription( IContextSource
$context, $namespace, $title ) {
193 // First we check whether the namespace exists or not.
194 if ( MWNamespace
::exists( $namespace ) ) {
195 if ( $namespace == NS_MAIN
) {
196 $name = $context->msg( 'blanknamespace' )->text();
198 $name = MediaWikiServices
::getInstance()->getContentLanguage()->
199 getFormattedNsText( $namespace );
201 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
204 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
209 * @param LinkTarget $target
212 public static function normaliseSpecialPage( LinkTarget
$target ) {
213 if ( $target->getNamespace() == NS_SPECIAL
&& !$target->isExternal() ) {
214 list( $name, $subpage ) = MediaWikiServices
::getInstance()->getSpecialPageFactory()->
215 resolveAlias( $target->getDBkey() );
217 return SpecialPage
::getTitleValueFor( $name, $subpage, $target->getFragment() );
225 * Returns the filename part of an url.
226 * Used as alternative text for external images.
232 private static function fnamePart( $url ) {
233 $basename = strrchr( $url, '/' );
234 if ( $basename === false ) {
237 $basename = substr( $basename, 1 );
243 * Return the code for images which were added via external links,
244 * via Parser::maybeMakeExternalImage().
252 public static function makeExternalImage( $url, $alt = '' ) {
254 $alt = self
::fnamePart( $url );
257 $success = Hooks
::run( 'LinkerMakeExternalImage', [ &$url, &$alt, &$img ] );
259 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
260 . "with url {$url} and alt text {$alt} to {$img}\n", true );
263 return Html
::element( 'img',
272 * Given parameters derived from [[Image:Foo|options...]], generate the
273 * HTML that that syntax inserts in the page.
275 * @param Parser $parser
276 * @param LinkTarget $title LinkTarget object of the file (not the currently viewed page)
277 * @param File $file File object, or false if it doesn't exist
278 * @param array $frameParams Associative array of parameters external to the media handler.
279 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
280 * will often be false.
281 * thumbnail If present, downscale and frame
282 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
283 * framed Shows image in original size in a frame
284 * frameless Downscale but don't frame
285 * upright If present, tweak default sizes for portrait orientation
286 * upright_factor Fudge factor for "upright" tweak (default 0.75)
287 * border If present, show a border around the image
288 * align Horizontal alignment (left, right, center, none)
289 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
290 * bottom, text-bottom)
291 * alt Alternate text for image (i.e. alt attribute). Plain text.
292 * class HTML for image classes. Plain text.
293 * caption HTML for image caption.
294 * link-url URL to link to
295 * link-title LinkTarget object to link to
296 * link-target Value for the target attribute, only with link-url
297 * no-link Boolean, suppress description link
298 * targetlang (optional) Target language code, see Parser::getTargetLanguage()
300 * @param array $handlerParams Associative array of media handler parameters, to be passed
301 * to transform(). Typical keys are "width" and "page".
302 * @param string|bool $time Timestamp of the file, set as false for current
303 * @param string $query Query params for desc url
304 * @param int|null $widthOption Used by the parser to remember the user preference thumbnailsize
306 * @return string HTML for an image, with links, wrappers, etc.
308 public static function makeImageLink( Parser
$parser, LinkTarget
$title,
309 $file, $frameParams = [], $handlerParams = [], $time = false,
310 $query = "", $widthOption = null
312 $title = Title
::newFromLinkTarget( $title );
314 $dummy = new DummyLinker
;
315 if ( !Hooks
::run( 'ImageBeforeProduceHTML', [ &$dummy, &$title,
316 &$file, &$frameParams, &$handlerParams, &$time, &$res,
317 $parser, &$query, &$widthOption
322 if ( $file && !$file->allowInlineDisplay() ) {
323 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
324 return self
::link( $title );
327 // Clean up parameters
328 $page = $handlerParams['page'] ??
false;
329 if ( !isset( $frameParams['align'] ) ) {
330 $frameParams['align'] = '';
332 if ( !isset( $frameParams['alt'] ) ) {
333 $frameParams['alt'] = '';
335 if ( !isset( $frameParams['title'] ) ) {
336 $frameParams['title'] = '';
338 if ( !isset( $frameParams['class'] ) ) {
339 $frameParams['class'] = '';
342 $prefix = $postfix = '';
344 if ( $frameParams['align'] == 'center' ) {
345 $prefix = '<div class="center">';
347 $frameParams['align'] = 'none';
349 if ( $file && !isset( $handlerParams['width'] ) ) {
350 if ( isset( $handlerParams['height'] ) && $file->isVectorized() ) {
351 // If its a vector image, and user only specifies height
352 // we don't want it to be limited by its "normal" width.
353 global $wgSVGMaxSize;
354 $handlerParams['width'] = $wgSVGMaxSize;
356 $handlerParams['width'] = $file->getWidth( $page );
359 if ( isset( $frameParams['thumbnail'] )
360 ||
isset( $frameParams['manualthumb'] )
361 ||
isset( $frameParams['framed'] )
362 ||
isset( $frameParams['frameless'] )
363 ||
!$handlerParams['width']
365 global $wgThumbLimits, $wgThumbUpright;
367 if ( $widthOption === null ||
!isset( $wgThumbLimits[$widthOption] ) ) {
368 $widthOption = User
::getDefaultOption( 'thumbsize' );
371 // Reduce width for upright images when parameter 'upright' is used
372 if ( isset( $frameParams['upright'] ) && $frameParams['upright'] == 0 ) {
373 $frameParams['upright'] = $wgThumbUpright;
376 // For caching health: If width scaled down due to upright
377 // parameter, round to full __0 pixel to avoid the creation of a
378 // lot of odd thumbs.
379 $prefWidth = isset( $frameParams['upright'] ) ?
380 round( $wgThumbLimits[$widthOption] * $frameParams['upright'], -1 ) :
381 $wgThumbLimits[$widthOption];
383 // Use width which is smaller: real image width or user preference width
384 // Unless image is scalable vector.
385 if ( !isset( $handlerParams['height'] ) && ( $handlerParams['width'] <= 0 ||
386 $prefWidth < $handlerParams['width'] ||
$file->isVectorized() ) ) {
387 $handlerParams['width'] = $prefWidth;
392 if ( isset( $frameParams['thumbnail'] ) ||
isset( $frameParams['manualthumb'] )
393 ||
isset( $frameParams['framed'] )
395 # Create a thumbnail. Alignment depends on the writing direction of
396 # the page content language (right-aligned for LTR languages,
397 # left-aligned for RTL languages)
398 # If a thumbnail width has not been provided, it is set
399 # to the default user option as specified in Language*.php
400 if ( $frameParams['align'] == '' ) {
401 $frameParams['align'] = $parser->getTargetLanguage()->alignEnd();
404 self
::makeThumbLink2( $title, $file, $frameParams, $handlerParams, $time, $query ) .
408 if ( $file && isset( $frameParams['frameless'] ) ) {
409 $srcWidth = $file->getWidth( $page );
410 # For "frameless" option: do not present an image bigger than the
411 # source (for bitmap-style images). This is the same behavior as the
412 # "thumb" option does it already.
413 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
414 $handlerParams['width'] = $srcWidth;
418 if ( $file && isset( $handlerParams['width'] ) ) {
419 # Create a resized image, without the additional thumbnail features
420 $thumb = $file->transform( $handlerParams );
426 $s = self
::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
428 self
::processResponsiveImages( $file, $thumb, $handlerParams );
430 'alt' => $frameParams['alt'],
431 'title' => $frameParams['title'],
432 'valign' => $frameParams['valign'] ??
false,
433 'img-class' => $frameParams['class'] ];
434 if ( isset( $frameParams['border'] ) ) {
435 $params['img-class'] .= ( $params['img-class'] !== '' ?
' ' : '' ) . 'thumbborder';
437 $params = self
::getImageLinkMTOParams( $frameParams, $query, $parser ) +
$params;
439 $s = $thumb->toHtml( $params );
441 if ( $frameParams['align'] != '' ) {
442 $s = Html
::rawElement(
444 [ 'class' => 'float' . $frameParams['align'] ],
448 return str_replace( "\n", ' ', $prefix . $s . $postfix );
452 * Get the link parameters for MediaTransformOutput::toHtml() from given
453 * frame parameters supplied by the Parser.
454 * @param array $frameParams The frame parameters
455 * @param string $query An optional query string to add to description page links
456 * @param Parser|null $parser
459 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
461 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
462 $mtoParams['custom-url-link'] = $frameParams['link-url'];
463 if ( isset( $frameParams['link-target'] ) ) {
464 $mtoParams['custom-target-link'] = $frameParams['link-target'];
467 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
468 foreach ( $extLinkAttrs as $name => $val ) {
469 // Currently could include 'rel' and 'target'
470 $mtoParams['parser-extlink-' . $name] = $val;
473 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
474 $mtoParams['custom-title-link'] = Title
::newFromLinkTarget(
475 self
::normaliseSpecialPage( $frameParams['link-title'] )
477 } elseif ( !empty( $frameParams['no-link'] ) ) {
480 $mtoParams['desc-link'] = true;
481 $mtoParams['desc-query'] = $query;
487 * Make HTML for a thumbnail including image, border and caption
488 * @param LinkTarget $title
489 * @param File|bool $file File object or false if it doesn't exist
490 * @param string $label
492 * @param string $align
493 * @param array $params
494 * @param bool $framed
495 * @param string $manualthumb
498 public static function makeThumbLinkObj( LinkTarget
$title, $file, $label = '', $alt = '',
499 $align = 'right', $params = [], $framed = false, $manualthumb = ""
507 $frameParams['framed'] = true;
509 if ( $manualthumb ) {
510 $frameParams['manualthumb'] = $manualthumb;
512 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
516 * @param LinkTarget $title
518 * @param array $frameParams
519 * @param array $handlerParams
521 * @param string $query
524 public static function makeThumbLink2( LinkTarget
$title, $file, $frameParams = [],
525 $handlerParams = [], $time = false, $query = ""
527 $exists = $file && $file->exists();
529 $page = $handlerParams['page'] ??
false;
530 if ( !isset( $frameParams['align'] ) ) {
531 $frameParams['align'] = 'right';
533 if ( !isset( $frameParams['alt'] ) ) {
534 $frameParams['alt'] = '';
536 if ( !isset( $frameParams['title'] ) ) {
537 $frameParams['title'] = '';
539 if ( !isset( $frameParams['caption'] ) ) {
540 $frameParams['caption'] = '';
543 if ( empty( $handlerParams['width'] ) ) {
544 // Reduce width for upright images when parameter 'upright' is used
545 $handlerParams['width'] = isset( $frameParams['upright'] ) ?
130 : 180;
549 $manualthumb = false;
552 $outerWidth = $handlerParams['width'] +
2;
554 if ( isset( $frameParams['manualthumb'] ) ) {
555 # Use manually specified thumbnail
556 $manual_title = Title
::makeTitleSafe( NS_FILE
, $frameParams['manualthumb'] );
557 if ( $manual_title ) {
558 $manual_img = wfFindFile( $manual_title );
560 $thumb = $manual_img->getUnscaledThumb( $handlerParams );
566 } elseif ( isset( $frameParams['framed'] ) ) {
567 // Use image dimensions, don't scale
568 $thumb = $file->getUnscaledThumb( $handlerParams );
571 # Do not present an image bigger than the source, for bitmap-style images
572 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
573 $srcWidth = $file->getWidth( $page );
574 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
575 $handlerParams['width'] = $srcWidth;
577 $thumb = $file->transform( $handlerParams );
581 $outerWidth = $thumb->getWidth() +
2;
583 $outerWidth = $handlerParams['width'] +
2;
587 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
588 # So we don't need to pass it here in $query. However, the URL for the
589 # zoom icon still needs it, so we make a unique query for it. See T16771
590 $url = Title
::newFromLinkTarget( $title )->getLocalURL( $query );
592 $url = wfAppendQuery( $url, [ 'page' => $page ] );
595 && !isset( $frameParams['link-title'] )
596 && !isset( $frameParams['link-url'] )
597 && !isset( $frameParams['no-link'] ) ) {
598 $frameParams['link-url'] = $url;
601 $s = "<div class=\"thumb t{$frameParams['align']}\">"
602 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
605 $s .= self
::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
607 } elseif ( !$thumb ) {
608 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
611 if ( !$noscale && !$manualthumb ) {
612 self
::processResponsiveImages( $file, $thumb, $handlerParams );
615 'alt' => $frameParams['alt'],
616 'title' => $frameParams['title'],
617 'img-class' => ( isset( $frameParams['class'] ) && $frameParams['class'] !== ''
618 ?
$frameParams['class'] . ' '
619 : '' ) . 'thumbimage'
621 $params = self
::getImageLinkMTOParams( $frameParams, $query ) +
$params;
622 $s .= $thumb->toHtml( $params );
623 if ( isset( $frameParams['framed'] ) ) {
626 $zoomIcon = Html
::rawElement( 'div', [ 'class' => 'magnify' ],
627 Html
::rawElement( 'a', [
629 'class' => 'internal',
630 'title' => wfMessage( 'thumbnail-more' )->text() ],
634 $s .= ' <div class="thumbcaption">' . $zoomIcon . $frameParams['caption'] . "</div></div></div>";
635 return str_replace( "\n", ' ', $s );
639 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
643 * @param MediaTransformOutput $thumb
644 * @param array $hp Image parameters
646 public static function processResponsiveImages( $file, $thumb, $hp ) {
647 global $wgResponsiveImages;
648 if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
650 $hp15['width'] = round( $hp['width'] * 1.5 );
652 $hp20['width'] = $hp['width'] * 2;
653 if ( isset( $hp['height'] ) ) {
654 $hp15['height'] = round( $hp['height'] * 1.5 );
655 $hp20['height'] = $hp['height'] * 2;
658 $thumb15 = $file->transform( $hp15 );
659 $thumb20 = $file->transform( $hp20 );
660 if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
661 $thumb->responsiveUrls
['1.5'] = $thumb15->getUrl();
663 if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
664 $thumb->responsiveUrls
['2'] = $thumb20->getUrl();
670 * Make a "broken" link to an image
673 * @param LinkTarget $title
674 * @param string $label Link label (plain text)
675 * @param string $query Query string
676 * @param string $unused1 Unused parameter kept for b/c
677 * @param string $unused2 Unused parameter kept for b/c
678 * @param bool $time A file of a certain timestamp was requested
681 public static function makeBrokenImageLinkObj( $title, $label = '',
682 $query = '', $unused1 = '', $unused2 = '', $time = false
684 if ( !$title instanceof LinkTarget
) {
685 wfWarn( __METHOD__
. ': Requires $title to be a LinkTarget object.' );
686 return "<!-- ERROR -->" . htmlspecialchars( $label );
689 $title = Title
::castFromLinkTarget( $title );
691 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
692 if ( $label == '' ) {
693 $label = $title->getPrefixedText();
695 $encLabel = htmlspecialchars( $label );
696 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
698 if ( ( $wgUploadMissingFileUrl ||
$wgUploadNavigationUrl ||
$wgEnableUploads )
701 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
704 // We already know it's a redirect, so mark it
709 [ 'class' => 'mw-redirect' ],
710 wfCgiToArray( $query ),
711 [ 'known', 'noclasses' ]
715 $href = self
::getUploadUrl( $title, $query );
717 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
718 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
722 return self
::link( $title, $encLabel, [], wfCgiToArray( $query ), [ 'known', 'noclasses' ] );
726 * Get the URL to upload a certain file
729 * @param LinkTarget $destFile LinkTarget object of the file to upload
730 * @param string $query Urlencoded query string to prepend
731 * @return string Urlencoded URL
733 protected static function getUploadUrl( $destFile, $query = '' ) {
734 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
735 $q = 'wpDestFile=' . Title
::castFromLinkTarget( $destFile )->getPartialURL();
736 if ( $query != '' ) {
740 if ( $wgUploadMissingFileUrl ) {
741 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
744 if ( $wgUploadNavigationUrl ) {
745 return wfAppendQuery( $wgUploadNavigationUrl, $q );
748 $upload = SpecialPage
::getTitleFor( 'Upload' );
750 return $upload->getLocalURL( $q );
754 * Create a direct link to a given uploaded file.
757 * @param LinkTarget $title
758 * @param string $html Pre-sanitized HTML
759 * @param string $time MW timestamp of file creation time
760 * @return string HTML
762 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
763 $img = wfFindFile( $title, [ 'time' => $time ] );
764 return self
::makeMediaLinkFile( $title, $img, $html );
768 * Create a direct link to a given uploaded file.
769 * This will make a broken link if $file is false.
772 * @param LinkTarget $title
773 * @param File|bool $file File object or false
774 * @param string $html Pre-sanitized HTML
775 * @return string HTML
777 * @todo Handle invalid or missing images better.
779 public static function makeMediaLinkFile( LinkTarget
$title, $file, $html = '' ) {
780 if ( $file && $file->exists() ) {
781 $url = $file->getUrl();
784 $url = self
::getUploadUrl( $title );
788 $alt = $title->getText();
800 if ( !Hooks
::run( 'LinkerMakeMediaLinkFile',
801 [ Title
::castFromLinkTarget( $title ), $file, &$html, &$attribs, &$ret ] ) ) {
802 wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
803 . "with url {$url} and text {$html} to {$ret}\n", true );
807 return Html
::rawElement( 'a', $attribs, $html );
811 * Make a link to a special page given its name and, optionally,
812 * a message key from the link text.
813 * Usage example: Linker::specialLink( 'Recentchanges' )
816 * @param string $name
820 public static function specialLink( $name, $key = '' ) {
822 $key = strtolower( $name );
825 return self
::linkKnown( SpecialPage
::getTitleFor( $name ), wfMessage( $key )->escaped() );
829 * Make an external link
831 * @since 1.16.3. $title added in 1.21
832 * @param string $url URL to link to
833 * @param-taint $url escapes_html
834 * @param string $text Text of link
835 * @param-taint $text escapes_html
836 * @param bool $escape Do we escape the link text?
837 * @param-taint $escape none
838 * @param string $linktype Type of external link. Gets added to the classes
839 * @param-taint $linktype escapes_html
840 * @param array $attribs Array of extra attributes to <a>
841 * @param-taint $attribs escapes_html
842 * @param LinkTarget|null $title LinkTarget object used for title specific link attributes
843 * @param-taint $title none
846 public static function makeExternalLink( $url, $text, $escape = true,
847 $linktype = '', $attribs = [], $title = null
852 $class .= " $linktype";
854 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
855 $class .= " {$attribs['class']}";
857 $attribs['class'] = $class;
860 $text = htmlspecialchars( $text );
866 $newRel = Parser
::getExternalLinkRel( $url, $title );
867 if ( !isset( $attribs['rel'] ) ||
$attribs['rel'] === '' ) {
868 $attribs['rel'] = $newRel;
869 } elseif ( $newRel !== '' ) {
870 // Merge the rel attributes.
871 $newRels = explode( ' ', $newRel );
872 $oldRels = explode( ' ', $attribs['rel'] );
873 $combined = array_unique( array_merge( $newRels, $oldRels ) );
874 $attribs['rel'] = implode( ' ', $combined );
877 $success = Hooks
::run( 'LinkerMakeExternalLink',
878 [ &$url, &$text, &$link, &$attribs, $linktype ] );
880 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
881 . "with url {$url} and text {$text} to {$link}\n", true );
884 $attribs['href'] = $url;
885 return Html
::rawElement( 'a', $attribs, $text );
889 * Make user link (or user contributions for unregistered users)
890 * @param int $userId User id in database.
891 * @param string $userName User name in database.
892 * @param string $altUserName Text to display instead of the user name (optional)
893 * @return string HTML fragment
894 * @since 1.16.3. $altUserName was added in 1.19.
896 public static function userLink( $userId, $userName, $altUserName = false ) {
897 $classes = 'mw-userlink';
899 if ( $userId == 0 ) {
900 $page = ExternalUserNames
::getUserLinkTitle( $userName );
902 if ( ExternalUserNames
::isExternal( $userName ) ) {
903 $classes .= ' mw-extuserlink';
904 } elseif ( $altUserName === false ) {
905 $altUserName = IP
::prettifyIP( $userName );
907 $classes .= ' mw-anonuserlink'; // Separate link class for anons (T45179)
909 $page = new TitleValue( NS_USER
, strtr( $userName, ' ', '_' ) );
912 // Wrap the output with <bdi> tags for directionality isolation
914 '<bdi>' . htmlspecialchars( $altUserName !== false ?
$altUserName : $userName ) . '</bdi>';
917 ? self
::link( $page, $linkText, [ 'class' => $classes ] )
918 : Html
::rawElement( 'span', [ 'class' => $classes ], $linkText );
922 * Generate standard user tool links (talk, contributions, block link, etc.)
925 * @param int $userId User identifier
926 * @param string $userText User name or IP address
927 * @param bool $redContribsWhenNoEdits Should the contributions link be
928 * red if the user has no edits?
929 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
930 * and Linker::TOOL_LINKS_EMAIL).
931 * @param int|null $edits User edit count (optional, for performance)
932 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
933 * @return string HTML fragment
935 public static function userToolLinks(
936 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null,
937 $useParentheses = true
939 global $wgUser, $wgDisableAnonTalk, $wgLang;
940 $talkable = !( $wgDisableAnonTalk && $userId == 0 );
941 $blockable = !( $flags & self
::TOOL_LINKS_NOBLOCK
);
942 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
&& $userId;
944 if ( $userId == 0 && ExternalUserNames
::isExternal( $userText ) ) {
945 // No tools for an external user
951 $items[] = self
::userTalkLink( $userId, $userText );
954 // check if the user has an edit
956 $attribs['class'] = 'mw-usertoollinks-contribs';
957 if ( $redContribsWhenNoEdits ) {
958 if ( intval( $edits ) === 0 && $edits !== 0 ) {
959 $user = User
::newFromId( $userId );
960 $edits = $user->getEditCount();
962 if ( $edits === 0 ) {
963 $attribs['class'] .= ' new';
966 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
968 $items[] = self
::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
970 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
971 $items[] = self
::blockLink( $userId, $userText );
974 if ( $addEmailLink && $wgUser->canSendEmail() ) {
975 $items[] = self
::emailLink( $userId, $userText );
978 Hooks
::run( 'UserToolLinksEdit', [ $userId, $userText, &$items ] );
984 if ( $useParentheses ) {
985 return wfMessage( 'word-separator' )->escaped()
986 . '<span class="mw-usertoollinks">'
987 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
992 foreach ( $items as $tool ) {
993 $tools[] = Html
::rawElement( 'span', [], $tool );
995 return ' <span class="mw-usertoollinks mw-changeslist-links">' .
996 implode( ' ', $tools ) . '</span>';
1000 * Alias for userToolLinks( $userId, $userText, true );
1002 * @param int $userId User identifier
1003 * @param string $userText User name or IP address
1004 * @param int|null $edits User edit count (optional, for performance)
1007 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1008 return self
::userToolLinks( $userId, $userText, true, 0, $edits, false );
1013 * @param int $userId User id in database.
1014 * @param string $userText User name in database.
1015 * @return string HTML fragment with user talk link
1017 public static function userTalkLink( $userId, $userText ) {
1018 $userTalkPage = new TitleValue( NS_USER_TALK
, strtr( $userText, ' ', '_' ) );
1019 $moreLinkAttribs['class'] = 'mw-usertoollinks-talk';
1021 return self
::link( $userTalkPage,
1022 wfMessage( 'talkpagelinktext' )->escaped(),
1029 * @param int $userId
1030 * @param string $userText User name in database.
1031 * @return string HTML fragment with block link
1033 public static function blockLink( $userId, $userText ) {
1034 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1035 $moreLinkAttribs['class'] = 'mw-usertoollinks-block';
1037 return self
::link( $blockPage,
1038 wfMessage( 'blocklink' )->escaped(),
1044 * @param int $userId
1045 * @param string $userText User name in database.
1046 * @return string HTML fragment with e-mail user link
1048 public static function emailLink( $userId, $userText ) {
1049 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1050 $moreLinkAttribs['class'] = 'mw-usertoollinks-mail';
1051 return self
::link( $emailPage,
1052 wfMessage( 'emaillink' )->escaped(),
1058 * Generate a user link if the current user is allowed to view it
1060 * @param Revision $rev
1061 * @param bool $isPublic Show only if all users can see it
1062 * @return string HTML fragment
1064 public static function revUserLink( $rev, $isPublic = false ) {
1065 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1066 $link = wfMessage( 'rev-deleted-user' )->escaped();
1067 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1068 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1069 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1071 $link = wfMessage( 'rev-deleted-user' )->escaped();
1073 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1074 return '<span class="history-deleted">' . $link . '</span>';
1080 * Generate a user tool link cluster if the current user is allowed to view it
1082 * @param Revision $rev
1083 * @param bool $isPublic Show only if all users can see it
1084 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
1085 * @return string HTML
1087 public static function revUserTools( $rev, $isPublic = false, $useParentheses = true ) {
1088 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1089 $link = wfMessage( 'rev-deleted-user' )->escaped();
1090 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1091 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1092 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1093 $link = self
::userLink( $userId, $userText )
1094 . self
::userToolLinks( $userId, $userText, false, 0, null,
1097 $link = wfMessage( 'rev-deleted-user' )->escaped();
1099 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1100 return ' <span class="history-deleted mw-userlink">' . $link . '</span>';
1106 * This function is called by all recent changes variants, by the page history,
1107 * and by the user contributions list. It is responsible for formatting edit
1108 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1109 * auto-generated comments (from section editing) and formats [[wikilinks]].
1111 * @author Erik Moeller <moeller@scireview.de>
1112 * @since 1.16.3. $wikiId added in 1.26
1114 * @param string $comment
1115 * @param LinkTarget|null $title LinkTarget object (to generate link to the section in
1116 * autocomment) or null
1117 * @param bool $local Whether section links should refer to local page
1118 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1119 * For use with external changes.
1121 * @return string HTML
1123 public static function formatComment(
1124 $comment, $title = null, $local = false, $wikiId = null
1126 # Sanitize text a bit:
1127 $comment = str_replace( "\n", " ", $comment );
1128 # Allow HTML entities (for T15815)
1129 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1131 # Render autocomments and make links:
1132 $comment = self
::formatAutocomments( $comment, $title, $local, $wikiId );
1133 return self
::formatLinksInComment( $comment, $title, $local, $wikiId );
1137 * Converts autogenerated comments in edit summaries into section links.
1139 * The pattern for autogen comments is / * foo * /, which makes for
1141 * We look for all comments, match any text before and after the comment,
1142 * add a separator where needed and format the comment itself with CSS
1143 * Called by Linker::formatComment.
1145 * @param string $comment Comment text
1146 * @param LinkTarget|null $title An optional LinkTarget object used to links to sections
1147 * @param bool $local Whether section links should refer to local page
1148 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1149 * as used by WikiMap.
1151 * @return string Formatted comment (wikitext)
1153 private static function formatAutocomments(
1154 $comment, $title = null, $local = false, $wikiId = null
1156 // @todo $append here is something of a hack to preserve the status
1157 // quo. Someone who knows more about bidi and such should decide
1158 // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1159 // wiki, both when autocomments exist and when they don't, and
1160 // (2) what markup will make that actually happen.
1162 $comment = preg_replace_callback(
1163 // To detect the presence of content before or after the
1164 // auto-comment, we use capturing groups inside optional zero-width
1165 // assertions. But older versions of PCRE can't directly make
1166 // zero-width assertions optional, so wrap them in a non-capturing
1168 '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1169 function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1172 // Ensure all match positions are defined
1173 $match +
= [ '', '', '', '' ];
1175 $pre = $match[1] !== '';
1177 $post = $match[3] !== '';
1181 'FormatAutocomments',
1182 [ &$comment, $pre, $auto, $post, Title
::castFromLinkTarget( $title ), $local,
1186 if ( $comment === null ) {
1189 # Remove links that a user may have manually put in the autosummary
1190 # This could be improved by copying as much of Parser::stripSectionName as desired.
1191 $section = str_replace( [
1197 // We don't want any links in the auto text to be linked, but we still
1198 // want to show any [[ ]]
1199 $sectionText = str_replace( '[[', '[[', $auto );
1201 $section = substr( Parser
::guessSectionNameFromStrippedText( $section ), 1 );
1203 $sectionTitle = new TitleValue( NS_MAIN
, '', $section );
1205 $sectionTitle = $title->createFragmentTarget( $section );
1207 if ( $sectionTitle ) {
1208 $auto = Linker
::makeCommentLink(
1209 $sectionTitle, $wgLang->getArrow() . $wgLang->getDirMark() . $sectionText,
1210 $wikiId, 'noclasses'
1215 # written summary $presep autocomment (summary /* section */)
1216 $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1219 # autocomment $postsep written summary (/* section */ summary)
1220 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1223 $auto = '<span dir="auto"><span class="autocomment">' . $auto . '</span>';
1224 $append .= '</span>';
1226 $comment = $pre . $auto;
1232 return $comment . $append;
1236 * Formats wiki links and media links in text; all other wiki formatting
1239 * @since 1.16.3. $wikiId added in 1.26
1240 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1242 * @param string $comment Text to format links in. WARNING! Since the output of this
1243 * function is html, $comment must be sanitized for use as html. You probably want
1244 * to pass $comment through Sanitizer::escapeHtmlAllowEntities() before calling
1246 * @param LinkTarget|null $title An optional LinkTarget object used to links to sections
1247 * @param bool $local Whether section links should refer to local page
1248 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1249 * as used by WikiMap.
1251 * @return string HTML
1252 * @return-taint onlysafefor_html
1254 public static function formatLinksInComment(
1255 $comment, $title = null, $local = false, $wikiId = null
1257 return preg_replace_callback(
1260 \s*+ # ignore leading whitespace, the *+ quantifier disallows backtracking
1261 :? # ignore optional leading colon
1262 ([^\]|]+) # 1. link target; page names cannot include ] or |
1265 # Stop matching at ]] without relying on backtracking.
1269 ([^[]*) # 3. link trail (the text up until the next link)
1271 function ( $match ) use ( $title, $local, $wikiId ) {
1272 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1273 $medians .= preg_quote(
1274 MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( NS_MEDIA
),
1278 $comment = $match[0];
1280 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1281 if ( strpos( $match[1], '%' ) !== false ) {
1283 rawurldecode( $match[1] ),
1284 [ '<' => '<', '>' => '>' ]
1288 # Handle link renaming [[foo|text]] will show link as "text"
1289 if ( $match[2] != "" ) {
1296 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1297 # Media link; trail not supported.
1298 $linkRegexp = '/\[\[(.*?)\]\]/';
1299 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1301 $thelink = Linker
::makeMediaLinkObj( $title, $text );
1304 # Other kind of link
1305 # Make sure its target is non-empty
1306 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1307 $match[1] = substr( $match[1], 1 );
1309 if ( $match[1] !== false && $match[1] !== '' ) {
1311 MediaWikiServices
::getInstance()->getContentLanguage()->linkTrail(),
1315 $trail = $submatch[1];
1319 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1320 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1323 $linkTarget = Linker
::normalizeSubpageLink( $title, $match[1], $linkText );
1325 Title
::newFromText( $linkTarget );
1327 $target = MediaWikiServices
::getInstance()->getTitleParser()->
1328 parseTitle( $linkTarget );
1330 if ( $target->getText() == '' && !$target->isExternal()
1331 && !$local && $title
1333 $target = $title->createFragmentTarget( $target->getFragment() );
1336 $thelink = Linker
::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1337 } catch ( MalformedTitleException
$e ) {
1343 // If the link is still valid, go ahead and replace it in!
1344 $comment = preg_replace(
1346 StringUtils
::escapeRegexReplacement( $thelink ),
1359 * Generates a link to the given LinkTarget
1361 * @note This is only public for technical reasons. It's not intended for use outside Linker.
1363 * @param LinkTarget $linkTarget
1364 * @param string $text
1365 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1366 * as used by WikiMap.
1367 * @param string|string[] $options See the $options parameter in Linker::link.
1369 * @return string HTML link
1371 public static function makeCommentLink(
1372 LinkTarget
$linkTarget, $text, $wikiId = null, $options = []
1374 if ( $wikiId !== null && !$linkTarget->isExternal() ) {
1375 $link = self
::makeExternalLink(
1376 WikiMap
::getForeignURL(
1378 $linkTarget->getNamespace() === 0
1379 ?
$linkTarget->getDBkey()
1380 : MWNamespace
::getCanonicalName( $linkTarget->getNamespace() ) . ':'
1381 . $linkTarget->getDBkey(),
1382 $linkTarget->getFragment()
1385 /* escape = */ false // Already escaped
1388 $link = self
::link( $linkTarget, $text, [], [], $options );
1395 * @param LinkTarget $contextTitle
1396 * @param string $target
1397 * @param string &$text
1400 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1403 # :Foobar -- override special treatment of prefix (images, language links)
1404 # /Foobar -- convert to CurrentPage/Foobar
1405 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1406 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1407 # ../Foobar -- convert to CurrentPage/Foobar,
1408 # (from CurrentPage/CurrentSubPage)
1409 # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1410 # (from CurrentPage/CurrentSubPage)
1412 $ret = $target; # default return value is no change
1414 # Some namespaces don't allow subpages,
1415 # so only perform processing if subpages are allowed
1416 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1417 $hash = strpos( $target, '#' );
1418 if ( $hash !== false ) {
1419 $suffix = substr( $target, $hash );
1420 $target = substr( $target, 0, $hash );
1425 $target = trim( $target );
1426 $contextPrefixedText = MediaWikiServices
::getInstance()->getTitleFormatter()->
1427 getPrefixedText( $contextTitle );
1428 # Look at the first character
1429 if ( $target != '' && $target[0] === '/' ) {
1430 # / at end means we don't want the slash to be shown
1432 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1433 if ( $trailingSlashes ) {
1434 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1436 $noslash = substr( $target, 1 );
1439 $ret = $contextPrefixedText . '/' . trim( $noslash ) . $suffix;
1440 if ( $text === '' ) {
1441 $text = $target . $suffix;
1442 } # this might be changed for ugliness reasons
1444 # check for .. subpage backlinks
1446 $nodotdot = $target;
1447 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1449 $nodotdot = substr( $nodotdot, 3 );
1451 if ( $dotdotcount > 0 ) {
1452 $exploded = explode( '/', $contextPrefixedText );
1453 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1454 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1455 # / at the end means don't show full path
1456 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1457 $nodotdot = rtrim( $nodotdot, '/' );
1458 if ( $text === '' ) {
1459 $text = $nodotdot . $suffix;
1462 $nodotdot = trim( $nodotdot );
1463 if ( $nodotdot != '' ) {
1464 $ret .= '/' . $nodotdot;
1476 * Wrap a comment in standard punctuation and formatting if
1477 * it's non-empty, otherwise return empty string.
1479 * @since 1.16.3. $wikiId added in 1.26
1480 * @param string $comment
1481 * @param LinkTarget|null $title LinkTarget object (to generate link to section in autocomment)
1483 * @param bool $local Whether section links should refer to local page
1484 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1485 * For use with external changes.
1489 public static function commentBlock(
1490 $comment, $title = null, $local = false, $wikiId = null, $useParentheses = true
1492 // '*' used to be the comment inserted by the software way back
1493 // in antiquity in case none was provided, here for backwards
1494 // compatibility, acc. to brion -ævar
1495 if ( $comment == '' ||
$comment == '*' ) {
1498 $formatted = self
::formatComment( $comment, $title, $local, $wikiId );
1499 if ( $useParentheses ) {
1500 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1501 $classNames = 'comment';
1503 $classNames = 'comment comment--without-parentheses';
1505 return " <span class=\"$classNames\">$formatted</span>";
1509 * Wrap and format the given revision's comment block, if the current
1510 * user is allowed to view it.
1513 * @param Revision $rev
1514 * @param bool $local Whether section links should refer to local page
1515 * @param bool $isPublic Show only if all users can see it
1516 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
1517 * @return string HTML fragment
1519 public static function revComment( Revision
$rev, $local = false, $isPublic = false,
1520 $useParentheses = true
1522 if ( $rev->getComment( Revision
::RAW
) == "" ) {
1525 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1526 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1527 } elseif ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1528 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1529 $rev->getTitle(), $local, null, $useParentheses );
1531 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1533 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1534 return " <span class=\"history-deleted comment\">$block</span>";
1544 public static function formatRevisionSize( $size ) {
1546 $stxt = wfMessage( 'historyempty' )->escaped();
1548 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1550 return "<span class=\"history-size mw-diff-bytes\">$stxt</span>";
1554 * Add another level to the Table of Contents
1559 public static function tocIndent() {
1564 * Finish one or more sublevels on the Table of Contents
1570 public static function tocUnindent( $level ) {
1571 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1575 * parameter level defines if we are on an indentation level
1578 * @param string $anchor
1579 * @param string $tocline
1580 * @param string $tocnumber
1581 * @param string $level
1582 * @param string|bool $sectionIndex
1585 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1586 $classes = "toclevel-$level";
1587 if ( $sectionIndex !== false ) {
1588 $classes .= " tocsection-$sectionIndex";
1591 // <li class="$classes"><a href="#$anchor"><span class="tocnumber">
1592 // $tocnumber</span> <span class="toctext">$tocline</span></a>
1593 return Html
::openElement( 'li', [ 'class' => $classes ] )
1594 . Html
::rawElement( 'a',
1595 [ 'href' => "#$anchor" ],
1596 Html
::element( 'span', [ 'class' => 'tocnumber' ], $tocnumber )
1598 . Html
::rawElement( 'span', [ 'class' => 'toctext' ], $tocline )
1603 * End a Table Of Contents line.
1604 * tocUnindent() will be used instead if we're ending a line below
1609 public static function tocLineEnd() {
1614 * Wraps the TOC in a table and provides the hide/collapse javascript.
1617 * @param string $toc Html of the Table Of Contents
1618 * @param string|Language|bool|null $lang Language for the toc title, defaults to user language.
1619 * The types string and bool are deprecated.
1620 * @return string Full html of the TOC
1622 public static function tocList( $toc, $lang = null ) {
1623 $lang = $lang ?? RequestContext
::getMain()->getLanguage();
1624 if ( !$lang instanceof Language
) {
1625 wfDeprecated( __METHOD__
. ' with type other than Language for $lang', '1.33' );
1626 $lang = wfGetLangObj( $lang );
1629 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1631 return '<div id="toc" class="toc">'
1632 . Html
::element( 'input', [
1633 'type' => 'checkbox',
1635 'id' => 'toctogglecheckbox',
1636 'class' => 'toctogglecheckbox',
1637 'style' => 'display:none',
1639 . Html
::openElement( 'div', [
1640 'class' => 'toctitle',
1641 'lang' => $lang->getHtmlCode(),
1642 'dir' => $lang->getDir(),
1645 . '<span class="toctogglespan">'
1646 . Html
::label( '', 'toctogglecheckbox', [
1647 'class' => 'toctogglelabel',
1652 . "</ul>\n</div>\n";
1656 * Generate a table of contents from a section tree.
1658 * @since 1.16.3. $lang added in 1.17
1659 * @param array $tree Return value of ParserOutput::getSections()
1660 * @param string|Language|bool|null $lang Language for the toc title, defaults to user language.
1661 * The types string and bool are deprecated.
1662 * @return string HTML fragment
1664 public static function generateTOC( $tree, $lang = null ) {
1667 foreach ( $tree as $section ) {
1668 if ( $section['toclevel'] > $lastLevel ) {
1669 $toc .= self
::tocIndent();
1670 } elseif ( $section['toclevel'] < $lastLevel ) {
1671 $toc .= self
::tocUnindent(
1672 $lastLevel - $section['toclevel'] );
1674 $toc .= self
::tocLineEnd();
1677 $toc .= self
::tocLine( $section['anchor'],
1678 $section['line'], $section['number'],
1679 $section['toclevel'], $section['index'] );
1680 $lastLevel = $section['toclevel'];
1682 $toc .= self
::tocLineEnd();
1683 return self
::tocList( $toc, $lang );
1687 * Create a headline for content
1690 * @param int $level The level of the headline (1-6)
1691 * @param string $attribs Any attributes for the headline, starting with
1692 * a space and ending with '>'
1693 * This *must* be at least '>' for no attribs
1694 * @param string $anchor The anchor to give the headline (the bit after the #)
1695 * @param string $html HTML for the text of the header
1696 * @param string $link HTML to add for the section edit link
1697 * @param string|bool $fallbackAnchor A second, optional anchor to give for
1698 * backward compatibility (false to omit)
1700 * @return string HTML headline
1702 public static function makeHeadline( $level, $attribs, $anchor, $html,
1703 $link, $fallbackAnchor = false
1705 $anchorEscaped = htmlspecialchars( $anchor );
1707 if ( $fallbackAnchor !== false && $fallbackAnchor !== $anchor ) {
1708 $fallbackAnchor = htmlspecialchars( $fallbackAnchor );
1709 $fallback = "<span id=\"$fallbackAnchor\"></span>";
1711 return "<h$level$attribs"
1712 . "$fallback<span class=\"mw-headline\" id=\"$anchorEscaped\">$html</span>"
1718 * Split a link trail, return the "inside" portion and the remainder of the trail
1719 * as a two-element array
1720 * @param string $trail
1723 static function splitTrail( $trail ) {
1724 $regex = MediaWikiServices
::getInstance()->getContentLanguage()->linkTrail();
1726 if ( $trail !== '' && preg_match( $regex, $trail, $m ) ) {
1727 list( , $inside, $trail ) = $m;
1729 return [ $inside, $trail ];
1733 * Generate a rollback link for a given revision. Currently it's the
1734 * caller's responsibility to ensure that the revision is the top one. If
1735 * it's not, of course, the user will get an error message.
1737 * If the calling page is called with the parameter &bot=1, all rollback
1738 * links also get that parameter. It causes the edit itself and the rollback
1739 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1740 * changes, so this allows sysops to combat a busy vandal without bothering
1743 * If the option verify is set this function will return the link only in case the
1744 * revision can be reverted. Please note that due to performance limitations
1745 * it might be assumed that a user isn't the only contributor of a page while
1746 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1747 * work if $wgShowRollbackEditCount is disabled, so this can only function
1748 * as an additional check.
1750 * If the option noBrackets is set the rollback link wont be enclosed in "[]".
1752 * @since 1.16.3. $context added in 1.20. $options added in 1.21
1754 * @param Revision $rev
1755 * @param IContextSource|null $context Context to use or null for the main context.
1756 * @param array $options
1759 public static function generateRollback( $rev, IContextSource
$context = null,
1760 $options = [ 'verify' ]
1762 if ( $context === null ) {
1763 $context = RequestContext
::getMain();
1767 if ( in_array( 'verify', $options, true ) ) {
1768 $editCount = self
::getRollbackEditCount( $rev, true );
1769 if ( $editCount === false ) {
1774 $inner = self
::buildRollbackLink( $rev, $context, $editCount );
1776 if ( !in_array( 'noBrackets', $options, true ) ) {
1777 $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1780 if ( $context->getUser()->getBoolOption( 'showrollbackconfirmation' ) ) {
1781 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1782 $stats->increment( 'rollbackconfirmation.event.load' );
1783 $context->getOutput()->addModules( 'mediawiki.page.rollback.confirmation' );
1786 return '<span class="mw-rollback-link">' . $inner . '</span>';
1790 * This function will return the number of revisions which a rollback
1791 * would revert and, if $verify is set it will verify that a revision
1792 * can be reverted (that the user isn't the only contributor and the
1793 * revision we might rollback to isn't deleted). These checks can only
1794 * function as an additional check as this function only checks against
1795 * the last $wgShowRollbackEditCount edits.
1797 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1798 * is set and the user is the only contributor of the page.
1800 * @param Revision $rev
1801 * @param bool $verify Try to verify that this revision can really be rolled back
1802 * @return int|bool|null
1804 public static function getRollbackEditCount( $rev, $verify ) {
1805 global $wgShowRollbackEditCount;
1806 if ( !is_int( $wgShowRollbackEditCount ) ||
!$wgShowRollbackEditCount > 0 ) {
1807 // Nothing has happened, indicate this by returning 'null'
1811 $dbr = wfGetDB( DB_REPLICA
);
1813 // Up to the value of $wgShowRollbackEditCount revisions are counted
1814 $revQuery = Revision
::getQueryInfo();
1815 $res = $dbr->select(
1816 $revQuery['tables'],
1817 [ 'rev_user_text' => $revQuery['fields']['rev_user_text'], 'rev_deleted' ],
1818 // $rev->getPage() returns null sometimes
1819 [ 'rev_page' => $rev->getTitle()->getArticleID() ],
1822 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
1823 'ORDER BY' => 'rev_timestamp DESC',
1824 'LIMIT' => $wgShowRollbackEditCount +
1
1831 foreach ( $res as $row ) {
1832 if ( $rev->getUserText( Revision
::RAW
) != $row->rev_user_text
) {
1834 ( $row->rev_deleted
& Revision
::DELETED_TEXT
1835 ||
$row->rev_deleted
& Revision
::DELETED_USER
1837 // If the user or the text of the revision we might rollback
1838 // to is deleted in some way we can't rollback. Similar to
1839 // the sanity checks in WikiPage::commitRollback.
1848 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1849 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1850 // and there weren't any other revisions. That means that the current user is the only
1851 // editor, so we can't rollback
1858 * Build a raw rollback link, useful for collections of "tool" links
1860 * @since 1.16.3. $context added in 1.20. $editCount added in 1.21
1861 * @param Revision $rev
1862 * @param IContextSource|null $context Context to use or null for the main context.
1863 * @param int $editCount Number of edits that would be reverted
1864 * @return string HTML fragment
1866 public static function buildRollbackLink( $rev, IContextSource
$context = null,
1869 global $wgShowRollbackEditCount, $wgMiserMode;
1871 // To config which pages are affected by miser mode
1872 $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
1874 if ( $context === null ) {
1875 $context = RequestContext
::getMain();
1878 $title = $rev->getTitle();
1881 'action' => 'rollback',
1882 'from' => $rev->getUserText(),
1883 'token' => $context->getUser()->getEditToken( 'rollback' ),
1887 'data-mw' => 'interface',
1888 'title' => $context->msg( 'tooltip-rollback' )->text()
1891 $options = [ 'known', 'noclasses' ];
1893 if ( $context->getRequest()->getBool( 'bot' ) ) {
1895 $query['hidediff'] = '1';
1896 $query['bot'] = '1';
1899 $disableRollbackEditCount = false;
1900 if ( $wgMiserMode ) {
1901 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1902 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1903 $disableRollbackEditCount = true;
1909 if ( !$disableRollbackEditCount
1910 && is_int( $wgShowRollbackEditCount )
1911 && $wgShowRollbackEditCount > 0
1913 if ( !is_numeric( $editCount ) ) {
1914 $editCount = self
::getRollbackEditCount( $rev, false );
1917 if ( $editCount > $wgShowRollbackEditCount ) {
1918 $html = $context->msg( 'rollbacklinkcount-morethan' )
1919 ->numParams( $wgShowRollbackEditCount )->parse();
1921 $html = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1924 return self
::link( $title, $html, $attrs, $query, $options );
1927 $html = $context->msg( 'rollbacklink' )->escaped();
1928 return self
::link( $title, $html, $attrs, $query, $options );
1932 * Returns HTML for the "hidden categories on this page" list.
1935 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1937 * @return string HTML output
1939 public static function formatHiddenCategories( $hiddencats ) {
1941 if ( count( $hiddencats ) > 0 ) {
1942 # Construct the HTML
1943 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1944 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
1945 $outText .= "</div><ul>\n";
1947 foreach ( $hiddencats as $titleObj ) {
1948 # If it's hidden, it must exist - no need to check with a LinkBatch
1950 . self
::link( $titleObj, null, [], [], 'known' )
1953 $outText .= '</ul>';
1959 * Given the id of an interface element, constructs the appropriate title
1960 * attribute from the system messages. (Note, this is usually the id but
1961 * isn't always, because sometimes the accesskey needs to go on a different
1962 * element than the id, for reverse-compatibility, etc.)
1964 * @since 1.16.3 $msgParams added in 1.27
1965 * @param string $name Id of the element, minus prefixes.
1966 * @param string|array|null $options Null, string or array with some of the following options:
1967 * - 'withaccess' to add an access-key hint
1968 * - 'nonexisting' to add an accessibility hint that page does not exist
1969 * @param array $msgParams Parameters to pass to the message
1971 * @return string Contents of the title attribute (which you must HTML-
1972 * escape), or false for no title attribute
1974 public static function titleAttrib( $name, $options = null, array $msgParams = [] ) {
1975 $message = wfMessage( "tooltip-$name", $msgParams );
1976 if ( !$message->exists() ) {
1979 $tooltip = $message->text();
1980 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1981 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1982 # Message equal to '-' means suppress it.
1983 if ( $tooltip == '-' ) {
1988 $options = (array)$options;
1990 if ( in_array( 'nonexisting', $options ) ) {
1991 $tooltip = wfMessage( 'red-link-title', $tooltip ?
: '' )->text();
1993 if ( in_array( 'withaccess', $options ) ) {
1994 $accesskey = self
::accesskey( $name );
1995 if ( $accesskey !== false ) {
1996 // Should be build the same as in jquery.accessKeyLabel.js
1997 if ( $tooltip === false ||
$tooltip === '' ) {
1998 $tooltip = wfMessage( 'brackets', $accesskey )->text();
2000 $tooltip .= wfMessage( 'word-separator' )->text();
2001 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
2009 public static $accesskeycache;
2012 * Given the id of an interface element, constructs the appropriate
2013 * accesskey attribute from the system messages. (Note, this is usually
2014 * the id but isn't always, because sometimes the accesskey needs to go on
2015 * a different element than the id, for reverse-compatibility, etc.)
2018 * @param string $name Id of the element, minus prefixes.
2019 * @return string Contents of the accesskey attribute (which you must HTML-
2020 * escape), or false for no accesskey attribute
2022 public static function accesskey( $name ) {
2023 if ( isset( self
::$accesskeycache[$name] ) ) {
2024 return self
::$accesskeycache[$name];
2027 $message = wfMessage( "accesskey-$name" );
2029 if ( !$message->exists() ) {
2032 $accesskey = $message->plain();
2033 if ( $accesskey === '' ||
$accesskey === '-' ) {
2034 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2035 # attribute, but this is broken for accesskey: that might be a useful
2041 self
::$accesskeycache[$name] = $accesskey;
2042 return self
::$accesskeycache[$name];
2046 * Get a revision-deletion link, or disabled link, or nothing, depending
2047 * on user permissions & the settings on the revision.
2049 * Will use forward-compatible revision ID in the Special:RevDelete link
2050 * if possible, otherwise the timestamp-based ID which may break after
2054 * @param Revision $rev
2055 * @param LinkTarget $title
2056 * @return string HTML fragment
2058 public static function getRevDeleteLink( User
$user, Revision
$rev, LinkTarget
$title ) {
2059 $canHide = $user->isAllowed( 'deleterevision' );
2060 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2064 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
2065 return self
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2067 $prefixedDbKey = MediaWikiServices
::getInstance()->getTitleFormatter()->
2068 getPrefixedDBkey( $title );
2069 if ( $rev->getId() ) {
2070 // RevDelete links using revision ID are stable across
2071 // page deletion and undeletion; use when possible.
2073 'type' => 'revision',
2074 'target' => $prefixedDbKey,
2075 'ids' => $rev->getId()
2078 // Older deleted entries didn't save a revision ID.
2079 // We have to refer to these by timestamp, ick!
2081 'type' => 'archive',
2082 'target' => $prefixedDbKey,
2083 'ids' => $rev->getTimestamp()
2086 return self
::revDeleteLink( $query,
2087 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
2091 * Creates a (show/hide) link for deleting revisions/log entries
2093 * @param array $query Query parameters to be passed to link()
2094 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2095 * @param bool $delete Set to true to use (show/hide) rather than (show)
2097 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2098 * span to allow for customization of appearance with CSS
2100 public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2101 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
2102 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2103 $html = wfMessage( $msgKey )->escaped();
2104 $tag = $restricted ?
'strong' : 'span';
2105 $link = self
::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2108 [ 'class' => 'mw-revdelundel-link' ],
2109 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2114 * Creates a dead (show/hide) link for deleting revisions/log entries
2117 * @param bool $delete Set to true to use (show/hide) rather than (show)
2119 * @return string HTML text wrapped in a span to allow for customization
2120 * of appearance with CSS
2122 public static function revDeleteLinkDisabled( $delete = true ) {
2123 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2124 $html = wfMessage( $msgKey )->escaped();
2125 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2126 return Xml
::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2130 * Returns the attributes for the tooltip and access key.
2132 * @since 1.16.3. $msgParams introduced in 1.27
2133 * @param string $name
2134 * @param array $msgParams Params for constructing the message
2135 * @param string|array|null $options Options to be passed to titleAttrib.
2137 * @see Linker::titleAttrib for what options could be passed to $options.
2141 public static function tooltipAndAccesskeyAttribs(
2143 array $msgParams = [],
2146 $options = (array)$options;
2147 $options[] = 'withaccess';
2150 'title' => self
::titleAttrib( $name, $options, $msgParams ),
2151 'accesskey' => self
::accesskey( $name )
2153 if ( $attribs['title'] === false ) {
2154 unset( $attribs['title'] );
2156 if ( $attribs['accesskey'] === false ) {
2157 unset( $attribs['accesskey'] );
2163 * Returns raw bits of HTML, use titleAttrib()
2165 * @param string $name
2166 * @param array|null $options
2167 * @return null|string
2169 public static function tooltip( $name, $options = null ) {
2170 $tooltip = self
::titleAttrib( $name, $options );
2171 if ( $tooltip === false ) {
2174 return Xml
::expandAttributes( [