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
23 namespace MediaWiki\Linker
;
27 use MediaTransformError
;
28 use MediaTransformOutput
;
29 use MediaWiki\Context\ContextSource
;
30 use MediaWiki\Context\DerivativeContext
;
31 use MediaWiki\Context\IContextSource
;
32 use MediaWiki\Context\RequestContext
;
33 use MediaWiki\HookContainer\HookRunner
;
34 use MediaWiki\Html\Html
;
35 use MediaWiki\Html\HtmlHelper
;
36 use MediaWiki\MainConfigNames
;
37 use MediaWiki\MediaWikiServices
;
38 use MediaWiki\Message\Message
;
39 use MediaWiki\Parser\Parser
;
40 use MediaWiki\Permissions\Authority
;
41 use MediaWiki\Revision\RevisionRecord
;
42 use MediaWiki\SpecialPage\SpecialPage
;
43 use MediaWiki\Title\Title
;
44 use MediaWiki\Title\TitleValue
;
45 use MediaWiki\User\ExternalUserNames
;
46 use MediaWiki\User\UserIdentityValue
;
47 use MediaWiki\Xml\Xml
;
49 use Wikimedia\Assert\Assert
;
50 use Wikimedia\IPUtils
;
51 use Wikimedia\Rdbms\SelectQueryBuilder
;
52 use Wikimedia\RemexHtml\Serializer\SerializerNode
;
55 * Some internal bits split of from Skin.php. These functions are used
56 * for primarily page content: links, embedded images, table of contents. Links
57 * are also used in the skin.
59 * @todo turn this into a legacy interface for HtmlPageLinkRenderer and similar services.
65 * Flags for userToolLinks()
67 public const TOOL_LINKS_NOBLOCK
= 1;
68 public const TOOL_LINKS_EMAIL
= 2;
71 * This function returns an HTML link to the given target. It serves a few
73 * 1) If $target is a LinkTarget, the correct URL to link to will be figured
75 * 2) It automatically adds the usual classes for various types of link
76 * targets: "new" for red links, "stub" for short articles, etc.
77 * 3) It escapes all attribute values safely so there's no risk of XSS.
78 * 4) It provides a default tooltip if the target is a LinkTarget (the page
79 * name of the target).
80 * link() replaces the old functions in the makeLink() family.
82 * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
83 * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
85 * @param LinkTarget $target Can currently only be a LinkTarget, but this may
86 * change to support Images, literal URLs, etc.
87 * @param string|null $html The HTML contents of the <a> element, i.e.,
88 * the link text. This is raw HTML and will not be escaped. If null,
89 * defaults to the prefixed text of the LinkTarget; or if the LinkTarget is just a
90 * fragment, the contents of the fragment.
91 * @param array $customAttribs A key => value array of extra HTML attributes,
92 * such as title and class. (href is ignored.) Classes will be
93 * merged with the default classes, while other attributes will replace
94 * default attributes. All passed attribute values will be HTML-escaped.
95 * A false attribute value means to suppress that attribute.
96 * @param array $query The query string to append to the URL
97 * you're linking to, in key => value array form. Query keys and values
98 * will be URL-encoded.
99 * @param string|array $options String or array of strings:
100 * 'known': Page is known to exist, so don't check if it does.
101 * 'broken': Page is known not to exist, so don't check if it does.
102 * 'noclasses': Don't add any classes automatically (includes "new",
103 * "stub", "mw-redirect", "extiw"). Only use the class attribute
104 * provided, if any, so you get a simple blue link with no icons.
105 * 'forcearticlepath': Use the article path always, even with a querystring.
106 * Has compatibility issues on some setups, so avoid wherever possible.
107 * 'http': Force a full URL with http:// as the scheme.
108 * 'https': Force a full URL with https:// as the scheme.
109 * @return string HTML <a> attribute
111 public static function link(
112 $target, $html = null, $customAttribs = [], $query = [], $options = []
114 if ( !$target instanceof LinkTarget
) {
115 wfWarn( __METHOD__
. ': Requires $target to be a LinkTarget object.', 2 );
116 return "<!-- ERROR -->$html";
119 $services = MediaWikiServices
::getInstance();
120 $options = (array)$options;
122 // Custom options, create new LinkRenderer
123 $linkRenderer = $services->getLinkRendererFactory()
124 ->createFromLegacyOptions( $options );
126 $linkRenderer = $services->getLinkRenderer();
129 if ( $html !== null ) {
130 $text = new HtmlArmor( $html );
135 if ( in_array( 'known', $options, true ) ) {
136 return $linkRenderer->makeKnownLink( $target, $text, $customAttribs, $query );
139 if ( in_array( 'broken', $options, true ) ) {
140 return $linkRenderer->makeBrokenLink( $target, $text, $customAttribs, $query );
143 if ( in_array( 'noclasses', $options, true ) ) {
144 return $linkRenderer->makePreloadedLink( $target, $text, '', $customAttribs, $query );
147 return $linkRenderer->makeLink( $target, $text, $customAttribs, $query );
151 * Identical to link(), except $options defaults to 'known'.
154 * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
156 * @param LinkTarget $target
157 * @param-taint $target none
158 * @param string|null $html
159 * @param-taint $html exec_html
160 * @param array $customAttribs
161 * @param-taint $customAttribs none
162 * @param array $query
163 * @param-taint $query none
164 * @param string|array $options
165 * @param-taint $options none
167 * @return-taint escaped
169 public static function linkKnown(
170 $target, $html = null, $customAttribs = [],
171 $query = [], $options = [ 'known' ]
173 return self
::link( $target, $html, $customAttribs, $query, $options );
177 * Make appropriate markup for a link to the current article. This is since
178 * MediaWiki 1.29.0 rendered as an <a> tag without an href and with a class
179 * showing the link text. The calling sequence is the same as for the other
180 * make*LinkObj static functions, but $query is not used.
183 * @param LinkTarget $nt
184 * @param string $html
185 * @param string $query
186 * @param string $trail
187 * @param string $prefix
188 * @param string $hash hash fragment since 1.40. Should be properly escaped using
189 * Sanitizer::escapeIdForLink before being passed to this function.
193 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '', $hash = '' ) {
194 $nt = Title
::newFromLinkTarget( $nt );
197 $attrs['class'] = 'mw-selflink-fragment';
198 $attrs['href'] = '#' . $hash;
200 // For backwards compatibility with gadgets we add selflink as well.
201 $attrs['class'] = 'mw-selflink selflink';
203 $ret = Html
::rawElement( 'a', $attrs, $prefix . $html ) . $trail;
204 $hookRunner = new HookRunner( MediaWikiServices
::getInstance()->getHookContainer() );
205 if ( !$hookRunner->onSelfLinkBegin( $nt, $html, $trail, $prefix, $ret ) ) {
210 $html = htmlspecialchars( $nt->getPrefixedText() );
212 [ $inside, $trail ] = self
::splitTrail( $trail );
213 return Html
::rawElement( 'a', $attrs, $prefix . $html . $inside ) . $trail;
217 * Get a message saying that an invalid title was encountered.
218 * This should be called after a method like Title::makeTitleSafe() returned
219 * a value indicating that the title object is invalid.
221 * @param IContextSource $context Context to use to get the messages
222 * @param int $namespace Namespace number
223 * @param string $title Text of the title, without the namespace part
226 public static function getInvalidTitleDescription( IContextSource
$context, $namespace, $title ) {
227 // First we check whether the namespace exists or not.
228 if ( MediaWikiServices
::getInstance()->getNamespaceInfo()->exists( $namespace ) ) {
229 if ( $namespace == NS_MAIN
) {
230 $name = $context->msg( 'blanknamespace' )->text();
232 $name = MediaWikiServices
::getInstance()->getContentLanguage()->
233 getFormattedNsText( $namespace );
235 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
238 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
242 * Returns the filename part of an url.
243 * Used as alternative text for external images.
249 private static function fnamePart( $url ) {
250 $basename = strrchr( $url, '/' );
251 if ( $basename === false ) {
254 $basename = substr( $basename, 1 );
260 * Return the code for images which were added via external links,
261 * via Parser::maybeMakeExternalImage().
269 public static function makeExternalImage( $url, $alt = '' ) {
271 $alt = self
::fnamePart( $url );
274 $success = ( new HookRunner( MediaWikiServices
::getInstance()->getHookContainer() ) )
275 ->onLinkerMakeExternalImage( $url, $alt, $img );
277 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
278 . "with url {$url} and alt text {$alt} to {$img}" );
281 return Html
::element( 'img',
290 * Given parameters derived from [[Image:Foo|options...]], generate the
291 * HTML that that syntax inserts in the page.
293 * @param Parser $parser
294 * @param LinkTarget $title LinkTarget object of the file (not the currently viewed page)
295 * @param File|false $file File object, or false if it doesn't exist
296 * @param array $frameParams Associative array of parameters external to the media handler.
297 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
298 * will often be false.
299 * thumbnail If present, downscale and frame
300 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
301 * framed Shows image in original size in a frame
302 * frameless Downscale but don't frame
303 * upright If present, tweak default sizes for portrait orientation
304 * upright_factor Fudge factor for "upright" tweak (default 0.75)
305 * border If present, show a border around the image
306 * align Horizontal alignment (left, right, center, none)
307 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
308 * bottom, text-bottom)
309 * alt Alternate text for image (i.e. alt attribute). Plain text.
310 * title Used for tooltips if caption isn't visible.
311 * class HTML for image classes. Plain text.
312 * caption HTML for image caption.
313 * link-url URL to link to
314 * link-title LinkTarget object to link to
315 * link-target Value for the target attribute, only with link-url
316 * no-link Boolean, suppress description link
318 * @param array $handlerParams Associative array of media handler parameters, to be passed
319 * to transform(). Typical keys are "width" and "page".
320 * targetlang (optional) Target language code, see Parser::getTargetLanguage()
321 * @param string|false $time Timestamp of the file, set as false for current
322 * @param string $query Query params for desc url
323 * @param int|null $widthOption Used by the parser to remember the user preference thumbnailsize
325 * @return string HTML for an image, with links, wrappers, etc.
327 public static function makeImageLink( Parser
$parser, LinkTarget
$title,
328 $file, $frameParams = [], $handlerParams = [], $time = false,
329 $query = '', $widthOption = null
331 $title = Title
::newFromLinkTarget( $title );
333 $hookRunner = new HookRunner( MediaWikiServices
::getInstance()->getHookContainer() );
334 if ( !$hookRunner->onImageBeforeProduceHTML( null, $title,
335 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
336 $file, $frameParams, $handlerParams, $time, $res,
337 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
338 $parser, $query, $widthOption )
343 if ( $file && !$file->allowInlineDisplay() ) {
344 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . ' does not allow inline display' );
345 return self
::link( $title );
348 // Clean up parameters
349 $page = $handlerParams['page'] ??
false;
350 if ( !isset( $frameParams['align'] ) ) {
351 $frameParams['align'] = '';
353 if ( !isset( $frameParams['title'] ) ) {
354 $frameParams['title'] = '';
356 if ( !isset( $frameParams['class'] ) ) {
357 $frameParams['class'] = '';
360 $services = MediaWikiServices
::getInstance();
361 $config = $services->getMainConfig();
362 $enableLegacyMediaDOM = $config->get( MainConfigNames
::ParserEnableLegacyMediaDOM
);
366 !isset( $handlerParams['width'] ) &&
367 !isset( $frameParams['manualthumb'] ) &&
368 !isset( $frameParams['framed'] )
370 $classes[] = 'mw-default-size';
373 $prefix = $postfix = '';
375 if ( $enableLegacyMediaDOM ) {
376 if ( $frameParams['align'] == 'center' ) {
377 $prefix = '<div class="center">';
379 $frameParams['align'] = 'none';
383 if ( $file && !isset( $handlerParams['width'] ) ) {
384 if ( isset( $handlerParams['height'] ) && $file->isVectorized() ) {
385 // If its a vector image, and user only specifies height
386 // we don't want it to be limited by its "normal" width.
387 $svgMaxSize = $config->get( MainConfigNames
::SVGMaxSize
);
388 $handlerParams['width'] = $svgMaxSize;
390 $handlerParams['width'] = $file->getWidth( $page );
393 if ( isset( $frameParams['thumbnail'] )
394 ||
isset( $frameParams['manualthumb'] )
395 ||
isset( $frameParams['framed'] )
396 ||
isset( $frameParams['frameless'] )
397 ||
!$handlerParams['width']
399 $thumbLimits = $config->get( MainConfigNames
::ThumbLimits
);
400 $thumbUpright = $config->get( MainConfigNames
::ThumbUpright
);
401 if ( $widthOption === null ||
!isset( $thumbLimits[$widthOption] ) ) {
402 $userOptionsLookup = $services->getUserOptionsLookup();
403 $widthOption = $userOptionsLookup->getDefaultOption( 'thumbsize' );
406 // Reduce width for upright images when parameter 'upright' is used
407 if ( isset( $frameParams['upright'] ) && $frameParams['upright'] == 0 ) {
408 $frameParams['upright'] = $thumbUpright;
411 // For caching health: If width scaled down due to upright
412 // parameter, round to full __0 pixel to avoid the creation of a
413 // lot of odd thumbs.
414 $prefWidth = isset( $frameParams['upright'] ) ?
415 round( $thumbLimits[$widthOption] * $frameParams['upright'], -1 ) :
416 $thumbLimits[$widthOption];
418 // Use width which is smaller: real image width or user preference width
419 // Unless image is scalable vector.
420 if ( !isset( $handlerParams['height'] ) && ( $handlerParams['width'] <= 0 ||
421 $prefWidth < $handlerParams['width'] ||
$file->isVectorized() ) ) {
422 $handlerParams['width'] = $prefWidth;
427 // Parser::makeImage has a similarly named variable
428 $hasVisibleCaption = isset( $frameParams['thumbnail'] ) ||
429 isset( $frameParams['manualthumb'] ) ||
430 isset( $frameParams['framed'] );
432 if ( $hasVisibleCaption ) {
433 if ( $enableLegacyMediaDOM ) {
434 // This is no longer needed in our new media output, since the
435 // default styling in content.media-common.less takes care of it;
438 # Create a thumbnail. Alignment depends on the writing direction of
439 # the page content language (right-aligned for LTR languages,
440 # left-aligned for RTL languages)
441 # If a thumbnail width has not been provided, it is set
442 # to the default user option as specified in Language*.php
443 if ( $frameParams['align'] == '' ) {
444 $frameParams['align'] = $parser->getTargetLanguage()->alignEnd();
447 return $prefix . self
::makeThumbLink2(
448 $title, $file, $frameParams, $handlerParams, $time, $query,
453 $rdfaType = 'mw:File';
455 if ( isset( $frameParams['frameless'] ) ) {
456 $rdfaType .= '/Frameless';
458 $srcWidth = $file->getWidth( $page );
459 # For "frameless" option: do not present an image bigger than the
460 # source (for bitmap-style images). This is the same behavior as the
461 # "thumb" option does it already.
462 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
463 $handlerParams['width'] = $srcWidth;
468 if ( $file && isset( $handlerParams['width'] ) ) {
469 # Create a resized image, without the additional thumbnail features
470 $thumb = $file->transform( $handlerParams );
475 $isBadFile = $file && $thumb &&
476 $parser->getBadFileLookup()->isBadFile( $title->getDBkey(), $parser->getTitle() );
478 if ( !$thumb ||
( !$enableLegacyMediaDOM && $thumb->isError() ) ||
$isBadFile ) {
479 $rdfaType = 'mw:Error ' . $rdfaType;
480 $currentExists = $file && $file->exists();
481 if ( $enableLegacyMediaDOM ) {
482 $label = $frameParams['title'];
484 if ( $currentExists && !$thumb ) {
485 $label = wfMessage( 'thumbnail_error', '' )->text();
486 } elseif ( $thumb && $thumb->isError() ) {
488 $thumb instanceof MediaTransformError
,
489 'Unknown MediaTransformOutput: ' . get_class( $thumb )
491 $label = $thumb->toText();
493 $label = $frameParams['alt'] ??
'';
496 $s = self
::makeBrokenImageLinkObj(
497 $title, $label, '', '', '', (bool)$time, $handlerParams, $currentExists
500 self
::processResponsiveImages( $file, $thumb, $handlerParams );
502 // An empty alt indicates an image is not a key part of the content
503 // and that non-visual browsers may omit it from rendering. Only
504 // set the parameter if it's explicitly requested.
505 if ( isset( $frameParams['alt'] ) ) {
506 $params['alt'] = $frameParams['alt'];
508 $params['title'] = $frameParams['title'];
509 if ( $enableLegacyMediaDOM ) {
511 'valign' => $frameParams['valign'] ??
false,
512 'img-class' => $frameParams['class'],
514 if ( isset( $frameParams['border'] ) ) {
515 $params['img-class'] .= ( $params['img-class'] !== '' ?
' ' : '' ) . 'thumbborder';
519 'img-class' => 'mw-file-element',
522 $params = self
::getImageLinkMTOParams( $frameParams, $query, $parser ) +
$params;
523 $s = $thumb->toHtml( $params );
526 if ( $enableLegacyMediaDOM ) {
527 if ( $frameParams['align'] != '' ) {
528 $s = Html
::rawElement(
530 [ 'class' => 'float' . $frameParams['align'] ],
534 return str_replace( "\n", ' ', $prefix . $s . $postfix );
540 if ( $frameParams['align'] != '' ) {
542 // Possible values: mw-halign-left mw-halign-center mw-halign-right mw-halign-none
543 $classes[] = "mw-halign-{$frameParams['align']}";
544 $caption = Html
::rawElement(
545 'figcaption', [], $frameParams['caption'] ??
''
547 } elseif ( isset( $frameParams['valign'] ) ) {
548 // Possible values: mw-valign-middle mw-valign-baseline mw-valign-sub
549 // mw-valign-super mw-valign-top mw-valign-text-top mw-valign-bottom
550 // mw-valign-text-bottom
551 $classes[] = "mw-valign-{$frameParams['valign']}";
554 if ( isset( $frameParams['border'] ) ) {
555 $classes[] = 'mw-image-border';
558 if ( isset( $frameParams['class'] ) ) {
559 $classes[] = $frameParams['class'];
564 'typeof' => $rdfaType,
567 $s = Html
::rawElement( $wrapper, $attribs, $s . $caption );
569 return str_replace( "\n", ' ', $s );
573 * Get the link parameters for MediaTransformOutput::toHtml() from given
574 * frame parameters supplied by the Parser.
575 * @param array $frameParams The frame parameters
576 * @param string $query An optional query string to add to description page links
577 * @param Parser|null $parser
580 public static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
582 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
583 $mtoParams['custom-url-link'] = $frameParams['link-url'];
584 if ( isset( $frameParams['link-target'] ) ) {
585 $mtoParams['custom-target-link'] = $frameParams['link-target'];
588 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
589 foreach ( $extLinkAttrs as $name => $val ) {
590 // Currently could include 'rel' and 'target'
591 $mtoParams['parser-extlink-' . $name] = $val;
594 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
595 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
596 $mtoParams['custom-title-link'] = Title
::newFromLinkTarget(
597 $linkRenderer->normalizeTarget( $frameParams['link-title'] )
599 if ( isset( $frameParams['link-title-query'] ) ) {
600 $mtoParams['custom-title-link-query'] = $frameParams['link-title-query'];
602 } elseif ( !empty( $frameParams['no-link'] ) ) {
605 $mtoParams['desc-link'] = true;
606 $mtoParams['desc-query'] = $query;
612 * Make HTML for a thumbnail including image, border and caption
613 * @param LinkTarget $title
614 * @param File|false $file File object or false if it doesn't exist
615 * @param string $label
617 * @param string|null $align
618 * @param array $params
619 * @param bool $framed
620 * @param string $manualthumb
623 public static function makeThumbLinkObj(
624 LinkTarget
$title, $file, $label = '', $alt = '', $align = null,
625 $params = [], $framed = false, $manualthumb = ''
633 if ( $manualthumb ) {
634 $frameParams['manualthumb'] = $manualthumb;
635 } elseif ( $framed ) {
636 $frameParams['framed'] = true;
637 } elseif ( !isset( $params['width'] ) ) {
638 $classes[] = 'mw-default-size';
640 return self
::makeThumbLink2(
641 $title, $file, $frameParams, $params, false, '', $classes
646 * @param LinkTarget $title
647 * @param File|false $file
648 * @param array $frameParams
649 * @param array $handlerParams
650 * @param bool $time If a file of a certain timestamp was requested
651 * @param string $query
652 * @param string[] $classes @since 1.36
653 * @param Parser|null $parser @since 1.38
656 public static function makeThumbLink2(
657 LinkTarget
$title, $file, $frameParams = [], $handlerParams = [],
658 $time = false, $query = '', array $classes = [], ?Parser
$parser = null
660 $exists = $file && $file->exists();
662 $services = MediaWikiServices
::getInstance();
663 $enableLegacyMediaDOM = $services->getMainConfig()->get( MainConfigNames
::ParserEnableLegacyMediaDOM
);
665 $page = $handlerParams['page'] ??
false;
666 $lang = $handlerParams['lang'] ??
false;
668 if ( !isset( $frameParams['align'] ) ) {
669 $frameParams['align'] = '';
670 if ( $enableLegacyMediaDOM ) {
671 $frameParams['align'] = 'right';
674 if ( !isset( $frameParams['caption'] ) ) {
675 $frameParams['caption'] = '';
678 if ( empty( $handlerParams['width'] ) ) {
679 // Reduce width for upright images when parameter 'upright' is used
680 $handlerParams['width'] = isset( $frameParams['upright'] ) ?
130 : 180;
685 $manualthumb = false;
687 $rdfaType = 'mw:File/Thumb';
690 // Same precedence as the $exists case
691 if ( !isset( $frameParams['manualthumb'] ) && isset( $frameParams['framed'] ) ) {
692 $rdfaType = 'mw:File/Frame';
694 $outerWidth = $handlerParams['width'] +
2;
696 if ( isset( $frameParams['manualthumb'] ) ) {
697 # Use manually specified thumbnail
698 $manual_title = Title
::makeTitleSafe( NS_FILE
, $frameParams['manualthumb'] );
699 if ( $manual_title ) {
700 $manual_img = $services->getRepoGroup()
701 ->findFile( $manual_title );
703 $thumb = $manual_img->getUnscaledThumb( $handlerParams );
708 $srcWidth = $file->getWidth( $page );
709 if ( isset( $frameParams['framed'] ) ) {
710 $rdfaType = 'mw:File/Frame';
711 if ( !$file->isVectorized() ) {
712 // Use image dimensions, don't scale
715 // framed is unscaled, but for vectorized images
716 // we need to a width for scaling up for the high density variants
717 $handlerParams['width'] = $srcWidth;
721 // Do not present an image bigger than the source, for bitmap-style images
722 // This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
723 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
724 $handlerParams['width'] = $srcWidth;
728 ?
$file->getUnscaledThumb( $handlerParams )
729 : $file->transform( $handlerParams );
733 $outerWidth = $thumb->getWidth() +
2;
735 $outerWidth = $handlerParams['width'] +
2;
739 if ( !$enableLegacyMediaDOM && $parser && $rdfaType === 'mw:File/Thumb' ) {
740 $parser->getOutput()->addModules( [ 'mediawiki.page.media' ] );
743 $url = Title
::newFromLinkTarget( $title )->getLocalURL( $query );
744 $linkTitleQuery = [];
745 if ( $page ||
$lang ) {
747 $linkTitleQuery['page'] = $page;
750 $linkTitleQuery['lang'] = $lang;
752 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
753 # So we don't need to pass it here in $query. However, the URL for the
754 # zoom icon still needs it, so we make a unique query for it. See T16771
755 $url = wfAppendQuery( $url, $linkTitleQuery );
759 && !isset( $frameParams['link-title'] )
760 && !isset( $frameParams['link-url'] )
761 && !isset( $frameParams['no-link'] ) ) {
762 $frameParams['link-title'] = $title;
763 $frameParams['link-title-query'] = $linkTitleQuery;
766 if ( $frameParams['align'] != '' ) {
767 // Possible values: mw-halign-left mw-halign-center mw-halign-right mw-halign-none
768 $classes[] = "mw-halign-{$frameParams['align']}";
771 if ( isset( $frameParams['class'] ) ) {
772 $classes[] = $frameParams['class'];
777 if ( $enableLegacyMediaDOM ) {
778 $s .= "<div class=\"thumb t{$frameParams['align']}\">"
779 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
782 $isBadFile = $exists && $thumb && $parser &&
783 $parser->getBadFileLookup()->isBadFile(
784 $manualthumb ?
$manual_title : $title->getDBkey(),
789 $rdfaType = 'mw:Error ' . $rdfaType;
791 if ( !$enableLegacyMediaDOM ) {
792 $label = $frameParams['alt'] ??
'';
794 $s .= self
::makeBrokenImageLinkObj(
795 $title, $label, '', '', '', (bool)$time, $handlerParams, false
798 } elseif ( !$thumb ||
( !$enableLegacyMediaDOM && $thumb->isError() ) ||
$isBadFile ) {
799 $rdfaType = 'mw:Error ' . $rdfaType;
800 if ( $enableLegacyMediaDOM ) {
802 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
804 $s .= self
::makeBrokenImageLinkObj(
805 $title, '', '', '', '', (bool)$time, $handlerParams, true
809 if ( $thumb && $thumb->isError() ) {
811 $thumb instanceof MediaTransformError
,
812 'Unknown MediaTransformOutput: ' . get_class( $thumb )
814 $label = $thumb->toText();
815 } elseif ( !$thumb ) {
816 $label = wfMessage( 'thumbnail_error', '' )->text();
820 $s .= self
::makeBrokenImageLinkObj(
821 $title, $label, '', '', '', (bool)$time, $handlerParams, true
826 if ( !$noscale && !$manualthumb ) {
827 self
::processResponsiveImages( $file, $thumb, $handlerParams );
830 // An empty alt indicates an image is not a key part of the content
831 // and that non-visual browsers may omit it from rendering. Only
832 // set the parameter if it's explicitly requested.
833 if ( isset( $frameParams['alt'] ) ) {
834 $params['alt'] = $frameParams['alt'];
836 if ( $enableLegacyMediaDOM ) {
838 'img-class' => ( isset( $frameParams['class'] ) && $frameParams['class'] !== ''
839 ?
$frameParams['class'] . ' '
840 : '' ) . 'thumbimage'
844 'img-class' => 'mw-file-element',
846 // Only thumbs gets the magnify link
847 if ( $rdfaType === 'mw:File/Thumb' ) {
848 $params['magnify-resource'] = $url;
851 $params = self
::getImageLinkMTOParams( $frameParams, $query, $parser ) +
$params;
852 $s .= $thumb->toHtml( $params );
853 if ( isset( $frameParams['framed'] ) ) {
856 $zoomIcon = Html
::rawElement( 'div', [ 'class' => 'magnify' ],
857 Html
::rawElement( 'a', [
859 'class' => 'internal',
860 'title' => wfMessage( 'thumbnail-more' )->text(),
866 if ( $enableLegacyMediaDOM ) {
867 $s .= ' <div class="thumbcaption">' . $zoomIcon . $frameParams['caption'] . '</div></div></div>';
868 return str_replace( "\n", ' ', $s );
871 $s .= Html
::rawElement(
872 'figcaption', [], $frameParams['caption'] ??
''
877 'typeof' => $rdfaType,
880 $s = Html
::rawElement( 'figure', $attribs, $s );
882 return str_replace( "\n", ' ', $s );
886 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
890 * @param MediaTransformOutput|null $thumb
891 * @param array $hp Image parameters
893 public static function processResponsiveImages( $file, $thumb, $hp ) {
894 $responsiveImages = MediaWikiServices
::getInstance()->getMainConfig()->get( MainConfigNames
::ResponsiveImages
);
895 if ( $responsiveImages && $thumb && !$thumb->isError() ) {
897 $hp15['width'] = round( $hp['width'] * 1.5 );
899 $hp20['width'] = $hp['width'] * 2;
900 if ( isset( $hp['height'] ) ) {
901 $hp15['height'] = round( $hp['height'] * 1.5 );
902 $hp20['height'] = $hp['height'] * 2;
905 $thumb15 = $file->transform( $hp15 );
906 $thumb20 = $file->transform( $hp20 );
907 if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
908 $thumb->responsiveUrls
['1.5'] = $thumb15->getUrl();
910 if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
911 $thumb->responsiveUrls
['2'] = $thumb20->getUrl();
917 * Make a "broken" link to an image
920 * @param LinkTarget $title
921 * @param string $label Link label (plain text)
922 * @param string $query Query string
923 * @param string $unused1 Unused parameter kept for b/c
924 * @param string $unused2 Unused parameter kept for b/c
925 * @param bool $time A file of a certain timestamp was requested
926 * @param array $handlerParams @since 1.36
927 * @param bool $currentExists @since 1.41
930 public static function makeBrokenImageLinkObj(
931 $title, $label = '', $query = '', $unused1 = '', $unused2 = '',
932 $time = false, array $handlerParams = [], bool $currentExists = false
934 if ( !$title instanceof LinkTarget
) {
935 wfWarn( __METHOD__
. ': Requires $title to be a LinkTarget object.' );
936 return "<!-- ERROR -->" . htmlspecialchars( $label );
939 $title = Title
::newFromLinkTarget( $title );
940 $services = MediaWikiServices
::getInstance();
941 $mainConfig = $services->getMainConfig();
942 $enableUploads = $mainConfig->get( MainConfigNames
::EnableUploads
);
943 $uploadMissingFileUrl = $mainConfig->get( MainConfigNames
::UploadMissingFileUrl
);
944 $uploadNavigationUrl = $mainConfig->get( MainConfigNames
::UploadNavigationUrl
);
945 if ( $label == '' ) {
946 $label = $title->getPrefixedText();
949 $html = Html
::element( 'span', [
950 'class' => 'mw-file-element mw-broken-media',
951 // These data attributes are used to dynamically size the span, see T273013
952 'data-width' => $handlerParams['width'] ??
null,
953 'data-height' => $handlerParams['height'] ??
null,
956 if ( $mainConfig->get( MainConfigNames
::ParserEnableLegacyMediaDOM
) ) {
957 $html = htmlspecialchars( $label, ENT_COMPAT
);
960 $repoGroup = $services->getRepoGroup();
961 $currentExists = $currentExists ||
962 ( $time && $repoGroup->findFile( $title ) !== false );
964 if ( ( $uploadMissingFileUrl ||
$uploadNavigationUrl ||
$enableUploads )
968 $title->inNamespace( NS_FILE
) &&
969 $repoGroup->getLocalRepo()->checkRedirect( $title )
971 // We already know it's a redirect, so mark it accordingly
975 [ 'class' => 'mw-redirect' ],
976 wfCgiToArray( $query ),
977 [ 'known', 'noclasses' ]
980 return Html
::rawElement( 'a', [
981 'href' => self
::getUploadUrl( $title, $query ),
983 'title' => $title->getPrefixedText()
990 wfCgiToArray( $query ),
991 [ 'known', 'noclasses' ]
996 * Get the URL to upload a certain file
999 * @param LinkTarget $destFile LinkTarget object of the file to upload
1000 * @param string $query Urlencoded query string to prepend
1001 * @return string Urlencoded URL
1003 public static function getUploadUrl( $destFile, $query = '' ) {
1004 $mainConfig = MediaWikiServices
::getInstance()->getMainConfig();
1005 $uploadMissingFileUrl = $mainConfig->get( MainConfigNames
::UploadMissingFileUrl
);
1006 $uploadNavigationUrl = $mainConfig->get( MainConfigNames
::UploadNavigationUrl
);
1007 $q = 'wpDestFile=' . Title
::newFromLinkTarget( $destFile )->getPartialURL();
1008 if ( $query != '' ) {
1012 if ( $uploadMissingFileUrl ) {
1013 return wfAppendQuery( $uploadMissingFileUrl, $q );
1016 if ( $uploadNavigationUrl ) {
1017 return wfAppendQuery( $uploadNavigationUrl, $q );
1020 $upload = SpecialPage
::getTitleFor( 'Upload' );
1022 return $upload->getLocalURL( $q );
1026 * Create a direct link to a given uploaded file.
1029 * @param LinkTarget $title
1030 * @param string $html Pre-sanitized HTML
1031 * @param string|false $time MW timestamp of file creation time
1032 * @return string HTML
1034 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
1035 $img = MediaWikiServices
::getInstance()->getRepoGroup()->findFile(
1036 $title, [ 'time' => $time ]
1038 return self
::makeMediaLinkFile( $title, $img, $html );
1042 * Create a direct link to a given uploaded file.
1043 * This will make a broken link if $file is false.
1046 * @param LinkTarget $title
1047 * @param File|false $file File object or false
1048 * @param string $html Pre-sanitized HTML
1049 * @return string HTML
1051 * @todo Handle invalid or missing images better.
1053 public static function makeMediaLinkFile( LinkTarget
$title, $file, $html = '' ) {
1054 if ( $file && $file->exists() ) {
1055 $url = $file->getUrl();
1056 $class = 'internal';
1058 $url = self
::getUploadUrl( $title );
1062 $alt = $title->getText();
1063 if ( $html == '' ) {
1074 if ( !( new HookRunner( MediaWikiServices
::getInstance()->getHookContainer() ) )->onLinkerMakeMediaLinkFile(
1075 Title
::newFromLinkTarget( $title ), $file, $html, $attribs, $ret )
1077 wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
1078 . "with url {$url} and text {$html} to {$ret}" );
1082 return Html
::rawElement( 'a', $attribs, $html );
1086 * Make a link to a special page given its name and, optionally,
1087 * a message key from the link text.
1088 * Usage example: Linker::specialLink( 'Recentchanges' )
1091 * @param string $name Special page name, can optionally include …/subpages and …?parameters
1092 * @param string $key Optional message key if different from $name
1095 public static function specialLink( $name, $key = '' ) {
1096 $queryPos = strpos( $name, '?' );
1097 if ( $queryPos !== false ) {
1098 $getParams = wfCgiToArray( substr( $name, $queryPos +
1 ) );
1099 $name = substr( $name, 0, $queryPos );
1104 $slashPos = strpos( $name, '/' );
1105 if ( $slashPos !== false ) {
1106 $subpage = substr( $name, $slashPos +
1 );
1107 $name = substr( $name, 0, $slashPos );
1113 $key = strtolower( $name );
1116 return self
::linkKnown(
1117 SpecialPage
::getTitleFor( $name, $subpage ),
1118 wfMessage( $key )->escaped(),
1125 * Make an external link
1127 * @since 1.16.3. $title added in 1.21
1128 * @param string $url URL to link to
1129 * @param-taint $url escapes_html
1130 * @param string $text Text of link
1131 * @param-taint $text none
1132 * @param bool $escape Do we escape the link text?
1133 * @param-taint $escape none
1134 * @param string $linktype Type of external link. Gets added to the classes
1135 * @param-taint $linktype escapes_html
1136 * @param array $attribs Array of extra attributes to <a>
1137 * @param-taint $attribs escapes_html
1138 * @param LinkTarget|null $title LinkTarget object used for title specific link attributes
1139 * @param-taint $title none
1141 * @deprecated since 1.43; use LinkRenderer::makeExternalLink(), passing
1142 * in an HtmlArmor instance if $escape was false.
1144 public static function makeExternalLink( $url, $text, $escape = true,
1145 $linktype = '', $attribs = [], $title = null
1147 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgTitle
1149 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1150 return $linkRenderer->makeExternalLink(
1152 $escape ?
$text : new HtmlArmor( $text ),
1153 $title ??
$wgTitle ?? SpecialPage
::getTitleFor( 'Badtitle' ),
1160 * Make user link (or user contributions for unregistered users)
1162 * This method produces HTML that requires CSS styles in mediawiki.interface.helpers.styles.
1164 * @param int $userId User id in database.
1165 * @param string $userName User name in database.
1166 * @param string|false $altUserName Text to display instead of the user name (optional)
1167 * @param string[] $attributes Extra HTML attributes. See Linker::link.
1168 * @return string HTML fragment
1169 * @since 1.16.3. $altUserName was added in 1.19. $attributes was added in 1.40.
1171 public static function userLink(
1174 $altUserName = false,
1177 if ( $userName === '' ||
$userName === false ||
$userName === null ) {
1178 wfDebug( __METHOD__
. ' received an empty username. Are there database errors ' .
1179 'that need to be fixed?' );
1180 return wfMessage( 'empty-username' )->parse();
1183 $classes = 'mw-userlink';
1184 if ( MediaWikiServices
::getInstance()->getTempUserConfig()->isTempName( $userName ) ) {
1185 $classes .= ' mw-tempuserlink';
1186 $page = SpecialPage
::getTitleValueFor( 'Contributions', $userName );
1187 } elseif ( $userId == 0 ) {
1188 $page = ExternalUserNames
::getUserLinkTitle( $userName );
1190 if ( ExternalUserNames
::isExternal( $userName ) ) {
1191 $classes .= ' mw-extuserlink';
1192 } elseif ( $altUserName === false ) {
1193 $altUserName = IPUtils
::prettifyIP( $userName );
1195 $classes .= ' mw-anonuserlink'; // Separate link class for anons (T45179)
1197 $page = TitleValue
::tryNew( NS_USER
, strtr( $userName, ' ', '_' ) );
1200 // Wrap the output with <bdi> tags for directionality isolation
1202 '<bdi>' . htmlspecialchars( $altUserName !== false ?
$altUserName : $userName ) . '</bdi>';
1204 if ( isset( $attributes['class'] ) ) {
1205 $attributes['class'] .= ' ' . $classes;
1207 $attributes['class'] = $classes;
1211 ? self
::link( $page, $linkText, $attributes )
1212 : Html
::rawElement( 'span', $attributes, $linkText );
1216 * Generate standard user tool links (talk, contributions, block link, etc.)
1219 * @param int $userId User identifier
1220 * @param string $userText User name or IP address
1221 * @param bool $redContribsWhenNoEdits Should the contributions link be
1222 * red if the user has no edits?
1223 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
1224 * and Linker::TOOL_LINKS_EMAIL).
1225 * @param int|null $edits User edit count. If you enable $redContribsWhenNoEdits,
1226 * you may pass a pre-computed edit count here, or 0 if the caller knows that
1227 * the account has 0 edits. Otherwise, the value is unused and null may
1228 * be passed. If $redContribsWhenNoEdits is enabled and null is passed, the
1229 * edit count will be lazily fetched from UserEditTracker.
1230 * @return string[] Array of HTML fragments, each of them a link tag with a distinctive
1231 * class; or a single string on error.
1233 public static function userToolLinkArray(
1234 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1236 $services = MediaWikiServices
::getInstance();
1237 $disableAnonTalk = $services->getMainConfig()->get( MainConfigNames
::DisableAnonTalk
);
1238 $talkable = !( $disableAnonTalk && $userId == 0 );
1239 $blockable = !( $flags & self
::TOOL_LINKS_NOBLOCK
);
1240 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
&& $userId;
1242 if ( $userId == 0 && ExternalUserNames
::isExternal( $userText ) ) {
1243 // No tools for an external user
1249 $items[] = self
::userTalkLink( $userId, $userText );
1252 // check if the user has an edit
1254 $attribs['class'] = 'mw-usertoollinks-contribs';
1255 if ( $redContribsWhenNoEdits ) {
1256 if ( $edits === null ) {
1257 $user = UserIdentityValue
::newRegistered( $userId, $userText );
1258 $edits = $services->getUserEditTracker()->getUserEditCount( $user );
1260 if ( $edits === 0 ) {
1261 // Note: "new" class is inappropriate here, as "new" class
1262 // should only be used for pages that do not exist.
1263 $attribs['class'] .= ' mw-usertoollinks-contribs-no-edits';
1266 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
1268 $items[] = self
::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1270 $userCanBlock = RequestContext
::getMain()->getAuthority()->isAllowed( 'block' );
1271 if ( $blockable && $userCanBlock ) {
1272 $items[] = self
::blockLink( $userId, $userText );
1277 && MediaWikiServices
::getInstance()->getEmailUserFactory()
1278 ->newEmailUser( RequestContext
::getMain()->getAuthority() )
1282 $items[] = self
::emailLink( $userId, $userText );
1285 ( new HookRunner( $services->getHookContainer() ) )->onUserToolLinksEdit( $userId, $userText, $items );
1291 * Generate standard tool links HTML from a link array returned by userToolLinkArray().
1293 * @param array $items
1294 * @param bool $useParentheses (optional, default true) Wrap comments in parentheses where needed
1297 public static function renderUserToolLinksArray( array $items, bool $useParentheses ): string {
1304 if ( $useParentheses ) {
1305 return wfMessage( 'word-separator' )->escaped()
1306 . '<span class="mw-usertoollinks">'
1307 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1312 foreach ( $items as $tool ) {
1313 $tools[] = Html
::rawElement( 'span', [], $tool );
1315 return ' <span class="mw-usertoollinks mw-changeslist-links">' .
1316 implode( ' ', $tools ) . '</span>';
1320 * Generate standard user tool links (talk, contributions, block link, etc.)
1323 * @param int $userId User identifier
1324 * @param string $userText User name or IP address
1325 * @param bool $redContribsWhenNoEdits Should the contributions link be
1326 * red if the user has no edits?
1327 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
1328 * and Linker::TOOL_LINKS_EMAIL).
1329 * @param int|null $edits User edit count (optional, for performance)
1330 * @param bool $useParentheses (optional, default true) Wrap comments in parentheses where needed
1331 * @return string HTML fragment
1333 public static function userToolLinks(
1334 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null,
1335 $useParentheses = true
1337 if ( $userText === '' ) {
1338 wfDebug( __METHOD__
. ' received an empty username. Are there database errors ' .
1339 'that need to be fixed?' );
1340 return ' ' . wfMessage( 'empty-username' )->parse();
1343 $items = self
::userToolLinkArray( $userId, $userText, $redContribsWhenNoEdits, $flags, $edits );
1344 return self
::renderUserToolLinksArray( $items, $useParentheses );
1348 * Alias for userToolLinks( $userId, $userText, true );
1350 * @param int $userId User identifier
1351 * @param string $userText User name or IP address
1352 * @param int|null $edits User edit count (optional, for performance)
1353 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
1356 public static function userToolLinksRedContribs(
1357 $userId, $userText, $edits = null, $useParentheses = true
1359 return self
::userToolLinks( $userId, $userText, true, 0, $edits, $useParentheses );
1364 * @param int $userId User id in database.
1365 * @param string $userText User name in database.
1366 * @return string HTML fragment with user talk link
1368 public static function userTalkLink( $userId, $userText ) {
1369 if ( $userText === '' ) {
1370 wfDebug( __METHOD__
. ' received an empty username. Are there database errors ' .
1371 'that need to be fixed?' );
1372 return wfMessage( 'empty-username' )->parse();
1375 $userTalkPage = TitleValue
::tryNew( NS_USER_TALK
, strtr( $userText, ' ', '_' ) );
1376 $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-talk' ];
1377 $linkText = wfMessage( 'talkpagelinktext' )->escaped();
1379 return $userTalkPage
1380 ? self
::link( $userTalkPage, $linkText, $moreLinkAttribs )
1381 : Html
::rawElement( 'span', $moreLinkAttribs, $linkText );
1386 * @param int $userId
1387 * @param string $userText User name in database.
1388 * @return string HTML fragment with block link
1390 public static function blockLink( $userId, $userText ) {
1391 if ( $userText === '' ) {
1392 wfDebug( __METHOD__
. ' received an empty username. Are there database errors ' .
1393 'that need to be fixed?' );
1394 return wfMessage( 'empty-username' )->parse();
1397 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1398 $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-block' ];
1400 return self
::link( $blockPage,
1401 wfMessage( 'blocklink' )->escaped(),
1407 * @param int $userId
1408 * @param string $userText User name in database.
1409 * @return string HTML fragment with e-mail user link
1411 public static function emailLink( $userId, $userText ) {
1412 if ( $userText === '' ) {
1413 wfLogWarning( __METHOD__
. ' received an empty username. Are there database errors ' .
1414 'that need to be fixed?' );
1415 return wfMessage( 'empty-username' )->parse();
1418 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1419 $moreLinkAttribs = [ 'class' => 'mw-usertoollinks-mail' ];
1420 return self
::link( $emailPage,
1421 wfMessage( 'emaillink' )->escaped(),
1427 * Generate a user link if the current user is allowed to view it
1429 * This method produces HTML that requires CSS styles in mediawiki.interface.helpers.styles.
1432 * @param RevisionRecord $revRecord (Switched from the old Revision class to RevisionRecord
1434 * @param bool $isPublic Show only if all users can see it
1435 * @return string HTML fragment
1437 public static function revUserLink( RevisionRecord
$revRecord, $isPublic = false ) {
1438 // TODO inject authority
1439 $authority = RequestContext
::getMain()->getAuthority();
1441 $revUser = $revRecord->getUser(
1442 $isPublic ? RevisionRecord
::FOR_PUBLIC
: RevisionRecord
::FOR_THIS_USER
,
1446 $link = self
::userLink( $revUser->getId(), $revUser->getName() );
1448 // User is deleted and we can't (or don't want to) view it
1449 $link = wfMessage( 'rev-deleted-user' )->escaped();
1452 if ( $revRecord->isDeleted( RevisionRecord
::DELETED_USER
) ) {
1453 $class = self
::getRevisionDeletedClass( $revRecord );
1454 return '<span class="' . $class . '">' . $link . '</span>';
1460 * Returns css class of a deleted revision
1461 * @param RevisionRecord $revisionRecord
1462 * @return string 'history-deleted', 'mw-history-suppressed' added if suppressed too
1465 public static function getRevisionDeletedClass( RevisionRecord
$revisionRecord ): string {
1466 $class = 'history-deleted';
1467 if ( $revisionRecord->isDeleted( RevisionRecord
::DELETED_RESTRICTED
) ) {
1468 $class .= ' mw-history-suppressed';
1474 * Generate a user tool link cluster if the current user is allowed to view it
1476 * This method produces HTML that requires CSS styles in mediawiki.interface.helpers.styles.
1479 * @param RevisionRecord $revRecord (Switched from the old Revision class to RevisionRecord
1481 * @param bool $isPublic Show only if all users can see it
1482 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
1483 * @return string HTML
1485 public static function revUserTools(
1486 RevisionRecord
$revRecord,
1488 $useParentheses = true
1490 // TODO inject authority
1491 $authority = RequestContext
::getMain()->getAuthority();
1493 $revUser = $revRecord->getUser(
1494 $isPublic ? RevisionRecord
::FOR_PUBLIC
: RevisionRecord
::FOR_THIS_USER
,
1498 $link = self
::userLink(
1500 $revUser->getName(),
1502 [ 'data-mw-revid' => $revRecord->getId() ]
1503 ) . self
::userToolLinks(
1505 $revUser->getName(),
1512 // User is deleted and we can't (or don't want to) view it
1513 $link = wfMessage( 'rev-deleted-user' )->escaped();
1516 if ( $revRecord->isDeleted( RevisionRecord
::DELETED_USER
) ) {
1517 $class = self
::getRevisionDeletedClass( $revRecord );
1518 return ' <span class="' . $class . ' mw-userlink">' . $link . '</span>';
1524 * Helper function to expand local links. Mostly used in action=render
1529 * @param string $html
1531 * @return string HTML
1533 public static function expandLocalLinks( string $html ) {
1534 return HtmlHelper
::modifyElements(
1536 static function ( SerializerNode
$node ): bool {
1537 return $node->name
=== 'a' && isset( $node->attrs
['href'] );
1539 static function ( SerializerNode
$node ): SerializerNode
{
1540 $urlUtils = MediaWikiServices
::getInstance()->getUrlUtils();
1541 $node->attrs
['href'] =
1542 $urlUtils->expand( $node->attrs
['href'], PROTO_RELATIVE
) ??
false;
1549 * @param LinkTarget|null $contextTitle
1550 * @param string $target
1551 * @param string &$text
1554 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1557 # :Foobar -- override special treatment of prefix (images, language links)
1558 # /Foobar -- convert to CurrentPage/Foobar
1559 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1560 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1561 # ../Foobar -- convert to CurrentPage/Foobar,
1562 # (from CurrentPage/CurrentSubPage)
1563 # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1564 # (from CurrentPage/CurrentSubPage)
1566 $ret = $target; # default return value is no change
1568 # Some namespaces don't allow subpages,
1569 # so only perform processing if subpages are allowed
1571 $contextTitle && MediaWikiServices
::getInstance()->getNamespaceInfo()->
1572 hasSubpages( $contextTitle->getNamespace() )
1574 $hash = strpos( $target, '#' );
1575 if ( $hash !== false ) {
1576 $suffix = substr( $target, $hash );
1577 $target = substr( $target, 0, $hash );
1582 $target = trim( $target );
1583 $contextPrefixedText = MediaWikiServices
::getInstance()->getTitleFormatter()->
1584 getPrefixedText( $contextTitle );
1585 # Look at the first character
1586 if ( $target != '' && $target[0] === '/' ) {
1587 # / at end means we don't want the slash to be shown
1589 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1590 if ( $trailingSlashes ) {
1591 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1593 $noslash = substr( $target, 1 );
1596 $ret = $contextPrefixedText . '/' . trim( $noslash ) . $suffix;
1597 if ( $text === '' ) {
1598 $text = $target . $suffix;
1599 } # this might be changed for ugliness reasons
1601 # check for .. subpage backlinks
1603 $nodotdot = $target;
1604 while ( str_starts_with( $nodotdot, '../' ) ) {
1606 $nodotdot = substr( $nodotdot, 3 );
1608 if ( $dotdotcount > 0 ) {
1609 $exploded = explode( '/', $contextPrefixedText );
1610 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1611 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1612 # / at the end means don't show full path
1613 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1614 $nodotdot = rtrim( $nodotdot, '/' );
1615 if ( $text === '' ) {
1616 $text = $nodotdot . $suffix;
1619 $nodotdot = trim( $nodotdot );
1620 if ( $nodotdot != '' ) {
1621 $ret .= '/' . $nodotdot;
1637 public static function formatRevisionSize( $size ) {
1639 $stxt = wfMessage( 'historyempty' )->escaped();
1641 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1643 return "<span class=\"history-size mw-diff-bytes\" data-mw-bytes=\"$size\">$stxt</span>";
1647 * Split a link trail, return the "inside" portion and the remainder of the trail
1648 * as a two-element array
1649 * @param string $trail
1652 public static function splitTrail( $trail ) {
1653 $regex = MediaWikiServices
::getInstance()->getContentLanguage()->linkTrail();
1655 if ( $trail !== '' && preg_match( $regex, $trail, $m ) ) {
1656 [ , $inside, $trail ] = $m;
1658 return [ $inside, $trail ];
1662 * Generate a rollback link for a given revision. Currently it's the
1663 * caller's responsibility to ensure that the revision is the top one. If
1664 * it's not, of course, the user will get an error message.
1666 * If the calling page is called with the parameter &bot=1, all rollback
1667 * links also get that parameter. It causes the edit itself and the rollback
1668 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1669 * changes, so this allows sysops to combat a busy vandal without bothering
1672 * This function will return the link only in case the revision can be reverted
1673 * (not all revisions are by the same user, and the last revision by a different
1674 * user is visible). Please note that due to performance limitations it might be
1675 * assumed that a user isn't the only contributor of a page while (s)he is, which
1676 * will lead to useless rollback links. Furthermore this won't work if
1677 * $wgShowRollbackEditCount is disabled, so this can only function as an
1680 * If the option noBrackets is set the rollback link wont be enclosed in "[]".
1682 * @since 1.16.3. $context added in 1.20. $options added in 1.21
1683 * $rev could be a RevisionRecord since 1.35
1685 * @param RevisionRecord $revRecord (Switched from the old Revision class to RevisionRecord
1687 * @param IContextSource|null $context Context to use or null for the main context.
1688 * @param array $options
1691 public static function generateRollback(
1692 RevisionRecord
$revRecord,
1693 ?IContextSource
$context = null,
1696 $context ??
= RequestContext
::getMain();
1698 $editCount = self
::getRollbackEditCount( $revRecord );
1699 if ( $editCount === false ) {
1703 $inner = self
::buildRollbackLink( $revRecord, $context, $editCount );
1705 $services = MediaWikiServices
::getInstance();
1706 // Allow extensions to modify the rollback link.
1707 // Abort further execution if the extension wants full control over the link.
1708 if ( !( new HookRunner( $services->getHookContainer() ) )->onLinkerGenerateRollbackLink(
1709 $revRecord, $context, $options, $inner ) ) {
1713 if ( !in_array( 'noBrackets', $options, true ) ) {
1714 $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1717 if ( $services->getUserOptionsLookup()
1718 ->getBoolOption( $context->getUser(), 'showrollbackconfirmation' )
1720 $services->getStatsFactory()
1721 ->getCounter( 'rollbackconfirmation_event_load_total' )
1722 ->copyToStatsdAt( 'rollbackconfirmation.event.load' )
1724 $context->getOutput()->addModules( 'mediawiki.misc-authed-curate' );
1727 return '<span class="mw-rollback-link">' . $inner . '</span>';
1731 * This function will return the number of revisions which a rollback
1732 * would revert and will verify that a revision can be reverted (that
1733 * the user isn't the only contributor and the revision we might
1734 * rollback to isn't deleted). These checks can only function as an
1735 * additional check as this function only checks against the last
1736 * $wgShowRollbackEditCount edits.
1738 * Returns null if $wgShowRollbackEditCount is disabled or false if
1739 * the user is the only contributor of the page.
1741 * @todo Unused outside of this file - should it be made private?
1743 * @param RevisionRecord $revRecord (Switched from the old Revision class to RevisionRecord
1745 * @param bool $verify Deprecated since 1.40, has no effect.
1746 * @return int|false|null
1748 public static function getRollbackEditCount( RevisionRecord
$revRecord, $verify = true ) {
1749 if ( func_num_args() > 1 ) {
1750 wfDeprecated( __METHOD__
. ' with $verify parameter', '1.40' );
1752 $showRollbackEditCount = MediaWikiServices
::getInstance()->getMainConfig()
1753 ->get( MainConfigNames
::ShowRollbackEditCount
);
1755 if ( !is_int( $showRollbackEditCount ) ||
!$showRollbackEditCount > 0 ) {
1756 // Nothing has happened, indicate this by returning 'null'
1760 $dbr = MediaWikiServices
::getInstance()->getConnectionProvider()->getReplicaDatabase();
1762 // Up to the value of $wgShowRollbackEditCount revisions are counted
1763 $queryBuilder = MediaWikiServices
::getInstance()->getRevisionStore()->newSelectQueryBuilder( $dbr );
1764 $res = $queryBuilder->where( [ 'rev_page' => $revRecord->getPageId() ] )
1765 ->useIndex( [ 'revision' => 'rev_page_timestamp' ] )
1766 ->orderBy( [ 'rev_timestamp', 'rev_id' ], SelectQueryBuilder
::SORT_DESC
)
1767 ->limit( $showRollbackEditCount +
1 )
1768 ->caller( __METHOD__
)->fetchResultSet();
1770 $revUser = $revRecord->getUser( RevisionRecord
::RAW
);
1771 $revUserText = $revUser ?
$revUser->getName() : '';
1775 foreach ( $res as $row ) {
1776 if ( $row->rev_user_text
!= $revUserText ) {
1777 if ( $row->rev_deleted
& RevisionRecord
::DELETED_TEXT
1778 ||
$row->rev_deleted
& RevisionRecord
::DELETED_USER
1780 // If the user or the text of the revision we might rollback
1781 // to is deleted in some way we can't rollback. Similar to
1782 // the checks in WikiPage::commitRollback.
1791 if ( $editCount <= $showRollbackEditCount && !$moreRevs ) {
1792 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1793 // and there weren't any other revisions. That means that the current user is the only
1794 // editor, so we can't rollback
1801 * Build a raw rollback link, useful for collections of "tool" links
1803 * @since 1.16.3. $context added in 1.20. $editCount added in 1.21
1804 * $rev could be a RevisionRecord since 1.35
1806 * @todo Unused outside of this file - should it be made private?
1808 * @param RevisionRecord $revRecord (Switched from the old Revision class to RevisionRecord
1810 * @param IContextSource|null $context Context to use or null for the main context.
1811 * @param int|false|null $editCount Number of edits that would be reverted
1812 * @return string HTML fragment
1814 public static function buildRollbackLink(
1815 RevisionRecord
$revRecord,
1816 ?IContextSource
$context = null,
1819 $config = MediaWikiServices
::getInstance()->getMainConfig();
1820 $showRollbackEditCount = $config->get( MainConfigNames
::ShowRollbackEditCount
);
1821 $miserMode = $config->get( MainConfigNames
::MiserMode
);
1822 // To config which pages are affected by miser mode
1823 $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
1825 $context ??
= RequestContext
::getMain();
1827 $title = $revRecord->getPageAsLinkTarget();
1828 $revUser = $revRecord->getUser();
1829 $revUserText = $revUser ?
$revUser->getName() : '';
1832 'action' => 'rollback',
1833 'from' => $revUserText,
1834 'token' => $context->getUser()->getEditToken( 'rollback' ),
1838 'data-mw' => 'interface',
1839 'title' => $context->msg( 'tooltip-rollback' )->text()
1842 $options = [ 'known', 'noclasses' ];
1844 if ( $context->getRequest()->getBool( 'bot' ) ) {
1846 $query['hidediff'] = '1';
1847 $query['bot'] = '1';
1851 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1852 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1853 $showRollbackEditCount = false;
1859 // The edit count can be 0 on replica lag, fall back to the generic rollbacklink message
1860 $msg = [ 'rollbacklink' ];
1861 if ( is_int( $showRollbackEditCount ) && $showRollbackEditCount > 0 ) {
1862 if ( !is_numeric( $editCount ) ) {
1863 $editCount = self
::getRollbackEditCount( $revRecord );
1866 if ( $editCount > $showRollbackEditCount ) {
1867 $msg = [ 'rollbacklinkcount-morethan', Message
::numParam( $showRollbackEditCount ) ];
1868 } elseif ( $editCount ) {
1869 $msg = [ 'rollbacklinkcount', Message
::numParam( $editCount ) ];
1873 $html = $context->msg( ...$msg )->parse();
1874 return self
::link( $title, $html, $attrs, $query, $options );
1878 * Returns HTML for the "hidden categories on this page" list.
1881 * @param array $hiddencats Array of hidden categories
1882 * from {@link WikiPage::getHiddenCategories} or similar
1883 * @return string HTML output
1885 public static function formatHiddenCategories( $hiddencats ) {
1887 if ( count( $hiddencats ) > 0 ) {
1888 # Construct the HTML
1889 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1890 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
1891 $outText .= "</div><ul>\n";
1893 foreach ( $hiddencats as $titleObj ) {
1894 # If it's hidden, it must exist - no need to check with a LinkBatch
1896 . self
::link( $titleObj, null, [], [], 'known' )
1899 $outText .= '</ul>';
1905 * @return ContextSource
1907 private static function getContextFromMain() {
1908 $context = RequestContext
::getMain();
1909 $context = new DerivativeContext( $context );
1914 * Given the id of an interface element, constructs the appropriate title
1915 * attribute from the system messages. (Note, this is usually the id but
1916 * isn't always, because sometimes the accesskey needs to go on a different
1917 * element than the id, for reverse-compatibility, etc.)
1919 * @since 1.16.3 $msgParams added in 1.27
1920 * @param string $name Id of the element, minus prefixes.
1921 * @param string|array|null $options Null, string or array with some of the following options:
1922 * - 'withaccess' to add an access-key hint
1923 * - 'nonexisting' to add an accessibility hint that page does not exist
1924 * @param array $msgParams Parameters to pass to the message
1925 * @param MessageLocalizer|null $localizer
1927 * @return string|false Contents of the title attribute (which you must HTML-
1928 * escape), or false for no title attribute
1930 public static function titleAttrib( $name, $options = null, array $msgParams = [], $localizer = null ) {
1931 if ( !$localizer ) {
1932 $localizer = self
::getContextFromMain();
1934 $message = $localizer->msg( "tooltip-$name", $msgParams );
1935 // Set a default tooltip for subject namespace tabs if that hasn't
1936 // been defined. See T22126
1937 if ( !$message->exists() && str_starts_with( $name, 'ca-nstab-' ) ) {
1938 $message = $localizer->msg( 'tooltip-ca-nstab' );
1941 if ( $message->isDisabled() ) {
1944 $tooltip = $message->text();
1945 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1946 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1949 $options = (array)$options;
1951 if ( in_array( 'nonexisting', $options ) ) {
1952 $tooltip = $localizer->msg( 'red-link-title', $tooltip ?
: '' )->text();
1954 if ( in_array( 'withaccess', $options ) ) {
1955 $accesskey = self
::accesskey( $name, $localizer );
1956 if ( $accesskey !== false ) {
1957 // Should be build the same as in jquery.accessKeyLabel.js
1958 if ( $tooltip === false ||
$tooltip === '' ) {
1959 $tooltip = $localizer->msg( 'brackets', $accesskey )->text();
1961 $tooltip .= $localizer->msg( 'word-separator' )->text();
1962 $tooltip .= $localizer->msg( 'brackets', $accesskey )->text();
1970 /** @var (string|false)[] */
1971 public static $accesskeycache;
1974 * Given the id of an interface element, constructs the appropriate
1975 * accesskey attribute from the system messages. (Note, this is usually
1976 * the id but isn't always, because sometimes the accesskey needs to go on
1977 * a different element than the id, for reverse-compatibility, etc.)
1980 * @param string $name Id of the element, minus prefixes.
1981 * @param MessageLocalizer|null $localizer
1982 * @return string|false Contents of the accesskey attribute (which you must HTML-
1983 * escape), or false for no accesskey attribute
1985 public static function accesskey( $name, $localizer = null ) {
1986 if ( !isset( self
::$accesskeycache[$name] ) ) {
1987 if ( !$localizer ) {
1988 $localizer = self
::getContextFromMain();
1990 $msg = $localizer->msg( "accesskey-$name" );
1991 // Set a default accesskey for subject namespace tabs if an
1992 // accesskey has not been defined. See T22126
1993 if ( !$msg->exists() && str_starts_with( $name, 'ca-nstab-' ) ) {
1994 $msg = $localizer->msg( 'accesskey-ca-nstab' );
1996 self
::$accesskeycache[$name] = $msg->isDisabled() ?
false : $msg->plain();
1998 return self
::$accesskeycache[$name];
2002 * Get a revision-deletion link, or disabled link, or nothing, depending
2003 * on user permissions & the settings on the revision.
2005 * Will use forward-compatible revision ID in the Special:RevDelete link
2006 * if possible, otherwise the timestamp-based ID which may break after
2009 * @param Authority $performer
2010 * @param RevisionRecord $revRecord (Switched from the old Revision class to RevisionRecord
2012 * @param LinkTarget $title
2013 * @return string HTML fragment
2015 public static function getRevDeleteLink(
2016 Authority
$performer,
2017 RevisionRecord
$revRecord,
2020 $canHide = $performer->isAllowed( 'deleterevision' );
2021 $canHideHistory = $performer->isAllowed( 'deletedhistory' );
2022 if ( !$canHide && !( $revRecord->getVisibility() && $canHideHistory ) ) {
2026 if ( !$revRecord->userCan( RevisionRecord
::DELETED_RESTRICTED
, $performer ) ) {
2027 return self
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2029 $prefixedDbKey = MediaWikiServices
::getInstance()->getTitleFormatter()->
2030 getPrefixedDBkey( $title );
2031 if ( $revRecord->getId() ) {
2032 // RevDelete links using revision ID are stable across
2033 // page deletion and undeletion; use when possible.
2035 'type' => 'revision',
2036 'target' => $prefixedDbKey,
2037 'ids' => $revRecord->getId()
2040 // Older deleted entries didn't save a revision ID.
2041 // We have to refer to these by timestamp, ick!
2043 'type' => 'archive',
2044 'target' => $prefixedDbKey,
2045 'ids' => $revRecord->getTimestamp()
2048 return self
::revDeleteLink(
2050 $revRecord->isDeleted( RevisionRecord
::DELETED_RESTRICTED
),
2056 * Creates a (show/hide) link for deleting revisions/log entries
2058 * This method produces HTML that requires CSS styles in mediawiki.interface.helpers.styles.
2060 * @param array $query Query parameters to be passed to link()
2061 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2062 * @param bool $delete Set to true to use (show/hide) rather than (show)
2064 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2065 * span to allow for customization of appearance with CSS
2067 public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2068 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
2069 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2070 $html = wfMessage( $msgKey )->escaped();
2071 $tag = $restricted ?
'strong' : 'span';
2072 $link = self
::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2075 [ 'class' => 'mw-revdelundel-link' ],
2076 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2081 * Creates a dead (show/hide) link for deleting revisions/log entries
2083 * This method produces HTML that requires CSS styles in mediawiki.interface.helpers.styles.
2086 * @param bool $delete Set to true to use (show/hide) rather than (show)
2088 * @return string HTML text wrapped in a span to allow for customization
2089 * of appearance with CSS
2091 public static function revDeleteLinkDisabled( $delete = true ) {
2092 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2093 $html = wfMessage( $msgKey )->escaped();
2094 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2095 return Xml
::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2099 * Returns the attributes for the tooltip and access key.
2101 * @since 1.16.3. $msgParams introduced in 1.27
2102 * @param string $name
2103 * @param array $msgParams Params for constructing the message
2104 * @param string|array|null $options Options to be passed to titleAttrib.
2105 * @param MessageLocalizer|null $localizer
2107 * @see Linker::titleAttrib for what options could be passed to $options.
2111 public static function tooltipAndAccesskeyAttribs(
2113 array $msgParams = [],
2117 $options = (array)$options;
2118 $options[] = 'withaccess';
2120 // Get optional parameters from global context if any missing.
2121 if ( !$localizer ) {
2122 $localizer = self
::getContextFromMain();
2126 'title' => self
::titleAttrib( $name, $options, $msgParams, $localizer ),
2127 'accesskey' => self
::accesskey( $name, $localizer )
2129 if ( $attribs['title'] === false ) {
2130 unset( $attribs['title'] );
2132 if ( $attribs['accesskey'] === false ) {
2133 unset( $attribs['accesskey'] );
2139 * Returns raw bits of HTML, use titleAttrib()
2141 * @param string $name
2142 * @param array|null $options
2143 * @return null|string
2145 public static function tooltip( $name, $options = null ) {
2146 $tooltip = self
::titleAttrib( $name, $options );
2147 if ( $tooltip === false ) {
2150 return Xml
::expandAttributes( [
2157 /** @deprecated class alias since 1.40 */
2158 class_alias( Linker
::class, 'Linker' );