3 * Methods to make links and related items.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 use MediaWiki\Linker\LinkTarget
;
23 use MediaWiki\MediaWikiServices
;
26 * Some internal bits split of from Skin.php. These functions are used
27 * for primarily page content: links, embedded images, table of contents. Links
28 * are also used in the skin.
30 * @todo turn this into a legacy interface for HtmlPageLinkRenderer and similar services.
36 * Flags for userToolLinks()
38 const TOOL_LINKS_NOBLOCK
= 1;
39 const TOOL_LINKS_EMAIL
= 2;
42 * This function returns an HTML link to the given target. It serves a few
44 * 1) If $target is a Title, the correct URL to link to will be figured
46 * 2) It automatically adds the usual classes for various types of link
47 * targets: "new" for red links, "stub" for short articles, etc.
48 * 3) It escapes all attribute values safely so there's no risk of XSS.
49 * 4) It provides a default tooltip if the target is a Title (the page
50 * name of the target).
51 * link() replaces the old functions in the makeLink() family.
53 * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
54 * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
56 * @param LinkTarget $target Can currently only be a LinkTarget, but this may
57 * change to support Images, literal URLs, etc.
58 * @param string $html The HTML contents of the <a> element, i.e.,
59 * the link text. This is raw HTML and will not be escaped. If null,
60 * defaults to the prefixed text of the Title; or if the Title is just a
61 * fragment, the contents of the fragment.
62 * @param array $customAttribs A key => value array of extra HTML attributes,
63 * such as title and class. (href is ignored.) Classes will be
64 * merged with the default classes, while other attributes will replace
65 * default attributes. All passed attribute values will be HTML-escaped.
66 * A false attribute value means to suppress that attribute.
67 * @param array $query The query string to append to the URL
68 * you're linking to, in key => value array form. Query keys and values
69 * will be URL-encoded.
70 * @param string|array $options String or array of strings:
71 * 'known': Page is known to exist, so don't check if it does.
72 * 'broken': Page is known not to exist, so don't check if it does.
73 * 'noclasses': Don't add any classes automatically (includes "new",
74 * "stub", "mw-redirect", "extiw"). Only use the class attribute
75 * provided, if any, so you get a simple blue link with no funny i-
77 * 'forcearticlepath': Use the article path always, even with a querystring.
78 * Has compatibility issues on some setups, so avoid wherever possible.
79 * 'http': Force a full URL with http:// as the scheme.
80 * 'https': Force a full URL with https:// as the scheme.
81 * 'stubThreshold' => (int): Stub threshold to use when determining link classes.
82 * @return string HTML <a> attribute
84 public static function link(
85 $target, $html = null, $customAttribs = [], $query = [], $options = []
87 if ( !$target instanceof LinkTarget
) {
88 wfWarn( __METHOD__
. ': Requires $target to be a LinkTarget object.', 2 );
89 return "<!-- ERROR -->$html";
92 if ( is_string( $query ) ) {
93 // some functions withing core using this still hand over query strings
94 wfDeprecated( __METHOD__
. ' with parameter $query as string (should be array)', '1.20' );
95 $query = wfCgiToArray( $query );
98 $services = MediaWikiServices
::getInstance();
99 $options = (array)$options;
101 // Custom options, create new LinkRenderer
102 if ( !isset( $options['stubThreshold'] ) ) {
103 $defaultLinkRenderer = $services->getLinkRenderer();
104 $options['stubThreshold'] = $defaultLinkRenderer->getStubThreshold();
106 $linkRenderer = $services->getLinkRendererFactory()
107 ->createFromLegacyOptions( $options );
109 $linkRenderer = $services->getLinkRenderer();
112 if ( $html !== null ) {
113 $text = new HtmlArmor( $html );
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 Title $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.
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 $ret = "<a class=\"mw-selflink selflink\">{$prefix}{$html}</a>{$trail}";
170 if ( !Hooks
::run( 'SelfLinkBegin', [ $nt, &$html, &$trail, &$prefix, &$ret ] ) ) {
175 $html = htmlspecialchars( $nt->getPrefixedText() );
177 list( $inside, $trail ) = self
::splitTrail( $trail );
178 return "<a class=\"mw-selflink selflink\">{$prefix}{$html}{$inside}</a>{$trail}";
182 * Get a message saying that an invalid title was encountered.
183 * This should be called after a method like Title::makeTitleSafe() returned
184 * a value indicating that the title object is invalid.
186 * @param IContextSource $context Context to use to get the messages
187 * @param int $namespace Namespace number
188 * @param string $title Text of the title, without the namespace part
191 public static function getInvalidTitleDescription( IContextSource
$context, $namespace, $title ) {
192 // First we check whether the namespace exists or not.
193 if ( MWNamespace
::exists( $namespace ) ) {
194 if ( $namespace == NS_MAIN
) {
195 $name = $context->msg( 'blanknamespace' )->text();
197 $name = MediaWikiServices
::getInstance()->getContentLanguage()->
198 getFormattedNsText( $namespace );
200 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
203 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
208 * @param LinkTarget $target
211 public static function normaliseSpecialPage( LinkTarget
$target ) {
212 if ( $target->getNamespace() == NS_SPECIAL
&& !$target->isExternal() ) {
213 list( $name, $subpage ) = MediaWikiServices
::getInstance()->getSpecialPageFactory()->
214 resolveAlias( $target->getDBkey() );
216 return SpecialPage
::getTitleValueFor( $name, $subpage, $target->getFragment() );
224 * Returns the filename part of an url.
225 * Used as alternative text for external images.
231 private static function fnamePart( $url ) {
232 $basename = strrchr( $url, '/' );
233 if ( $basename === false ) {
236 $basename = substr( $basename, 1 );
242 * Return the code for images which were added via external links,
243 * via Parser::maybeMakeExternalImage().
251 public static function makeExternalImage( $url, $alt = '' ) {
253 $alt = self
::fnamePart( $url );
256 $success = Hooks
::run( 'LinkerMakeExternalImage', [ &$url, &$alt, &$img ] );
258 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
259 . "with url {$url} and alt text {$alt} to {$img}\n", true );
262 return Html
::element( 'img',
271 * Given parameters derived from [[Image:Foo|options...]], generate the
272 * HTML that that syntax inserts in the page.
274 * @param Parser $parser
275 * @param Title $title Title object of the file (not the currently viewed page)
276 * @param File $file File object, or false if it doesn't exist
277 * @param array $frameParams Associative array of parameters external to the media handler.
278 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
279 * will often be false.
280 * thumbnail If present, downscale and frame
281 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
282 * framed Shows image in original size in a frame
283 * frameless Downscale but don't frame
284 * upright If present, tweak default sizes for portrait orientation
285 * upright_factor Fudge factor for "upright" tweak (default 0.75)
286 * border If present, show a border around the image
287 * align Horizontal alignment (left, right, center, none)
288 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
289 * bottom, text-bottom)
290 * alt Alternate text for image (i.e. alt attribute). Plain text.
291 * class HTML for image classes. Plain text.
292 * caption HTML for image caption.
293 * link-url URL to link to
294 * link-title Title object to link to
295 * link-target Value for the target attribute, only with link-url
296 * no-link Boolean, suppress description link
297 * targetlang (optional) Target language code, see Parser::getTargetLanguage()
299 * @param array $handlerParams Associative array of media handler parameters, to be passed
300 * to transform(). Typical keys are "width" and "page".
301 * @param string|bool $time Timestamp of the file, set as false for current
302 * @param string $query Query params for desc url
303 * @param int|null $widthOption Used by the parser to remember the user preference thumbnailsize
305 * @return string HTML for an image, with links, wrappers, etc.
307 public static function makeImageLink( Parser
$parser, Title
$title,
308 $file, $frameParams = [], $handlerParams = [], $time = false,
309 $query = "", $widthOption = null
312 $dummy = new DummyLinker
;
313 if ( !Hooks
::run( 'ImageBeforeProduceHTML', [ &$dummy, &$title,
314 &$file, &$frameParams, &$handlerParams, &$time, &$res,
315 $parser, &$query, &$widthOption
320 if ( $file && !$file->allowInlineDisplay() ) {
321 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
322 return self
::link( $title );
325 // Clean up parameters
326 $page = $handlerParams['page'] ??
false;
327 if ( !isset( $frameParams['align'] ) ) {
328 $frameParams['align'] = '';
330 if ( !isset( $frameParams['alt'] ) ) {
331 $frameParams['alt'] = '';
333 if ( !isset( $frameParams['title'] ) ) {
334 $frameParams['title'] = '';
336 if ( !isset( $frameParams['class'] ) ) {
337 $frameParams['class'] = '';
340 $prefix = $postfix = '';
342 if ( $frameParams['align'] == 'center' ) {
343 $prefix = '<div class="center">';
345 $frameParams['align'] = 'none';
347 if ( $file && !isset( $handlerParams['width'] ) ) {
348 if ( isset( $handlerParams['height'] ) && $file->isVectorized() ) {
349 // If its a vector image, and user only specifies height
350 // we don't want it to be limited by its "normal" width.
351 global $wgSVGMaxSize;
352 $handlerParams['width'] = $wgSVGMaxSize;
354 $handlerParams['width'] = $file->getWidth( $page );
357 if ( isset( $frameParams['thumbnail'] )
358 ||
isset( $frameParams['manualthumb'] )
359 ||
isset( $frameParams['framed'] )
360 ||
isset( $frameParams['frameless'] )
361 ||
!$handlerParams['width']
363 global $wgThumbLimits, $wgThumbUpright;
365 if ( $widthOption === null ||
!isset( $wgThumbLimits[$widthOption] ) ) {
366 $widthOption = User
::getDefaultOption( 'thumbsize' );
369 // Reduce width for upright images when parameter 'upright' is used
370 if ( isset( $frameParams['upright'] ) && $frameParams['upright'] == 0 ) {
371 $frameParams['upright'] = $wgThumbUpright;
374 // For caching health: If width scaled down due to upright
375 // parameter, round to full __0 pixel to avoid the creation of a
376 // lot of odd thumbs.
377 $prefWidth = isset( $frameParams['upright'] ) ?
378 round( $wgThumbLimits[$widthOption] * $frameParams['upright'], -1 ) :
379 $wgThumbLimits[$widthOption];
381 // Use width which is smaller: real image width or user preference width
382 // Unless image is scalable vector.
383 if ( !isset( $handlerParams['height'] ) && ( $handlerParams['width'] <= 0 ||
384 $prefWidth < $handlerParams['width'] ||
$file->isVectorized() ) ) {
385 $handlerParams['width'] = $prefWidth;
390 if ( isset( $frameParams['thumbnail'] ) ||
isset( $frameParams['manualthumb'] )
391 ||
isset( $frameParams['framed'] )
393 # Create a thumbnail. Alignment depends on the writing direction of
394 # the page content language (right-aligned for LTR languages,
395 # left-aligned for RTL languages)
396 # If a thumbnail width has not been provided, it is set
397 # to the default user option as specified in Language*.php
398 if ( $frameParams['align'] == '' ) {
399 $frameParams['align'] = $parser->getTargetLanguage()->alignEnd();
402 self
::makeThumbLink2( $title, $file, $frameParams, $handlerParams, $time, $query ) .
406 if ( $file && isset( $frameParams['frameless'] ) ) {
407 $srcWidth = $file->getWidth( $page );
408 # For "frameless" option: do not present an image bigger than the
409 # source (for bitmap-style images). This is the same behavior as the
410 # "thumb" option does it already.
411 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
412 $handlerParams['width'] = $srcWidth;
416 if ( $file && isset( $handlerParams['width'] ) ) {
417 # Create a resized image, without the additional thumbnail features
418 $thumb = $file->transform( $handlerParams );
424 $s = self
::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
426 self
::processResponsiveImages( $file, $thumb, $handlerParams );
428 'alt' => $frameParams['alt'],
429 'title' => $frameParams['title'],
430 'valign' => $frameParams['valign'] ??
false,
431 'img-class' => $frameParams['class'] ];
432 if ( isset( $frameParams['border'] ) ) {
433 $params['img-class'] .= ( $params['img-class'] !== '' ?
' ' : '' ) . 'thumbborder';
435 $params = self
::getImageLinkMTOParams( $frameParams, $query, $parser ) +
$params;
437 $s = $thumb->toHtml( $params );
439 if ( $frameParams['align'] != '' ) {
440 $s = Html
::rawElement(
442 [ 'class' => 'float' . $frameParams['align'] ],
446 return str_replace( "\n", ' ', $prefix . $s . $postfix );
450 * Get the link parameters for MediaTransformOutput::toHtml() from given
451 * frame parameters supplied by the Parser.
452 * @param array $frameParams The frame parameters
453 * @param string $query An optional query string to add to description page links
454 * @param Parser|null $parser
457 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
459 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
460 $mtoParams['custom-url-link'] = $frameParams['link-url'];
461 if ( isset( $frameParams['link-target'] ) ) {
462 $mtoParams['custom-target-link'] = $frameParams['link-target'];
465 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
466 foreach ( $extLinkAttrs as $name => $val ) {
467 // Currently could include 'rel' and 'target'
468 $mtoParams['parser-extlink-' . $name] = $val;
471 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
472 $mtoParams['custom-title-link'] = Title
::newFromLinkTarget(
473 self
::normaliseSpecialPage( $frameParams['link-title'] )
475 } elseif ( !empty( $frameParams['no-link'] ) ) {
478 $mtoParams['desc-link'] = true;
479 $mtoParams['desc-query'] = $query;
485 * Make HTML for a thumbnail including image, border and caption
486 * @param Title $title
487 * @param File|bool $file File object or false if it doesn't exist
488 * @param string $label
490 * @param string $align
491 * @param array $params
492 * @param bool $framed
493 * @param string $manualthumb
496 public static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt = '',
497 $align = 'right', $params = [], $framed = false, $manualthumb = ""
505 $frameParams['framed'] = true;
507 if ( $manualthumb ) {
508 $frameParams['manualthumb'] = $manualthumb;
510 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
514 * @param Title $title
516 * @param array $frameParams
517 * @param array $handlerParams
519 * @param string $query
522 public static function makeThumbLink2( Title
$title, $file, $frameParams = [],
523 $handlerParams = [], $time = false, $query = ""
525 $exists = $file && $file->exists();
527 $page = $handlerParams['page'] ??
false;
528 if ( !isset( $frameParams['align'] ) ) {
529 $frameParams['align'] = 'right';
531 if ( !isset( $frameParams['alt'] ) ) {
532 $frameParams['alt'] = '';
534 if ( !isset( $frameParams['title'] ) ) {
535 $frameParams['title'] = '';
537 if ( !isset( $frameParams['caption'] ) ) {
538 $frameParams['caption'] = '';
541 if ( empty( $handlerParams['width'] ) ) {
542 // Reduce width for upright images when parameter 'upright' is used
543 $handlerParams['width'] = isset( $frameParams['upright'] ) ?
130 : 180;
547 $manualthumb = false;
550 $outerWidth = $handlerParams['width'] +
2;
552 if ( isset( $frameParams['manualthumb'] ) ) {
553 # Use manually specified thumbnail
554 $manual_title = Title
::makeTitleSafe( NS_FILE
, $frameParams['manualthumb'] );
555 if ( $manual_title ) {
556 $manual_img = wfFindFile( $manual_title );
558 $thumb = $manual_img->getUnscaledThumb( $handlerParams );
564 } elseif ( isset( $frameParams['framed'] ) ) {
565 // Use image dimensions, don't scale
566 $thumb = $file->getUnscaledThumb( $handlerParams );
569 # Do not present an image bigger than the source, for bitmap-style images
570 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
571 $srcWidth = $file->getWidth( $page );
572 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
573 $handlerParams['width'] = $srcWidth;
575 $thumb = $file->transform( $handlerParams );
579 $outerWidth = $thumb->getWidth() +
2;
581 $outerWidth = $handlerParams['width'] +
2;
585 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
586 # So we don't need to pass it here in $query. However, the URL for the
587 # zoom icon still needs it, so we make a unique query for it. See T16771
588 $url = $title->getLocalURL( $query );
590 $url = wfAppendQuery( $url, [ 'page' => $page ] );
593 && !isset( $frameParams['link-title'] )
594 && !isset( $frameParams['link-url'] )
595 && !isset( $frameParams['no-link'] ) ) {
596 $frameParams['link-url'] = $url;
599 $s = "<div class=\"thumb t{$frameParams['align']}\">"
600 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
603 $s .= self
::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
605 } elseif ( !$thumb ) {
606 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
609 if ( !$noscale && !$manualthumb ) {
610 self
::processResponsiveImages( $file, $thumb, $handlerParams );
613 'alt' => $frameParams['alt'],
614 'title' => $frameParams['title'],
615 'img-class' => ( isset( $frameParams['class'] ) && $frameParams['class'] !== ''
616 ?
$frameParams['class'] . ' '
617 : '' ) . 'thumbimage'
619 $params = self
::getImageLinkMTOParams( $frameParams, $query ) +
$params;
620 $s .= $thumb->toHtml( $params );
621 if ( isset( $frameParams['framed'] ) ) {
624 $zoomIcon = Html
::rawElement( 'div', [ 'class' => 'magnify' ],
625 Html
::rawElement( 'a', [
627 'class' => 'internal',
628 'title' => wfMessage( 'thumbnail-more' )->text() ],
632 $s .= ' <div class="thumbcaption">' . $zoomIcon . $frameParams['caption'] . "</div></div></div>";
633 return str_replace( "\n", ' ', $s );
637 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
641 * @param MediaTransformOutput $thumb
642 * @param array $hp Image parameters
644 public static function processResponsiveImages( $file, $thumb, $hp ) {
645 global $wgResponsiveImages;
646 if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
648 $hp15['width'] = round( $hp['width'] * 1.5 );
650 $hp20['width'] = $hp['width'] * 2;
651 if ( isset( $hp['height'] ) ) {
652 $hp15['height'] = round( $hp['height'] * 1.5 );
653 $hp20['height'] = $hp['height'] * 2;
656 $thumb15 = $file->transform( $hp15 );
657 $thumb20 = $file->transform( $hp20 );
658 if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
659 $thumb->responsiveUrls
['1.5'] = $thumb15->getUrl();
661 if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
662 $thumb->responsiveUrls
['2'] = $thumb20->getUrl();
668 * Make a "broken" link to an image
671 * @param Title $title
672 * @param string $label Link label (plain text)
673 * @param string $query Query string
674 * @param string $unused1 Unused parameter kept for b/c
675 * @param string $unused2 Unused parameter kept for b/c
676 * @param bool $time A file of a certain timestamp was requested
679 public static function makeBrokenImageLinkObj( $title, $label = '',
680 $query = '', $unused1 = '', $unused2 = '', $time = false
682 if ( !$title instanceof Title
) {
683 wfWarn( __METHOD__
. ': Requires $title to be a Title object.' );
684 return "<!-- ERROR -->" . htmlspecialchars( $label );
687 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
688 if ( $label == '' ) {
689 $label = $title->getPrefixedText();
691 $encLabel = htmlspecialchars( $label );
692 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
694 if ( ( $wgUploadMissingFileUrl ||
$wgUploadNavigationUrl ||
$wgEnableUploads )
697 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
700 // We already know it's a redirect, so mark it
705 [ 'class' => 'mw-redirect' ],
706 wfCgiToArray( $query ),
707 [ 'known', 'noclasses' ]
711 $href = self
::getUploadUrl( $title, $query );
713 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
714 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
718 return self
::link( $title, $encLabel, [], wfCgiToArray( $query ), [ 'known', 'noclasses' ] );
722 * Get the URL to upload a certain file
725 * @param Title $destFile Title object of the file to upload
726 * @param string $query Urlencoded query string to prepend
727 * @return string Urlencoded URL
729 protected static function getUploadUrl( $destFile, $query = '' ) {
730 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
731 $q = 'wpDestFile=' . $destFile->getPartialURL();
732 if ( $query != '' ) {
736 if ( $wgUploadMissingFileUrl ) {
737 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
740 if ( $wgUploadNavigationUrl ) {
741 return wfAppendQuery( $wgUploadNavigationUrl, $q );
744 $upload = SpecialPage
::getTitleFor( 'Upload' );
746 return $upload->getLocalURL( $q );
750 * Create a direct link to a given uploaded file.
753 * @param Title $title
754 * @param string $html Pre-sanitized HTML
755 * @param string $time MW timestamp of file creation time
756 * @return string HTML
758 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
759 $img = wfFindFile( $title, [ 'time' => $time ] );
760 return self
::makeMediaLinkFile( $title, $img, $html );
764 * Create a direct link to a given uploaded file.
765 * This will make a broken link if $file is false.
768 * @param Title $title
769 * @param File|bool $file File object or false
770 * @param string $html Pre-sanitized HTML
771 * @return string HTML
773 * @todo Handle invalid or missing images better.
775 public static function makeMediaLinkFile( Title
$title, $file, $html = '' ) {
776 if ( $file && $file->exists() ) {
777 $url = $file->getUrl();
780 $url = self
::getUploadUrl( $title );
784 $alt = $title->getText();
796 if ( !Hooks
::run( 'LinkerMakeMediaLinkFile',
797 [ $title, $file, &$html, &$attribs, &$ret ] ) ) {
798 wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
799 . "with url {$url} and text {$html} to {$ret}\n", true );
803 return Html
::rawElement( 'a', $attribs, $html );
807 * Make a link to a special page given its name and, optionally,
808 * a message key from the link text.
809 * Usage example: Linker::specialLink( 'Recentchanges' )
812 * @param string $name
816 public static function specialLink( $name, $key = '' ) {
818 $key = strtolower( $name );
821 return self
::linkKnown( SpecialPage
::getTitleFor( $name ), wfMessage( $key )->escaped() );
825 * Make an external link
827 * @since 1.16.3. $title added in 1.21
828 * @param string $url URL to link to
829 * @param-taint $url escapes_html
830 * @param string $text Text of link
831 * @param-taint $text escapes_html
832 * @param bool $escape Do we escape the link text?
833 * @param-taint $escape none
834 * @param string $linktype Type of external link. Gets added to the classes
835 * @param-taint $linktype escapes_html
836 * @param array $attribs Array of extra attributes to <a>
837 * @param-taint $attribs escapes_html
838 * @param Title|null $title Title object used for title specific link attributes
839 * @param-taint $title none
842 public static function makeExternalLink( $url, $text, $escape = true,
843 $linktype = '', $attribs = [], $title = null
848 $class .= " $linktype";
850 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
851 $class .= " {$attribs['class']}";
853 $attribs['class'] = $class;
856 $text = htmlspecialchars( $text );
862 $newRel = Parser
::getExternalLinkRel( $url, $title );
863 if ( !isset( $attribs['rel'] ) ||
$attribs['rel'] === '' ) {
864 $attribs['rel'] = $newRel;
865 } elseif ( $newRel !== '' ) {
866 // Merge the rel attributes.
867 $newRels = explode( ' ', $newRel );
868 $oldRels = explode( ' ', $attribs['rel'] );
869 $combined = array_unique( array_merge( $newRels, $oldRels ) );
870 $attribs['rel'] = implode( ' ', $combined );
873 $success = Hooks
::run( 'LinkerMakeExternalLink',
874 [ &$url, &$text, &$link, &$attribs, $linktype ] );
876 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
877 . "with url {$url} and text {$text} to {$link}\n", true );
880 $attribs['href'] = $url;
881 return Html
::rawElement( 'a', $attribs, $text );
885 * Make user link (or user contributions for unregistered users)
886 * @param int $userId User id in database.
887 * @param string $userName User name in database.
888 * @param string $altUserName Text to display instead of the user name (optional)
889 * @return string HTML fragment
890 * @since 1.16.3. $altUserName was added in 1.19.
892 public static function userLink( $userId, $userName, $altUserName = false ) {
893 $classes = 'mw-userlink';
895 if ( $userId == 0 ) {
896 $page = ExternalUserNames
::getUserLinkTitle( $userName );
898 if ( ExternalUserNames
::isExternal( $userName ) ) {
899 $classes .= ' mw-extuserlink';
900 } elseif ( $altUserName === false ) {
901 $altUserName = IP
::prettifyIP( $userName );
903 $classes .= ' mw-anonuserlink'; // Separate link class for anons (T45179)
905 $page = Title
::makeTitle( NS_USER
, $userName );
908 // Wrap the output with <bdi> tags for directionality isolation
910 '<bdi>' . htmlspecialchars( $altUserName !== false ?
$altUserName : $userName ) . '</bdi>';
913 ? self
::link( $page, $linkText, [ 'class' => $classes ] )
914 : Html
::rawElement( 'span', [ 'class' => $classes ], $linkText );
918 * Generate standard user tool links (talk, contributions, block link, etc.)
921 * @param int $userId User identifier
922 * @param string $userText User name or IP address
923 * @param bool $redContribsWhenNoEdits Should the contributions link be
924 * red if the user has no edits?
925 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
926 * and Linker::TOOL_LINKS_EMAIL).
927 * @param int|null $edits User edit count (optional, for performance)
928 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
929 * @return string HTML fragment
931 public static function userToolLinks(
932 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null,
933 $useParentheses = true
935 global $wgUser, $wgDisableAnonTalk, $wgLang;
936 $talkable = !( $wgDisableAnonTalk && $userId == 0 );
937 $blockable = !( $flags & self
::TOOL_LINKS_NOBLOCK
);
938 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
&& $userId;
940 if ( $userId == 0 && ExternalUserNames
::isExternal( $userText ) ) {
941 // No tools for an external user
947 $items[] = self
::userTalkLink( $userId, $userText );
950 // check if the user has an edit
952 $attribs['class'] = 'mw-usertoollinks-contribs';
953 if ( $redContribsWhenNoEdits ) {
954 if ( intval( $edits ) === 0 && $edits !== 0 ) {
955 $user = User
::newFromId( $userId );
956 $edits = $user->getEditCount();
958 if ( $edits === 0 ) {
959 $attribs['class'] .= ' new';
962 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
964 $items[] = self
::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
966 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
967 $items[] = self
::blockLink( $userId, $userText );
970 if ( $addEmailLink && $wgUser->canSendEmail() ) {
971 $items[] = self
::emailLink( $userId, $userText );
974 Hooks
::run( 'UserToolLinksEdit', [ $userId, $userText, &$items ] );
980 if ( $useParentheses ) {
981 return wfMessage( 'word-separator' )->escaped()
982 . '<span class="mw-usertoollinks">'
983 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
988 foreach ( $items as $tool ) {
989 $tools[] = Html
::rawElement( 'span', [], $tool );
991 return ' <span class="mw-usertoollinks mw-changeslist-links">' .
992 implode( ' ', $tools ) . '</span>';
996 * Alias for userToolLinks( $userId, $userText, true );
998 * @param int $userId User identifier
999 * @param string $userText User name or IP address
1000 * @param int|null $edits User edit count (optional, for performance)
1003 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1004 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
1009 * @param int $userId User id in database.
1010 * @param string $userText User name in database.
1011 * @return string HTML fragment with user talk link
1013 public static function userTalkLink( $userId, $userText ) {
1014 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
1015 $moreLinkAttribs['class'] = 'mw-usertoollinks-talk';
1017 return self
::link( $userTalkPage,
1018 wfMessage( 'talkpagelinktext' )->escaped(),
1025 * @param int $userId
1026 * @param string $userText User name in database.
1027 * @return string HTML fragment with block link
1029 public static function blockLink( $userId, $userText ) {
1030 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1031 $moreLinkAttribs['class'] = 'mw-usertoollinks-block';
1033 return self
::link( $blockPage,
1034 wfMessage( 'blocklink' )->escaped(),
1040 * @param int $userId
1041 * @param string $userText User name in database.
1042 * @return string HTML fragment with e-mail user link
1044 public static function emailLink( $userId, $userText ) {
1045 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1046 $moreLinkAttribs['class'] = 'mw-usertoollinks-mail';
1047 return self
::link( $emailPage,
1048 wfMessage( 'emaillink' )->escaped(),
1054 * Generate a user link if the current user is allowed to view it
1056 * @param Revision $rev
1057 * @param bool $isPublic Show only if all users can see it
1058 * @return string HTML fragment
1060 public static function revUserLink( $rev, $isPublic = false ) {
1061 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1062 $link = wfMessage( 'rev-deleted-user' )->escaped();
1063 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1064 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1065 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1067 $link = wfMessage( 'rev-deleted-user' )->escaped();
1069 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1070 return '<span class="history-deleted">' . $link . '</span>';
1076 * Generate a user tool link cluster if the current user is allowed to view it
1078 * @param Revision $rev
1079 * @param bool $isPublic Show only if all users can see it
1080 * @return string HTML
1082 public static function revUserTools( $rev, $isPublic = false ) {
1083 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1084 $link = wfMessage( 'rev-deleted-user' )->escaped();
1085 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1086 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1087 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1088 $link = self
::userLink( $userId, $userText )
1089 . self
::userToolLinks( $userId, $userText );
1091 $link = wfMessage( 'rev-deleted-user' )->escaped();
1093 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1094 return ' <span class="history-deleted">' . $link . '</span>';
1100 * This function is called by all recent changes variants, by the page history,
1101 * and by the user contributions list. It is responsible for formatting edit
1102 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1103 * auto-generated comments (from section editing) and formats [[wikilinks]].
1105 * @author Erik Moeller <moeller@scireview.de>
1106 * @since 1.16.3. $wikiId added in 1.26
1108 * @param string $comment
1109 * @param Title|null $title Title object (to generate link to the section in autocomment)
1111 * @param bool $local Whether section links should refer to local page
1112 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1113 * For use with external changes.
1115 * @return string HTML
1117 public static function formatComment(
1118 $comment, $title = null, $local = false, $wikiId = null
1120 # Sanitize text a bit:
1121 $comment = str_replace( "\n", " ", $comment );
1122 # Allow HTML entities (for T15815)
1123 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1125 # Render autocomments and make links:
1126 $comment = self
::formatAutocomments( $comment, $title, $local, $wikiId );
1127 return self
::formatLinksInComment( $comment, $title, $local, $wikiId );
1131 * Converts autogenerated comments in edit summaries into section links.
1133 * The pattern for autogen comments is / * foo * /, which makes for
1135 * We look for all comments, match any text before and after the comment,
1136 * add a separator where needed and format the comment itself with CSS
1137 * Called by Linker::formatComment.
1139 * @param string $comment Comment text
1140 * @param Title|null $title An optional title object used to links to sections
1141 * @param bool $local Whether section links should refer to local page
1142 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1143 * as used by WikiMap.
1145 * @return string Formatted comment (wikitext)
1147 private static function formatAutocomments(
1148 $comment, $title = null, $local = false, $wikiId = null
1150 // @todo $append here is something of a hack to preserve the status
1151 // quo. Someone who knows more about bidi and such should decide
1152 // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1153 // wiki, both when autocomments exist and when they don't, and
1154 // (2) what markup will make that actually happen.
1156 $comment = preg_replace_callback(
1157 // To detect the presence of content before or after the
1158 // auto-comment, we use capturing groups inside optional zero-width
1159 // assertions. But older versions of PCRE can't directly make
1160 // zero-width assertions optional, so wrap them in a non-capturing
1162 '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1163 function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1166 // Ensure all match positions are defined
1167 $match +
= [ '', '', '', '' ];
1169 $pre = $match[1] !== '';
1171 $post = $match[3] !== '';
1175 'FormatAutocomments',
1176 [ &$comment, $pre, $auto, $post, $title, $local, $wikiId ]
1179 if ( $comment === null ) {
1182 # Remove links that a user may have manually put in the autosummary
1183 # This could be improved by copying as much of Parser::stripSectionName as desired.
1184 $section = str_replace( [
1190 // We don't want any links in the auto text to be linked, but we still
1191 // want to show any [[ ]]
1192 $sectionText = str_replace( '[[', '[[', $auto );
1194 $section = substr( Parser
::guessSectionNameFromStrippedText( $section ), 1 );
1196 $sectionTitle = Title
::makeTitleSafe( NS_MAIN
, '', $section );
1198 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1199 $title->getDBkey(), $section );
1201 if ( $sectionTitle ) {
1202 $auto = Linker
::makeCommentLink(
1203 $sectionTitle, $wgLang->getArrow() . $wgLang->getDirMark() . $sectionText,
1204 $wikiId, 'noclasses'
1209 # written summary $presep autocomment (summary /* section */)
1210 $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1213 # autocomment $postsep written summary (/* section */ summary)
1214 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1217 $auto = '<span dir="auto"><span class="autocomment">' . $auto . '</span>';
1218 $append .= '</span>';
1220 $comment = $pre . $auto;
1226 return $comment . $append;
1230 * Formats wiki links and media links in text; all other wiki formatting
1233 * @since 1.16.3. $wikiId added in 1.26
1234 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1236 * @param string $comment Text to format links in. WARNING! Since the output of this
1237 * function is html, $comment must be sanitized for use as html. You probably want
1238 * to pass $comment through Sanitizer::escapeHtmlAllowEntities() before calling
1240 * @param Title|null $title An optional title object used to links to sections
1241 * @param bool $local Whether section links should refer to local page
1242 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1243 * as used by WikiMap.
1245 * @return string HTML
1246 * @return-taint onlysafefor_html
1248 public static function formatLinksInComment(
1249 $comment, $title = null, $local = false, $wikiId = null
1251 return preg_replace_callback(
1254 \s*+ # ignore leading whitespace, the *+ quantifier disallows backtracking
1255 :? # ignore optional leading colon
1256 ([^\]|]+) # 1. link target; page names cannot include ] or |
1259 # Stop matching at ]] without relying on backtracking.
1263 ([^[]*) # 3. link trail (the text up until the next link)
1265 function ( $match ) use ( $title, $local, $wikiId ) {
1266 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1267 $medians .= preg_quote(
1268 MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( NS_MEDIA
),
1272 $comment = $match[0];
1274 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1275 if ( strpos( $match[1], '%' ) !== false ) {
1277 rawurldecode( $match[1] ),
1278 [ '<' => '<', '>' => '>' ]
1282 # Handle link renaming [[foo|text]] will show link as "text"
1283 if ( $match[2] != "" ) {
1290 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1291 # Media link; trail not supported.
1292 $linkRegexp = '/\[\[(.*?)\]\]/';
1293 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1295 $thelink = Linker
::makeMediaLinkObj( $title, $text );
1298 # Other kind of link
1299 # Make sure its target is non-empty
1300 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1301 $match[1] = substr( $match[1], 1 );
1303 if ( $match[1] !== false && $match[1] !== '' ) {
1305 MediaWikiServices
::getInstance()->getContentLanguage()->linkTrail(),
1309 $trail = $submatch[1];
1313 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1314 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1317 $linkTarget = Linker
::normalizeSubpageLink( $title, $match[1], $linkText );
1319 $target = Title
::newFromText( $linkTarget );
1321 if ( $target->getText() == '' && !$target->isExternal()
1322 && !$local && $title
1324 $target = $title->createFragmentTarget( $target->getFragment() );
1327 $thelink = Linker
::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1332 // If the link is still valid, go ahead and replace it in!
1333 $comment = preg_replace(
1335 StringUtils
::escapeRegexReplacement( $thelink ),
1348 * Generates a link to the given Title
1350 * @note This is only public for technical reasons. It's not intended for use outside Linker.
1352 * @param LinkTarget $linkTarget
1353 * @param string $text
1354 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1355 * as used by WikiMap.
1356 * @param string|string[] $options See the $options parameter in Linker::link.
1358 * @return string HTML link
1360 public static function makeCommentLink(
1361 LinkTarget
$linkTarget, $text, $wikiId = null, $options = []
1363 if ( $wikiId !== null && !$linkTarget->isExternal() ) {
1364 $link = self
::makeExternalLink(
1365 WikiMap
::getForeignURL(
1367 $linkTarget->getNamespace() === 0
1368 ?
$linkTarget->getDBkey()
1369 : MWNamespace
::getCanonicalName( $linkTarget->getNamespace() ) . ':'
1370 . $linkTarget->getDBkey(),
1371 $linkTarget->getFragment()
1374 /* escape = */ false // Already escaped
1377 $link = self
::link( $linkTarget, $text, [], [], $options );
1384 * @param Title $contextTitle
1385 * @param string $target
1386 * @param string &$text
1389 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1392 # :Foobar -- override special treatment of prefix (images, language links)
1393 # /Foobar -- convert to CurrentPage/Foobar
1394 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1395 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1396 # ../Foobar -- convert to CurrentPage/Foobar,
1397 # (from CurrentPage/CurrentSubPage)
1398 # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1399 # (from CurrentPage/CurrentSubPage)
1401 $ret = $target; # default return value is no change
1403 # Some namespaces don't allow subpages,
1404 # so only perform processing if subpages are allowed
1405 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1406 $hash = strpos( $target, '#' );
1407 if ( $hash !== false ) {
1408 $suffix = substr( $target, $hash );
1409 $target = substr( $target, 0, $hash );
1414 $target = trim( $target );
1415 # Look at the first character
1416 if ( $target != '' && $target[0] === '/' ) {
1417 # / at end means we don't want the slash to be shown
1419 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1420 if ( $trailingSlashes ) {
1421 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1423 $noslash = substr( $target, 1 );
1426 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1427 if ( $text === '' ) {
1428 $text = $target . $suffix;
1429 } # this might be changed for ugliness reasons
1431 # check for .. subpage backlinks
1433 $nodotdot = $target;
1434 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1436 $nodotdot = substr( $nodotdot, 3 );
1438 if ( $dotdotcount > 0 ) {
1439 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1440 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1441 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1442 # / at the end means don't show full path
1443 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1444 $nodotdot = rtrim( $nodotdot, '/' );
1445 if ( $text === '' ) {
1446 $text = $nodotdot . $suffix;
1449 $nodotdot = trim( $nodotdot );
1450 if ( $nodotdot != '' ) {
1451 $ret .= '/' . $nodotdot;
1463 * Wrap a comment in standard punctuation and formatting if
1464 * it's non-empty, otherwise return empty string.
1466 * @since 1.16.3. $wikiId added in 1.26
1467 * @param string $comment
1468 * @param Title|null $title Title object (to generate link to section in autocomment) or null
1469 * @param bool $local Whether section links should refer to local page
1470 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1471 * For use with external changes.
1475 public static function commentBlock(
1476 $comment, $title = null, $local = false, $wikiId = null, $useParentheses = true
1478 // '*' used to be the comment inserted by the software way back
1479 // in antiquity in case none was provided, here for backwards
1480 // compatibility, acc. to brion -ævar
1481 if ( $comment == '' ||
$comment == '*' ) {
1484 $formatted = self
::formatComment( $comment, $title, $local, $wikiId );
1485 if ( $useParentheses ) {
1486 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1487 $classNames = 'comment';
1489 $classNames = 'comment comment--without-parentheses';
1491 return " <span class=\"$classNames\">$formatted</span>";
1495 * Wrap and format the given revision's comment block, if the current
1496 * user is allowed to view it.
1499 * @param Revision $rev
1500 * @param bool $local Whether section links should refer to local page
1501 * @param bool $isPublic Show only if all users can see it
1502 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
1503 * @return string HTML fragment
1505 public static function revComment( Revision
$rev, $local = false, $isPublic = false,
1506 $useParentheses = true
1508 if ( $rev->getComment( Revision
::RAW
) == "" ) {
1511 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1512 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1513 } elseif ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1514 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1515 $rev->getTitle(), $local, null, $useParentheses );
1517 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1519 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1520 return " <span class=\"history-deleted\">$block</span>";
1530 public static function formatRevisionSize( $size ) {
1532 $stxt = wfMessage( 'historyempty' )->escaped();
1534 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1535 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1537 return "<span class=\"history-size\">$stxt</span>";
1541 * Add another level to the Table of Contents
1546 public static function tocIndent() {
1551 * Finish one or more sublevels on the Table of Contents
1557 public static function tocUnindent( $level ) {
1558 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1562 * parameter level defines if we are on an indentation level
1565 * @param string $anchor
1566 * @param string $tocline
1567 * @param string $tocnumber
1568 * @param string $level
1569 * @param string|bool $sectionIndex
1572 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1573 $classes = "toclevel-$level";
1574 if ( $sectionIndex !== false ) {
1575 $classes .= " tocsection-$sectionIndex";
1578 // <li class="$classes"><a href="#$anchor"><span class="tocnumber">
1579 // $tocnumber</span> <span class="toctext">$tocline</span></a>
1580 return Html
::openElement( 'li', [ 'class' => $classes ] )
1581 . Html
::rawElement( 'a',
1582 [ 'href' => "#$anchor" ],
1583 Html
::element( 'span', [ 'class' => 'tocnumber' ], $tocnumber )
1585 . Html
::rawElement( 'span', [ 'class' => 'toctext' ], $tocline )
1590 * End a Table Of Contents line.
1591 * tocUnindent() will be used instead if we're ending a line below
1596 public static function tocLineEnd() {
1601 * Wraps the TOC in a table and provides the hide/collapse javascript.
1604 * @param string $toc Html of the Table Of Contents
1605 * @param string|Language|bool|null $lang Language for the toc title, defaults to user language.
1606 * The types string and bool are deprecated.
1607 * @return string Full html of the TOC
1609 public static function tocList( $toc, $lang = null ) {
1611 $lang = $lang ??
$wgLang;
1612 if ( !is_object( $lang ) ) {
1613 wfDeprecated( __METHOD__
. ' with type other than Language for $lang', '1.33' );
1614 $lang = wfGetLangObj( $lang );
1617 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1619 return '<div id="toc" class="toc">'
1620 . Html
::element( 'input', [
1621 'type' => 'checkbox',
1623 'id' => 'toctogglecheckbox',
1624 'class' => 'toctogglecheckbox',
1625 'style' => 'display:none',
1627 . Html
::openElement( 'div', [
1628 'class' => 'toctitle',
1629 'lang' => $lang->getHtmlCode(),
1630 'dir' => $lang->getDir(),
1633 . '<span class="toctogglespan">'
1634 . Html
::label( '', 'toctogglecheckbox', [
1635 'class' => 'toctogglelabel',
1640 . "</ul>\n</div>\n";
1644 * Generate a table of contents from a section tree.
1646 * @since 1.16.3. $lang added in 1.17
1647 * @param array $tree Return value of ParserOutput::getSections()
1648 * @param string|Language|bool|null $lang Language for the toc title, defaults to user language.
1649 * The types string and bool are deprecated.
1650 * @return string HTML fragment
1652 public static function generateTOC( $tree, $lang = null ) {
1655 foreach ( $tree as $section ) {
1656 if ( $section['toclevel'] > $lastLevel ) {
1657 $toc .= self
::tocIndent();
1658 } elseif ( $section['toclevel'] < $lastLevel ) {
1659 $toc .= self
::tocUnindent(
1660 $lastLevel - $section['toclevel'] );
1662 $toc .= self
::tocLineEnd();
1665 $toc .= self
::tocLine( $section['anchor'],
1666 $section['line'], $section['number'],
1667 $section['toclevel'], $section['index'] );
1668 $lastLevel = $section['toclevel'];
1670 $toc .= self
::tocLineEnd();
1671 return self
::tocList( $toc, $lang );
1675 * Create a headline for content
1678 * @param int $level The level of the headline (1-6)
1679 * @param string $attribs Any attributes for the headline, starting with
1680 * a space and ending with '>'
1681 * This *must* be at least '>' for no attribs
1682 * @param string $anchor The anchor to give the headline (the bit after the #)
1683 * @param string $html HTML for the text of the header
1684 * @param string $link HTML to add for the section edit link
1685 * @param string|bool $fallbackAnchor A second, optional anchor to give for
1686 * backward compatibility (false to omit)
1688 * @return string HTML headline
1690 public static function makeHeadline( $level, $attribs, $anchor, $html,
1691 $link, $fallbackAnchor = false
1693 $anchorEscaped = htmlspecialchars( $anchor );
1695 if ( $fallbackAnchor !== false && $fallbackAnchor !== $anchor ) {
1696 $fallbackAnchor = htmlspecialchars( $fallbackAnchor );
1697 $fallback = "<span id=\"$fallbackAnchor\"></span>";
1699 return "<h$level$attribs"
1700 . "$fallback<span class=\"mw-headline\" id=\"$anchorEscaped\">$html</span>"
1706 * Split a link trail, return the "inside" portion and the remainder of the trail
1707 * as a two-element array
1708 * @param string $trail
1711 static function splitTrail( $trail ) {
1712 $regex = MediaWikiServices
::getInstance()->getContentLanguage()->linkTrail();
1714 if ( $trail !== '' ) {
1716 if ( preg_match( $regex, $trail, $m ) ) {
1721 return [ $inside, $trail ];
1725 * Generate a rollback link for a given revision. Currently it's the
1726 * caller's responsibility to ensure that the revision is the top one. If
1727 * it's not, of course, the user will get an error message.
1729 * If the calling page is called with the parameter &bot=1, all rollback
1730 * links also get that parameter. It causes the edit itself and the rollback
1731 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1732 * changes, so this allows sysops to combat a busy vandal without bothering
1735 * If the option verify is set this function will return the link only in case the
1736 * revision can be reverted. Please note that due to performance limitations
1737 * it might be assumed that a user isn't the only contributor of a page while
1738 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1739 * work if $wgShowRollbackEditCount is disabled, so this can only function
1740 * as an additional check.
1742 * If the option noBrackets is set the rollback link wont be enclosed in "[]".
1744 * @since 1.16.3. $context added in 1.20. $options added in 1.21
1746 * @param Revision $rev
1747 * @param IContextSource|null $context Context to use or null for the main context.
1748 * @param array $options
1751 public static function generateRollback( $rev, IContextSource
$context = null,
1752 $options = [ 'verify' ]
1754 if ( $context === null ) {
1755 $context = RequestContext
::getMain();
1759 if ( in_array( 'verify', $options, true ) ) {
1760 $editCount = self
::getRollbackEditCount( $rev, true );
1761 if ( $editCount === false ) {
1766 $inner = self
::buildRollbackLink( $rev, $context, $editCount );
1768 if ( !in_array( 'noBrackets', $options, true ) ) {
1769 $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1772 return '<span class="mw-rollback-link">' . $inner . '</span>';
1776 * This function will return the number of revisions which a rollback
1777 * would revert and, if $verify is set it will verify that a revision
1778 * can be reverted (that the user isn't the only contributor and the
1779 * revision we might rollback to isn't deleted). These checks can only
1780 * function as an additional check as this function only checks against
1781 * the last $wgShowRollbackEditCount edits.
1783 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1784 * is set and the user is the only contributor of the page.
1786 * @param Revision $rev
1787 * @param bool $verify Try to verify that this revision can really be rolled back
1788 * @return int|bool|null
1790 public static function getRollbackEditCount( $rev, $verify ) {
1791 global $wgShowRollbackEditCount;
1792 if ( !is_int( $wgShowRollbackEditCount ) ||
!$wgShowRollbackEditCount > 0 ) {
1793 // Nothing has happened, indicate this by returning 'null'
1797 $dbr = wfGetDB( DB_REPLICA
);
1799 // Up to the value of $wgShowRollbackEditCount revisions are counted
1800 $revQuery = Revision
::getQueryInfo();
1801 $res = $dbr->select(
1802 $revQuery['tables'],
1803 [ 'rev_user_text' => $revQuery['fields']['rev_user_text'], 'rev_deleted' ],
1804 // $rev->getPage() returns null sometimes
1805 [ 'rev_page' => $rev->getTitle()->getArticleID() ],
1808 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
1809 'ORDER BY' => 'rev_timestamp DESC',
1810 'LIMIT' => $wgShowRollbackEditCount +
1
1817 foreach ( $res as $row ) {
1818 if ( $rev->getUserText( Revision
::RAW
) != $row->rev_user_text
) {
1820 ( $row->rev_deleted
& Revision
::DELETED_TEXT
1821 ||
$row->rev_deleted
& Revision
::DELETED_USER
1823 // If the user or the text of the revision we might rollback
1824 // to is deleted in some way we can't rollback. Similar to
1825 // the sanity checks in WikiPage::commitRollback.
1834 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1835 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1836 // and there weren't any other revisions. That means that the current user is the only
1837 // editor, so we can't rollback
1844 * Build a raw rollback link, useful for collections of "tool" links
1846 * @since 1.16.3. $context added in 1.20. $editCount added in 1.21
1847 * @param Revision $rev
1848 * @param IContextSource|null $context Context to use or null for the main context.
1849 * @param int $editCount Number of edits that would be reverted
1850 * @return string HTML fragment
1852 public static function buildRollbackLink( $rev, IContextSource
$context = null,
1855 global $wgShowRollbackEditCount, $wgMiserMode;
1857 // To config which pages are affected by miser mode
1858 $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
1860 if ( $context === null ) {
1861 $context = RequestContext
::getMain();
1864 $title = $rev->getTitle();
1866 'action' => 'rollback',
1867 'from' => $rev->getUserText(),
1868 'token' => $context->getUser()->getEditToken( 'rollback' ),
1871 'data-mw' => 'interface',
1872 'title' => $context->msg( 'tooltip-rollback' )->text(),
1874 $options = [ 'known', 'noclasses' ];
1876 if ( $context->getRequest()->getBool( 'bot' ) ) {
1877 $query['bot'] = '1';
1878 $query['hidediff'] = '1'; // T17999
1881 $disableRollbackEditCount = false;
1882 if ( $wgMiserMode ) {
1883 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1884 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1885 $disableRollbackEditCount = true;
1891 if ( !$disableRollbackEditCount
1892 && is_int( $wgShowRollbackEditCount )
1893 && $wgShowRollbackEditCount > 0
1895 if ( !is_numeric( $editCount ) ) {
1896 $editCount = self
::getRollbackEditCount( $rev, false );
1899 if ( $editCount > $wgShowRollbackEditCount ) {
1900 $html = $context->msg( 'rollbacklinkcount-morethan' )
1901 ->numParams( $wgShowRollbackEditCount )->parse();
1903 $html = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1906 return self
::link( $title, $html, $attrs, $query, $options );
1909 $html = $context->msg( 'rollbacklink' )->escaped();
1910 return self
::link( $title, $html, $attrs, $query, $options );
1914 * Returns HTML for the "hidden categories on this page" list.
1917 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1919 * @return string HTML output
1921 public static function formatHiddenCategories( $hiddencats ) {
1923 if ( count( $hiddencats ) > 0 ) {
1924 # Construct the HTML
1925 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1926 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
1927 $outText .= "</div><ul>\n";
1929 foreach ( $hiddencats as $titleObj ) {
1930 # If it's hidden, it must exist - no need to check with a LinkBatch
1932 . self
::link( $titleObj, null, [], [], 'known' )
1935 $outText .= '</ul>';
1941 * Given the id of an interface element, constructs the appropriate title
1942 * attribute from the system messages. (Note, this is usually the id but
1943 * isn't always, because sometimes the accesskey needs to go on a different
1944 * element than the id, for reverse-compatibility, etc.)
1946 * @since 1.16.3 $msgParams added in 1.27
1947 * @param string $name Id of the element, minus prefixes.
1948 * @param string|array|null $options Null, string or array with some of the following options:
1949 * - 'withaccess' to add an access-key hint
1950 * - 'nonexisting' to add an accessibility hint that page does not exist
1951 * @param array $msgParams Parameters to pass to the message
1953 * @return string Contents of the title attribute (which you must HTML-
1954 * escape), or false for no title attribute
1956 public static function titleAttrib( $name, $options = null, array $msgParams = [] ) {
1957 $message = wfMessage( "tooltip-$name", $msgParams );
1958 if ( !$message->exists() ) {
1961 $tooltip = $message->text();
1962 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1963 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1964 # Message equal to '-' means suppress it.
1965 if ( $tooltip == '-' ) {
1970 $options = (array)$options;
1972 if ( in_array( 'nonexisting', $options ) ) {
1973 $tooltip = wfMessage( 'red-link-title', $tooltip ?
: '' )->text();
1975 if ( in_array( 'withaccess', $options ) ) {
1976 $accesskey = self
::accesskey( $name );
1977 if ( $accesskey !== false ) {
1978 // Should be build the same as in jquery.accessKeyLabel.js
1979 if ( $tooltip === false ||
$tooltip === '' ) {
1980 $tooltip = wfMessage( 'brackets', $accesskey )->text();
1982 $tooltip .= wfMessage( 'word-separator' )->text();
1983 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
1991 public static $accesskeycache;
1994 * Given the id of an interface element, constructs the appropriate
1995 * accesskey attribute from the system messages. (Note, this is usually
1996 * the id but isn't always, because sometimes the accesskey needs to go on
1997 * a different element than the id, for reverse-compatibility, etc.)
2000 * @param string $name Id of the element, minus prefixes.
2001 * @return string Contents of the accesskey attribute (which you must HTML-
2002 * escape), or false for no accesskey attribute
2004 public static function accesskey( $name ) {
2005 if ( isset( self
::$accesskeycache[$name] ) ) {
2006 return self
::$accesskeycache[$name];
2009 $message = wfMessage( "accesskey-$name" );
2011 if ( !$message->exists() ) {
2014 $accesskey = $message->plain();
2015 if ( $accesskey === '' ||
$accesskey === '-' ) {
2016 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2017 # attribute, but this is broken for accesskey: that might be a useful
2023 self
::$accesskeycache[$name] = $accesskey;
2024 return self
::$accesskeycache[$name];
2028 * Get a revision-deletion link, or disabled link, or nothing, depending
2029 * on user permissions & the settings on the revision.
2031 * Will use forward-compatible revision ID in the Special:RevDelete link
2032 * if possible, otherwise the timestamp-based ID which may break after
2036 * @param Revision $rev
2037 * @param Title $title
2038 * @return string HTML fragment
2040 public static function getRevDeleteLink( User
$user, Revision
$rev, Title
$title ) {
2041 $canHide = $user->isAllowed( 'deleterevision' );
2042 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2046 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
2047 return self
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2049 if ( $rev->getId() ) {
2050 // RevDelete links using revision ID are stable across
2051 // page deletion and undeletion; use when possible.
2053 'type' => 'revision',
2054 'target' => $title->getPrefixedDBkey(),
2055 'ids' => $rev->getId()
2058 // Older deleted entries didn't save a revision ID.
2059 // We have to refer to these by timestamp, ick!
2061 'type' => 'archive',
2062 'target' => $title->getPrefixedDBkey(),
2063 'ids' => $rev->getTimestamp()
2066 return self
::revDeleteLink( $query,
2067 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
2071 * Creates a (show/hide) link for deleting revisions/log entries
2073 * @param array $query Query parameters to be passed to link()
2074 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2075 * @param bool $delete Set to true to use (show/hide) rather than (show)
2077 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2078 * span to allow for customization of appearance with CSS
2080 public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2081 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
2082 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2083 $html = wfMessage( $msgKey )->escaped();
2084 $tag = $restricted ?
'strong' : 'span';
2085 $link = self
::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2088 [ 'class' => 'mw-revdelundel-link' ],
2089 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2094 * Creates a dead (show/hide) link for deleting revisions/log entries
2097 * @param bool $delete Set to true to use (show/hide) rather than (show)
2099 * @return string HTML text wrapped in a span to allow for customization
2100 * of appearance with CSS
2102 public static function revDeleteLinkDisabled( $delete = true ) {
2103 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2104 $html = wfMessage( $msgKey )->escaped();
2105 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2106 return Xml
::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2110 * Returns the attributes for the tooltip and access key.
2112 * @since 1.16.3. $msgParams introduced in 1.27
2113 * @param string $name
2114 * @param array $msgParams Params for constructing the message
2115 * @param string|array|null $options Options to be passed to titleAttrib.
2117 * @see Linker::titleAttrib for what options could be passed to $options.
2121 public static function tooltipAndAccesskeyAttribs(
2123 array $msgParams = [],
2126 $options = (array)$options;
2127 $options[] = 'withaccess';
2130 'title' => self
::titleAttrib( $name, $options, $msgParams ),
2131 'accesskey' => self
::accesskey( $name )
2133 if ( $attribs['title'] === false ) {
2134 unset( $attribs['title'] );
2136 if ( $attribs['accesskey'] === false ) {
2137 unset( $attribs['accesskey'] );
2143 * Returns raw bits of HTML, use titleAttrib()
2145 * @param string $name
2146 * @param array|null $options
2147 * @return null|string
2149 public static function tooltip( $name, $options = null ) {
2150 $tooltip = self
::titleAttrib( $name, $options );
2151 if ( $tooltip === false ) {
2154 return Xml
::expandAttributes( [