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 * Return the CSS colour of a known link
44 * @deprecated since 1.28, use LinkRenderer::getLinkClasses() instead
47 * @param LinkTarget $t
48 * @param int $threshold User defined threshold
49 * @return string CSS class
51 public static function getLinkColour( LinkTarget
$t, $threshold ) {
52 wfDeprecated( __METHOD__
, '1.28' );
53 $services = MediaWikiServices
::getInstance();
54 $linkRenderer = $services->getLinkRenderer();
55 if ( $threshold !== $linkRenderer->getStubThreshold() ) {
56 // Need to create a new instance with the right stub threshold...
57 $linkRenderer = $services->getLinkRendererFactory()->create();
58 $linkRenderer->setStubThreshold( $threshold );
61 return $linkRenderer->getLinkClasses( $t );
65 * This function returns an HTML link to the given target. It serves a few
67 * 1) If $target is a Title, the correct URL to link to will be figured
69 * 2) It automatically adds the usual classes for various types of link
70 * targets: "new" for red links, "stub" for short articles, etc.
71 * 3) It escapes all attribute values safely so there's no risk of XSS.
72 * 4) It provides a default tooltip if the target is a Title (the page
73 * name of the target).
74 * link() replaces the old functions in the makeLink() family.
76 * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
77 * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
79 * @param Title $target Can currently only be a Title, but this may
80 * change to support Images, literal URLs, etc.
81 * @param string $html The HTML contents of the <a> element, i.e.,
82 * the link text. This is raw HTML and will not be escaped. If null,
83 * defaults to the prefixed text of the Title; or if the Title is just a
84 * fragment, the contents of the fragment.
85 * @param array $customAttribs A key => value array of extra HTML attributes,
86 * such as title and class. (href is ignored.) Classes will be
87 * merged with the default classes, while other attributes will replace
88 * default attributes. All passed attribute values will be HTML-escaped.
89 * A false attribute value means to suppress that attribute.
90 * @param array $query The query string to append to the URL
91 * you're linking to, in key => value array form. Query keys and values
92 * will be URL-encoded.
93 * @param string|array $options String or array of strings:
94 * 'known': Page is known to exist, so don't check if it does.
95 * 'broken': Page is known not to exist, so don't check if it does.
96 * 'noclasses': Don't add any classes automatically (includes "new",
97 * "stub", "mw-redirect", "extiw"). Only use the class attribute
98 * provided, if any, so you get a simple blue link with no funny i-
100 * 'forcearticlepath': Use the article path always, even with a querystring.
101 * Has compatibility issues on some setups, so avoid wherever possible.
102 * 'http': Force a full URL with http:// as the scheme.
103 * 'https': Force a full URL with https:// as the scheme.
104 * 'stubThreshold' => (int): Stub threshold to use when determining link classes.
105 * @return string HTML <a> attribute
107 public static function link(
108 $target, $html = null, $customAttribs = [], $query = [], $options = []
110 if ( !$target instanceof Title
) {
111 wfWarn( __METHOD__
. ': Requires $target to be a Title object.', 2 );
112 return "<!-- ERROR -->$html";
115 if ( is_string( $query ) ) {
116 // some functions withing core using this still hand over query strings
117 wfDeprecated( __METHOD__
. ' with parameter $query as string (should be array)', '1.20' );
118 $query = wfCgiToArray( $query );
121 $services = MediaWikiServices
::getInstance();
122 $options = (array)$options;
124 // Custom options, create new LinkRenderer
125 if ( !isset( $options['stubThreshold'] ) ) {
126 $defaultLinkRenderer = $services->getLinkRenderer();
127 $options['stubThreshold'] = $defaultLinkRenderer->getStubThreshold();
129 $linkRenderer = $services->getLinkRendererFactory()
130 ->createFromLegacyOptions( $options );
132 $linkRenderer = $services->getLinkRenderer();
135 if ( $html !== null ) {
136 $text = new HtmlArmor( $html );
138 $text = $html; // null
140 if ( in_array( 'known', $options, true ) ) {
141 return $linkRenderer->makeKnownLink( $target, $text, $customAttribs, $query );
142 } elseif ( in_array( 'broken', $options, true ) ) {
143 return $linkRenderer->makeBrokenLink( $target, $text, $customAttribs, $query );
144 } elseif ( in_array( 'noclasses', $options, true ) ) {
145 return $linkRenderer->makePreloadedLink( $target, $text, '', $customAttribs, $query );
147 return $linkRenderer->makeLink( $target, $text, $customAttribs, $query );
152 * Identical to link(), except $options defaults to 'known'.
155 * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
159 public static function linkKnown(
160 $target, $html = null, $customAttribs = [],
161 $query = [], $options = [ 'known' ]
163 return self
::link( $target, $html, $customAttribs, $query, $options );
167 * Make appropriate markup for a link to the current article. This is since
168 * MediaWiki 1.29.0 rendered as an <a> tag without an href and with a class
169 * showing the link text. The calling sequence is the same as for the other
170 * make*LinkObj static functions, but $query is not used.
174 * @param string $html [optional]
175 * @param string $query [optional]
176 * @param string $trail [optional]
177 * @param string $prefix [optional]
181 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
182 $ret = "<a class=\"mw-selflink selflink\">{$prefix}{$html}</a>{$trail}";
183 if ( !Hooks
::run( 'SelfLinkBegin', [ $nt, &$html, &$trail, &$prefix, &$ret ] ) ) {
188 $html = htmlspecialchars( $nt->getPrefixedText() );
190 list( $inside, $trail ) = self
::splitTrail( $trail );
191 return "<a class=\"mw-selflink selflink\">{$prefix}{$html}{$inside}</a>{$trail}";
195 * Get a message saying that an invalid title was encountered.
196 * This should be called after a method like Title::makeTitleSafe() returned
197 * a value indicating that the title object is invalid.
199 * @param IContextSource $context Context to use to get the messages
200 * @param int $namespace Namespace number
201 * @param string $title Text of the title, without the namespace part
204 public static function getInvalidTitleDescription( IContextSource
$context, $namespace, $title ) {
207 // First we check whether the namespace exists or not.
208 if ( MWNamespace
::exists( $namespace ) ) {
209 if ( $namespace == NS_MAIN
) {
210 $name = $context->msg( 'blanknamespace' )->text();
212 $name = $wgContLang->getFormattedNsText( $namespace );
214 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
216 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
222 * @param LinkTarget $target
225 public static function normaliseSpecialPage( LinkTarget
$target ) {
226 if ( $target->getNamespace() == NS_SPECIAL
&& !$target->isExternal() ) {
227 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $target->getDBkey() );
231 $ret = SpecialPage
::getTitleValueFor( $name, $subpage, $target->getFragment() );
239 * Returns the filename part of an url.
240 * Used as alternative text for external images.
246 private static function fnamePart( $url ) {
247 $basename = strrchr( $url, '/' );
248 if ( false === $basename ) {
251 $basename = substr( $basename, 1 );
257 * Return the code for images which were added via external links,
258 * via Parser::maybeMakeExternalImage().
266 public static function makeExternalImage( $url, $alt = '' ) {
268 $alt = self
::fnamePart( $url );
271 $success = Hooks
::run( 'LinkerMakeExternalImage', [ &$url, &$alt, &$img ] );
273 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
274 . "with url {$url} and alt text {$alt} to {$img}\n", true );
277 return Html
::element( 'img',
284 * Given parameters derived from [[Image:Foo|options...]], generate the
285 * HTML that that syntax inserts in the page.
287 * @param Parser $parser
288 * @param Title $title Title object of the file (not the currently viewed page)
289 * @param File $file File object, or false if it doesn't exist
290 * @param array $frameParams Associative array of parameters external to the media handler.
291 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
292 * will often be false.
293 * thumbnail If present, downscale and frame
294 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
295 * framed Shows image in original size in a frame
296 * frameless Downscale but don't frame
297 * upright If present, tweak default sizes for portrait orientation
298 * upright_factor Fudge factor for "upright" tweak (default 0.75)
299 * border If present, show a border around the image
300 * align Horizontal alignment (left, right, center, none)
301 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
302 * bottom, text-bottom)
303 * alt Alternate text for image (i.e. alt attribute). Plain text.
304 * class HTML for image classes. Plain text.
305 * caption HTML for image caption.
306 * link-url URL to link to
307 * link-title Title object to link to
308 * link-target Value for the target attribute, only with link-url
309 * no-link Boolean, suppress description link
311 * @param array $handlerParams Associative array of media handler parameters, to be passed
312 * to transform(). Typical keys are "width" and "page".
313 * @param string|bool $time Timestamp of the file, set as false for current
314 * @param string $query Query params for desc url
315 * @param int|null $widthOption Used by the parser to remember the user preference thumbnailsize
317 * @return string HTML for an image, with links, wrappers, etc.
319 public static function makeImageLink( Parser
$parser, Title
$title,
320 $file, $frameParams = [], $handlerParams = [], $time = false,
321 $query = "", $widthOption = null
324 $dummy = new DummyLinker
;
325 if ( !Hooks
::run( 'ImageBeforeProduceHTML', [ &$dummy, &$title,
326 &$file, &$frameParams, &$handlerParams, &$time, &$res ] ) ) {
330 if ( $file && !$file->allowInlineDisplay() ) {
331 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
332 return self
::link( $title );
335 // Clean up parameters
336 $page = isset( $handlerParams['page'] ) ?
$handlerParams['page'] : false;
337 if ( !isset( $frameParams['align'] ) ) {
338 $frameParams['align'] = '';
340 if ( !isset( $frameParams['alt'] ) ) {
341 $frameParams['alt'] = '';
343 if ( !isset( $frameParams['title'] ) ) {
344 $frameParams['title'] = '';
346 if ( !isset( $frameParams['class'] ) ) {
347 $frameParams['class'] = '';
350 $prefix = $postfix = '';
352 if ( 'center' == $frameParams['align'] ) {
353 $prefix = '<div class="center">';
355 $frameParams['align'] = 'none';
357 if ( $file && !isset( $handlerParams['width'] ) ) {
358 if ( isset( $handlerParams['height'] ) && $file->isVectorized() ) {
359 // If its a vector image, and user only specifies height
360 // we don't want it to be limited by its "normal" width.
361 global $wgSVGMaxSize;
362 $handlerParams['width'] = $wgSVGMaxSize;
364 $handlerParams['width'] = $file->getWidth( $page );
367 if ( isset( $frameParams['thumbnail'] )
368 ||
isset( $frameParams['manualthumb'] )
369 ||
isset( $frameParams['framed'] )
370 ||
isset( $frameParams['frameless'] )
371 ||
!$handlerParams['width']
373 global $wgThumbLimits, $wgThumbUpright;
375 if ( $widthOption === null ||
!isset( $wgThumbLimits[$widthOption] ) ) {
376 $widthOption = User
::getDefaultOption( 'thumbsize' );
379 // Reduce width for upright images when parameter 'upright' is used
380 if ( isset( $frameParams['upright'] ) && $frameParams['upright'] == 0 ) {
381 $frameParams['upright'] = $wgThumbUpright;
384 // For caching health: If width scaled down due to upright
385 // parameter, round to full __0 pixel to avoid the creation of a
386 // lot of odd thumbs.
387 $prefWidth = isset( $frameParams['upright'] ) ?
388 round( $wgThumbLimits[$widthOption] * $frameParams['upright'], -1 ) :
389 $wgThumbLimits[$widthOption];
391 // Use width which is smaller: real image width or user preference width
392 // Unless image is scalable vector.
393 if ( !isset( $handlerParams['height'] ) && ( $handlerParams['width'] <= 0 ||
394 $prefWidth < $handlerParams['width'] ||
$file->isVectorized() ) ) {
395 $handlerParams['width'] = $prefWidth;
400 if ( isset( $frameParams['thumbnail'] ) ||
isset( $frameParams['manualthumb'] )
401 ||
isset( $frameParams['framed'] )
403 # Create a thumbnail. Alignment depends on the writing direction of
404 # the page content language (right-aligned for LTR languages,
405 # left-aligned for RTL languages)
406 # If a thumbnail width has not been provided, it is set
407 # to the default user option as specified in Language*.php
408 if ( $frameParams['align'] == '' ) {
409 $frameParams['align'] = $parser->getTargetLanguage()->alignEnd();
412 self
::makeThumbLink2( $title, $file, $frameParams, $handlerParams, $time, $query ) .
416 if ( $file && isset( $frameParams['frameless'] ) ) {
417 $srcWidth = $file->getWidth( $page );
418 # For "frameless" option: do not present an image bigger than the
419 # source (for bitmap-style images). This is the same behavior as the
420 # "thumb" option does it already.
421 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
422 $handlerParams['width'] = $srcWidth;
426 if ( $file && isset( $handlerParams['width'] ) ) {
427 # Create a resized image, without the additional thumbnail features
428 $thumb = $file->transform( $handlerParams );
434 $s = self
::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
436 self
::processResponsiveImages( $file, $thumb, $handlerParams );
438 'alt' => $frameParams['alt'],
439 'title' => $frameParams['title'],
440 'valign' => isset( $frameParams['valign'] ) ?
$frameParams['valign'] : false,
441 'img-class' => $frameParams['class'] ];
442 if ( isset( $frameParams['border'] ) ) {
443 $params['img-class'] .= ( $params['img-class'] !== '' ?
' ' : '' ) . 'thumbborder';
445 $params = self
::getImageLinkMTOParams( $frameParams, $query, $parser ) +
$params;
447 $s = $thumb->toHtml( $params );
449 if ( $frameParams['align'] != '' ) {
450 $s = "<div class=\"float{$frameParams['align']}\">{$s}</div>";
452 return str_replace( "\n", ' ', $prefix . $s . $postfix );
456 * Get the link parameters for MediaTransformOutput::toHtml() from given
457 * frame parameters supplied by the Parser.
458 * @param array $frameParams The frame parameters
459 * @param string $query An optional query string to add to description page links
460 * @param Parser|null $parser
463 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
465 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
466 $mtoParams['custom-url-link'] = $frameParams['link-url'];
467 if ( isset( $frameParams['link-target'] ) ) {
468 $mtoParams['custom-target-link'] = $frameParams['link-target'];
471 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
472 foreach ( $extLinkAttrs as $name => $val ) {
473 // Currently could include 'rel' and 'target'
474 $mtoParams['parser-extlink-' . $name] = $val;
477 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
478 $mtoParams['custom-title-link'] = Title
::newFromLinkTarget(
479 self
::normaliseSpecialPage( $frameParams['link-title'] )
481 } elseif ( !empty( $frameParams['no-link'] ) ) {
484 $mtoParams['desc-link'] = true;
485 $mtoParams['desc-query'] = $query;
491 * Make HTML for a thumbnail including image, border and caption
492 * @param Title $title
493 * @param File|bool $file File object or false if it doesn't exist
494 * @param string $label
496 * @param string $align
497 * @param array $params
498 * @param bool $framed
499 * @param string $manualthumb
502 public static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt,
503 $align = 'right', $params = [], $framed = false, $manualthumb = ""
511 $frameParams['framed'] = true;
513 if ( $manualthumb ) {
514 $frameParams['manualthumb'] = $manualthumb;
516 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
520 * @param Title $title
522 * @param array $frameParams
523 * @param array $handlerParams
525 * @param string $query
528 public static function makeThumbLink2( Title
$title, $file, $frameParams = [],
529 $handlerParams = [], $time = false, $query = ""
531 $exists = $file && $file->exists();
533 $page = isset( $handlerParams['page'] ) ?
$handlerParams['page'] : false;
534 if ( !isset( $frameParams['align'] ) ) {
535 $frameParams['align'] = 'right';
537 if ( !isset( $frameParams['alt'] ) ) {
538 $frameParams['alt'] = '';
540 if ( !isset( $frameParams['title'] ) ) {
541 $frameParams['title'] = '';
543 if ( !isset( $frameParams['caption'] ) ) {
544 $frameParams['caption'] = '';
547 if ( empty( $handlerParams['width'] ) ) {
548 // Reduce width for upright images when parameter 'upright' is used
549 $handlerParams['width'] = isset( $frameParams['upright'] ) ?
130 : 180;
553 $manualthumb = false;
556 $outerWidth = $handlerParams['width'] +
2;
558 if ( isset( $frameParams['manualthumb'] ) ) {
559 # Use manually specified thumbnail
560 $manual_title = Title
::makeTitleSafe( NS_FILE
, $frameParams['manualthumb'] );
561 if ( $manual_title ) {
562 $manual_img = wfFindFile( $manual_title );
564 $thumb = $manual_img->getUnscaledThumb( $handlerParams );
570 } elseif ( isset( $frameParams['framed'] ) ) {
571 // Use image dimensions, don't scale
572 $thumb = $file->getUnscaledThumb( $handlerParams );
575 # Do not present an image bigger than the source, for bitmap-style images
576 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
577 $srcWidth = $file->getWidth( $page );
578 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
579 $handlerParams['width'] = $srcWidth;
581 $thumb = $file->transform( $handlerParams );
585 $outerWidth = $thumb->getWidth() +
2;
587 $outerWidth = $handlerParams['width'] +
2;
591 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
592 # So we don't need to pass it here in $query. However, the URL for the
593 # zoom icon still needs it, so we make a unique query for it. See T16771
594 $url = $title->getLocalURL( $query );
596 $url = wfAppendQuery( $url, [ 'page' => $page ] );
599 && !isset( $frameParams['link-title'] )
600 && !isset( $frameParams['link-url'] )
601 && !isset( $frameParams['no-link'] ) ) {
602 $frameParams['link-url'] = $url;
605 $s = "<div class=\"thumb t{$frameParams['align']}\">"
606 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
609 $s .= self
::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
611 } elseif ( !$thumb ) {
612 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
615 if ( !$noscale && !$manualthumb ) {
616 self
::processResponsiveImages( $file, $thumb, $handlerParams );
619 'alt' => $frameParams['alt'],
620 'title' => $frameParams['title'],
621 'img-class' => ( isset( $frameParams['class'] ) && $frameParams['class'] !== ''
622 ?
$frameParams['class'] . ' '
623 : '' ) . 'thumbimage'
625 $params = self
::getImageLinkMTOParams( $frameParams, $query ) +
$params;
626 $s .= $thumb->toHtml( $params );
627 if ( isset( $frameParams['framed'] ) ) {
630 $zoomIcon = Html
::rawElement( 'div', [ 'class' => 'magnify' ],
631 Html
::rawElement( 'a', [
633 'class' => 'internal',
634 'title' => wfMessage( 'thumbnail-more' )->text() ],
638 $s .= ' <div class="thumbcaption">' . $zoomIcon . $frameParams['caption'] . "</div></div></div>";
639 return str_replace( "\n", ' ', $s );
643 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
647 * @param MediaTransformOutput $thumb
648 * @param array $hp Image parameters
650 public static function processResponsiveImages( $file, $thumb, $hp ) {
651 global $wgResponsiveImages;
652 if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
654 $hp15['width'] = round( $hp['width'] * 1.5 );
656 $hp20['width'] = $hp['width'] * 2;
657 if ( isset( $hp['height'] ) ) {
658 $hp15['height'] = round( $hp['height'] * 1.5 );
659 $hp20['height'] = $hp['height'] * 2;
662 $thumb15 = $file->transform( $hp15 );
663 $thumb20 = $file->transform( $hp20 );
664 if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
665 $thumb->responsiveUrls
['1.5'] = $thumb15->getUrl();
667 if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
668 $thumb->responsiveUrls
['2'] = $thumb20->getUrl();
674 * Make a "broken" link to an image
677 * @param Title $title
678 * @param string $label Link label (plain text)
679 * @param string $query Query string
680 * @param string $unused1 Unused parameter kept for b/c
681 * @param string $unused2 Unused parameter kept for b/c
682 * @param bool $time A file of a certain timestamp was requested
685 public static function makeBrokenImageLinkObj( $title, $label = '',
686 $query = '', $unused1 = '', $unused2 = '', $time = false
688 if ( !$title instanceof Title
) {
689 wfWarn( __METHOD__
. ': Requires $title to be a Title object.' );
690 return "<!-- ERROR -->" . htmlspecialchars( $label );
693 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
694 if ( $label == '' ) {
695 $label = $title->getPrefixedText();
697 $encLabel = htmlspecialchars( $label );
698 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
700 if ( ( $wgUploadMissingFileUrl ||
$wgUploadNavigationUrl ||
$wgEnableUploads )
703 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
706 // We already know it's a redirect, so mark it
711 [ 'class' => 'mw-redirect' ],
712 wfCgiToArray( $query ),
713 [ 'known', 'noclasses' ]
717 $href = self
::getUploadUrl( $title, $query );
719 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
720 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
724 return self
::link( $title, $encLabel, [], wfCgiToArray( $query ), [ 'known', 'noclasses' ] );
728 * Get the URL to upload a certain file
731 * @param Title $destFile Title object of the file to upload
732 * @param string $query Urlencoded query string to prepend
733 * @return string Urlencoded URL
735 protected static function getUploadUrl( $destFile, $query = '' ) {
736 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
737 $q = 'wpDestFile=' . $destFile->getPartialURL();
738 if ( $query != '' ) {
742 if ( $wgUploadMissingFileUrl ) {
743 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
744 } elseif ( $wgUploadNavigationUrl ) {
745 return wfAppendQuery( $wgUploadNavigationUrl, $q );
747 $upload = SpecialPage
::getTitleFor( 'Upload' );
748 return $upload->getLocalURL( $q );
753 * Create a direct link to a given uploaded file.
756 * @param Title $title
757 * @param string $html Pre-sanitized HTML
758 * @param string $time MW timestamp of file creation time
759 * @return string HTML
761 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
762 $img = wfFindFile( $title, [ 'time' => $time ] );
763 return self
::makeMediaLinkFile( $title, $img, $html );
767 * Create a direct link to a given uploaded file.
768 * This will make a broken link if $file is false.
771 * @param Title $title
772 * @param File|bool $file File object or false
773 * @param string $html Pre-sanitized HTML
774 * @return string HTML
776 * @todo Handle invalid or missing images better.
778 public static function makeMediaLinkFile( Title
$title, $file, $html = '' ) {
779 if ( $file && $file->exists() ) {
780 $url = $file->getUrl();
783 $url = self
::getUploadUrl( $title );
787 $alt = $title->getText();
799 if ( !Hooks
::run( 'LinkerMakeMediaLinkFile',
800 [ $title, $file, &$html, &$attribs, &$ret ] ) ) {
801 wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
802 . "with url {$url} and text {$html} to {$ret}\n", true );
806 return Html
::rawElement( 'a', $attribs, $html );
810 * Make a link to a special page given its name and, optionally,
811 * a message key from the link text.
812 * Usage example: Linker::specialLink( 'Recentchanges' )
815 * @param string $name
819 public static function specialLink( $name, $key = '' ) {
821 $key = strtolower( $name );
824 return self
::linkKnown( SpecialPage
::getTitleFor( $name ), wfMessage( $key )->text() );
828 * Make an external link
829 * @since 1.16.3. $title added in 1.21
830 * @param string $url URL to link to
831 * @param string $text Text of link
832 * @param bool $escape Do we escape the link text?
833 * @param string $linktype Type of external link. Gets added to the classes
834 * @param array $attribs Array of extra attributes to <a>
835 * @param Title|null $title Title object used for title specific link attributes
838 public static function makeExternalLink( $url, $text, $escape = true,
839 $linktype = '', $attribs = [], $title = null
844 $class .= " $linktype";
846 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
847 $class .= " {$attribs['class']}";
849 $attribs['class'] = $class;
852 $text = htmlspecialchars( $text );
858 $newRel = Parser
::getExternalLinkRel( $url, $title );
859 if ( !isset( $attribs['rel'] ) ||
$attribs['rel'] === '' ) {
860 $attribs['rel'] = $newRel;
861 } elseif ( $newRel !== '' ) {
862 // Merge the rel attributes.
863 $newRels = explode( ' ', $newRel );
864 $oldRels = explode( ' ', $attribs['rel'] );
865 $combined = array_unique( array_merge( $newRels, $oldRels ) );
866 $attribs['rel'] = implode( ' ', $combined );
869 $success = Hooks
::run( 'LinkerMakeExternalLink',
870 [ &$url, &$text, &$link, &$attribs, $linktype ] );
872 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
873 . "with url {$url} and text {$text} to {$link}\n", true );
876 $attribs['href'] = $url;
877 return Html
::rawElement( 'a', $attribs, $text );
881 * Make user link (or user contributions for unregistered users)
882 * @param int $userId User id in database.
883 * @param string $userName User name in database.
884 * @param string $altUserName Text to display instead of the user name (optional)
885 * @return string HTML fragment
886 * @since 1.16.3. $altUserName was added in 1.19.
888 public static function userLink( $userId, $userName, $altUserName = false ) {
889 $classes = 'mw-userlink';
890 if ( $userId == 0 ) {
891 $page = SpecialPage
::getTitleFor( 'Contributions', $userName );
892 if ( $altUserName === false ) {
893 $altUserName = IP
::prettifyIP( $userName );
895 $classes .= ' mw-anonuserlink'; // Separate link class for anons (T45179)
897 $page = Title
::makeTitle( NS_USER
, $userName );
900 // Wrap the output with <bdi> tags for directionality isolation
903 '<bdi>' . htmlspecialchars( $altUserName !== false ?
$altUserName : $userName ) . '</bdi>',
904 [ 'class' => $classes ]
909 * Generate standard user tool links (talk, contributions, block link, etc.)
912 * @param int $userId User identifier
913 * @param string $userText User name or IP address
914 * @param bool $redContribsWhenNoEdits Should the contributions link be
915 * red if the user has no edits?
916 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
917 * and Linker::TOOL_LINKS_EMAIL).
918 * @param int $edits User edit count (optional, for performance)
919 * @return string HTML fragment
921 public static function userToolLinks(
922 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
924 global $wgUser, $wgDisableAnonTalk, $wgLang;
925 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
926 $blockable = !( $flags & self
::TOOL_LINKS_NOBLOCK
);
927 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
&& $userId;
931 $items[] = self
::userTalkLink( $userId, $userText );
934 // check if the user has an edit
936 $attribs['class'] = 'mw-usertoollinks-contribs';
937 if ( $redContribsWhenNoEdits ) {
938 if ( intval( $edits ) === 0 && $edits !== 0 ) {
939 $user = User
::newFromId( $userId );
940 $edits = $user->getEditCount();
942 if ( $edits === 0 ) {
943 $attribs['class'] .= ' new';
946 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
948 $items[] = self
::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
950 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
951 $items[] = self
::blockLink( $userId, $userText );
954 if ( $addEmailLink && $wgUser->canSendEmail() ) {
955 $items[] = self
::emailLink( $userId, $userText );
958 Hooks
::run( 'UserToolLinksEdit', [ $userId, $userText, &$items ] );
961 return wfMessage( 'word-separator' )->escaped()
962 . '<span class="mw-usertoollinks">'
963 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
971 * Alias for userToolLinks( $userId, $userText, true );
973 * @param int $userId User identifier
974 * @param string $userText User name or IP address
975 * @param int $edits User edit count (optional, for performance)
978 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
979 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
984 * @param int $userId User id in database.
985 * @param string $userText User name in database.
986 * @return string HTML fragment with user talk link
988 public static function userTalkLink( $userId, $userText ) {
989 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
990 $moreLinkAttribs['class'] = 'mw-usertoollinks-talk';
991 $userTalkLink = self
::link( $userTalkPage,
992 wfMessage( 'talkpagelinktext' )->escaped(),
994 return $userTalkLink;
999 * @param int $userId Userid
1000 * @param string $userText User name in database.
1001 * @return string HTML fragment with block link
1003 public static function blockLink( $userId, $userText ) {
1004 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1005 $moreLinkAttribs['class'] = 'mw-usertoollinks-block';
1006 $blockLink = self
::link( $blockPage,
1007 wfMessage( 'blocklink' )->escaped(),
1013 * @param int $userId Userid
1014 * @param string $userText User name in database.
1015 * @return string HTML fragment with e-mail user link
1017 public static function emailLink( $userId, $userText ) {
1018 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1019 $moreLinkAttribs['class'] = 'mw-usertoollinks-mail';
1020 $emailLink = self
::link( $emailPage,
1021 wfMessage( 'emaillink' )->escaped(),
1027 * Generate a user link if the current user is allowed to view it
1029 * @param Revision $rev
1030 * @param bool $isPublic Show only if all users can see it
1031 * @return string HTML fragment
1033 public static function revUserLink( $rev, $isPublic = false ) {
1034 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1035 $link = wfMessage( 'rev-deleted-user' )->escaped();
1036 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1037 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1038 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1040 $link = wfMessage( 'rev-deleted-user' )->escaped();
1042 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1043 return '<span class="history-deleted">' . $link . '</span>';
1049 * Generate a user tool link cluster if the current user is allowed to view it
1051 * @param Revision $rev
1052 * @param bool $isPublic Show only if all users can see it
1053 * @return string HTML
1055 public static function revUserTools( $rev, $isPublic = false ) {
1056 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1057 $link = wfMessage( 'rev-deleted-user' )->escaped();
1058 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1059 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1060 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1061 $link = self
::userLink( $userId, $userText )
1062 . self
::userToolLinks( $userId, $userText );
1064 $link = wfMessage( 'rev-deleted-user' )->escaped();
1066 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1067 return ' <span class="history-deleted">' . $link . '</span>';
1073 * This function is called by all recent changes variants, by the page history,
1074 * and by the user contributions list. It is responsible for formatting edit
1075 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1076 * auto-generated comments (from section editing) and formats [[wikilinks]].
1078 * @author Erik Moeller <moeller@scireview.de>
1079 * @since 1.16.3. $wikiId added in 1.26
1081 * Note: there's not always a title to pass to this function.
1082 * Since you can't set a default parameter for a reference, I've turned it
1083 * temporarily to a value pass. Should be adjusted further. --brion
1085 * @param string $comment
1086 * @param Title|null $title Title object (to generate link to the section in autocomment)
1088 * @param bool $local Whether section links should refer to local page
1089 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1090 * For use with external changes.
1092 * @return mixed|string
1094 public static function formatComment(
1095 $comment, $title = null, $local = false, $wikiId = null
1097 # Sanitize text a bit:
1098 $comment = str_replace( "\n", " ", $comment );
1099 # Allow HTML entities (for T15815)
1100 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1102 # Render autocomments and make links:
1103 $comment = self
::formatAutocomments( $comment, $title, $local, $wikiId );
1104 $comment = self
::formatLinksInComment( $comment, $title, $local, $wikiId );
1110 * Converts autogenerated comments in edit summaries into section links.
1112 * The pattern for autogen comments is / * foo * /, which makes for
1114 * We look for all comments, match any text before and after the comment,
1115 * add a separator where needed and format the comment itself with CSS
1116 * Called by Linker::formatComment.
1118 * @param string $comment Comment text
1119 * @param Title|null $title An optional title object used to links to sections
1120 * @param bool $local Whether section links should refer to local page
1121 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1122 * as used by WikiMap.
1124 * @return string Formatted comment (wikitext)
1126 private static function formatAutocomments(
1127 $comment, $title = null, $local = false, $wikiId = null
1129 // @todo $append here is something of a hack to preserve the status
1130 // quo. Someone who knows more about bidi and such should decide
1131 // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1132 // wiki, both when autocomments exist and when they don't, and
1133 // (2) what markup will make that actually happen.
1135 $comment = preg_replace_callback(
1136 // To detect the presence of content before or after the
1137 // auto-comment, we use capturing groups inside optional zero-width
1138 // assertions. But older versions of PCRE can't directly make
1139 // zero-width assertions optional, so wrap them in a non-capturing
1141 '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1142 function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1145 // Ensure all match positions are defined
1146 $match +
= [ '', '', '', '' ];
1148 $pre = $match[1] !== '';
1150 $post = $match[3] !== '';
1154 'FormatAutocomments',
1155 [ &$comment, $pre, $auto, $post, $title, $local, $wikiId ]
1158 if ( $comment === null ) {
1162 # Remove links that a user may have manually put in the autosummary
1163 # This could be improved by copying as much of Parser::stripSectionName as desired.
1164 $section = str_replace( '[[:', '', $section );
1165 $section = str_replace( '[[', '', $section );
1166 $section = str_replace( ']]', '', $section );
1168 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # T24784
1170 $sectionTitle = Title
::newFromText( '#' . $section );
1172 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1173 $title->getDBkey(), $section );
1175 if ( $sectionTitle ) {
1176 $link = Linker
::makeCommentLink( $sectionTitle, $wgLang->getArrow(), $wikiId, 'noclasses' );
1182 # written summary $presep autocomment (summary /* section */)
1183 $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1186 # autocomment $postsep written summary (/* section */ summary)
1187 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1189 $auto = '<span class="autocomment">' . $auto . '</span>';
1190 $comment = $pre . $link . $wgLang->getDirMark()
1191 . '<span dir="auto">' . $auto;
1192 $append .= '</span>';
1198 return $comment . $append;
1202 * Formats wiki links and media links in text; all other wiki formatting
1205 * @since 1.16.3. $wikiId added in 1.26
1206 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1208 * @param string $comment Text to format links in. WARNING! Since the output of this
1209 * function is html, $comment must be sanitized for use as html. You probably want
1210 * to pass $comment through Sanitizer::escapeHtmlAllowEntities() before calling
1212 * @param Title|null $title An optional title object used to links to sections
1213 * @param bool $local Whether section links should refer to local page
1214 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1215 * as used by WikiMap.
1219 public static function formatLinksInComment(
1220 $comment, $title = null, $local = false, $wikiId = null
1222 return preg_replace_callback(
1225 :? # ignore optional leading colon
1226 ([^\]|]+) # 1. link target; page names cannot include ] or |
1229 # Stop matching at ]] without relying on backtracking.
1233 ([^[]*) # 3. link trail (the text up until the next link)
1235 function ( $match ) use ( $title, $local, $wikiId ) {
1238 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1239 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1241 $comment = $match[0];
1243 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1244 if ( strpos( $match[1], '%' ) !== false ) {
1246 rawurldecode( $match[1] ),
1247 [ '<' => '<', '>' => '>' ]
1251 # Handle link renaming [[foo|text]] will show link as "text"
1252 if ( $match[2] != "" ) {
1259 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1260 # Media link; trail not supported.
1261 $linkRegexp = '/\[\[(.*?)\]\]/';
1262 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1264 $thelink = Linker
::makeMediaLinkObj( $title, $text );
1267 # Other kind of link
1268 # Make sure its target is non-empty
1269 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1270 $match[1] = substr( $match[1], 1 );
1272 if ( $match[1] !== false && $match[1] !== '' ) {
1273 if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1274 $trail = $submatch[1];
1278 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1279 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1282 $linkTarget = Linker
::normalizeSubpageLink( $title, $match[1], $linkText );
1284 $target = Title
::newFromText( $linkTarget );
1286 if ( $target->getText() == '' && !$target->isExternal()
1287 && !$local && $title
1289 $newTarget = clone $title;
1290 $newTarget->setFragment( '#' . $target->getFragment() );
1291 $target = $newTarget;
1294 $thelink = Linker
::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1299 // If the link is still valid, go ahead and replace it in!
1300 $comment = preg_replace(
1302 StringUtils
::escapeRegexReplacement( $thelink ),
1315 * Generates a link to the given Title
1317 * @note This is only public for technical reasons. It's not intended for use outside Linker.
1319 * @param Title $title
1320 * @param string $text
1321 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1322 * as used by WikiMap.
1323 * @param string|string[] $options See the $options parameter in Linker::link.
1325 * @return string HTML link
1327 public static function makeCommentLink(
1328 Title
$title, $text, $wikiId = null, $options = []
1330 if ( $wikiId !== null && !$title->isExternal() ) {
1331 $link = Linker
::makeExternalLink(
1332 WikiMap
::getForeignURL(
1334 $title->getPrefixedText(),
1335 $title->getFragment()
1338 /* escape = */ false // Already escaped
1341 $link = Linker
::link( $title, $text, [], [], $options );
1348 * @param Title $contextTitle
1349 * @param string $target
1350 * @param string $text
1353 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1356 # :Foobar -- override special treatment of prefix (images, language links)
1357 # /Foobar -- convert to CurrentPage/Foobar
1358 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1359 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1360 # ../Foobar -- convert to CurrentPage/Foobar,
1361 # (from CurrentPage/CurrentSubPage)
1362 # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1363 # (from CurrentPage/CurrentSubPage)
1365 $ret = $target; # default return value is no change
1367 # Some namespaces don't allow subpages,
1368 # so only perform processing if subpages are allowed
1369 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1370 $hash = strpos( $target, '#' );
1371 if ( $hash !== false ) {
1372 $suffix = substr( $target, $hash );
1373 $target = substr( $target, 0, $hash );
1378 $target = trim( $target );
1379 # Look at the first character
1380 if ( $target != '' && $target[0] === '/' ) {
1381 # / at end means we don't want the slash to be shown
1383 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1384 if ( $trailingSlashes ) {
1385 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1387 $noslash = substr( $target, 1 );
1390 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1391 if ( $text === '' ) {
1392 $text = $target . $suffix;
1393 } # this might be changed for ugliness reasons
1395 # check for .. subpage backlinks
1397 $nodotdot = $target;
1398 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1400 $nodotdot = substr( $nodotdot, 3 );
1402 if ( $dotdotcount > 0 ) {
1403 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1404 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1405 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1406 # / at the end means don't show full path
1407 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1408 $nodotdot = rtrim( $nodotdot, '/' );
1409 if ( $text === '' ) {
1410 $text = $nodotdot . $suffix;
1413 $nodotdot = trim( $nodotdot );
1414 if ( $nodotdot != '' ) {
1415 $ret .= '/' . $nodotdot;
1427 * Wrap a comment in standard punctuation and formatting if
1428 * it's non-empty, otherwise return empty string.
1430 * @since 1.16.3. $wikiId added in 1.26
1431 * @param string $comment
1432 * @param Title|null $title Title object (to generate link to section in autocomment) or null
1433 * @param bool $local Whether section links should refer to local page
1434 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1435 * For use with external changes.
1439 public static function commentBlock(
1440 $comment, $title = null, $local = false, $wikiId = null
1442 // '*' used to be the comment inserted by the software way back
1443 // in antiquity in case none was provided, here for backwards
1444 // compatibility, acc. to brion -ævar
1445 if ( $comment == '' ||
$comment == '*' ) {
1448 $formatted = self
::formatComment( $comment, $title, $local, $wikiId );
1449 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1450 return " <span class=\"comment\">$formatted</span>";
1455 * Wrap and format the given revision's comment block, if the current
1456 * user is allowed to view it.
1459 * @param Revision $rev
1460 * @param bool $local Whether section links should refer to local page
1461 * @param bool $isPublic Show only if all users can see it
1462 * @return string HTML fragment
1464 public static function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1465 if ( $rev->getComment( Revision
::RAW
) == "" ) {
1468 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1469 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1470 } elseif ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1471 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1472 $rev->getTitle(), $local );
1474 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1476 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1477 return " <span class=\"history-deleted\">$block</span>";
1487 public static function formatRevisionSize( $size ) {
1489 $stxt = wfMessage( 'historyempty' )->escaped();
1491 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1492 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1494 return "<span class=\"history-size\">$stxt</span>";
1498 * Add another level to the Table of Contents
1503 public static function tocIndent() {
1508 * Finish one or more sublevels on the Table of Contents
1514 public static function tocUnindent( $level ) {
1515 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1519 * parameter level defines if we are on an indentation level
1522 * @param string $anchor
1523 * @param string $tocline
1524 * @param string $tocnumber
1525 * @param string $level
1526 * @param string|bool $sectionIndex
1529 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1530 $classes = "toclevel-$level";
1531 if ( $sectionIndex !== false ) {
1532 $classes .= " tocsection-$sectionIndex";
1534 return "\n<li class=\"$classes\"><a href=\"#" .
1535 $anchor . '"><span class="tocnumber">' .
1536 $tocnumber . '</span> <span class="toctext">' .
1537 $tocline . '</span></a>';
1541 * End a Table Of Contents line.
1542 * tocUnindent() will be used instead if we're ending a line below
1547 public static function tocLineEnd() {
1552 * Wraps the TOC in a table and provides the hide/collapse javascript.
1555 * @param string $toc Html of the Table Of Contents
1556 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1557 * @return string Full html of the TOC
1559 public static function tocList( $toc, $lang = false ) {
1560 $lang = wfGetLangObj( $lang );
1561 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1563 return '<div id="toc" class="toc">'
1564 . '<div id="toctitle" class="toctitle"><h2>' . $title . "</h2></div>\n"
1566 . "</ul>\n</div>\n";
1570 * Generate a table of contents from a section tree.
1572 * @since 1.16.3. $lang added in 1.17
1573 * @param array $tree Return value of ParserOutput::getSections()
1574 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1575 * @return string HTML fragment
1577 public static function generateTOC( $tree, $lang = false ) {
1580 foreach ( $tree as $section ) {
1581 if ( $section['toclevel'] > $lastLevel ) {
1582 $toc .= self
::tocIndent();
1583 } elseif ( $section['toclevel'] < $lastLevel ) {
1584 $toc .= self
::tocUnindent(
1585 $lastLevel - $section['toclevel'] );
1587 $toc .= self
::tocLineEnd();
1590 $toc .= self
::tocLine( $section['anchor'],
1591 $section['line'], $section['number'],
1592 $section['toclevel'], $section['index'] );
1593 $lastLevel = $section['toclevel'];
1595 $toc .= self
::tocLineEnd();
1596 return self
::tocList( $toc, $lang );
1600 * Create a headline for content
1603 * @param int $level The level of the headline (1-6)
1604 * @param string $attribs Any attributes for the headline, starting with
1605 * a space and ending with '>'
1606 * This *must* be at least '>' for no attribs
1607 * @param string $anchor The anchor to give the headline (the bit after the #)
1608 * @param string $html Html for the text of the header
1609 * @param string $link HTML to add for the section edit link
1610 * @param bool|string $legacyAnchor A second, optional anchor to give for
1611 * backward compatibility (false to omit)
1613 * @return string HTML headline
1615 public static function makeHeadline( $level, $attribs, $anchor, $html,
1616 $link, $legacyAnchor = false
1618 $ret = "<h$level$attribs"
1619 . "<span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1622 if ( $legacyAnchor !== false ) {
1623 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1629 * Split a link trail, return the "inside" portion and the remainder of the trail
1630 * as a two-element array
1631 * @param string $trail
1634 static function splitTrail( $trail ) {
1636 $regex = $wgContLang->linkTrail();
1638 if ( $trail !== '' ) {
1640 if ( preg_match( $regex, $trail, $m ) ) {
1645 return [ $inside, $trail ];
1649 * Generate a rollback link for a given revision. Currently it's the
1650 * caller's responsibility to ensure that the revision is the top one. If
1651 * it's not, of course, the user will get an error message.
1653 * If the calling page is called with the parameter &bot=1, all rollback
1654 * links also get that parameter. It causes the edit itself and the rollback
1655 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1656 * changes, so this allows sysops to combat a busy vandal without bothering
1659 * If the option verify is set this function will return the link only in case the
1660 * revision can be reverted. Please note that due to performance limitations
1661 * it might be assumed that a user isn't the only contributor of a page while
1662 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1663 * work if $wgShowRollbackEditCount is disabled, so this can only function
1664 * as an additional check.
1666 * If the option noBrackets is set the rollback link wont be enclosed in "[]".
1668 * @since 1.16.3. $context added in 1.20. $options added in 1.21
1670 * @param Revision $rev
1671 * @param IContextSource $context Context to use or null for the main context.
1672 * @param array $options
1675 public static function generateRollback( $rev, IContextSource
$context = null,
1676 $options = [ 'verify' ]
1678 if ( $context === null ) {
1679 $context = RequestContext
::getMain();
1683 if ( in_array( 'verify', $options, true ) ) {
1684 $editCount = self
::getRollbackEditCount( $rev, true );
1685 if ( $editCount === false ) {
1690 $inner = self
::buildRollbackLink( $rev, $context, $editCount );
1692 if ( !in_array( 'noBrackets', $options, true ) ) {
1693 $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1696 return '<span class="mw-rollback-link">' . $inner . '</span>';
1700 * This function will return the number of revisions which a rollback
1701 * would revert and, if $verify is set it will verify that a revision
1702 * can be reverted (that the user isn't the only contributor and the
1703 * revision we might rollback to isn't deleted). These checks can only
1704 * function as an additional check as this function only checks against
1705 * the last $wgShowRollbackEditCount edits.
1707 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1708 * is set and the user is the only contributor of the page.
1710 * @param Revision $rev
1711 * @param bool $verify Try to verify that this revision can really be rolled back
1712 * @return int|bool|null
1714 public static function getRollbackEditCount( $rev, $verify ) {
1715 global $wgShowRollbackEditCount;
1716 if ( !is_int( $wgShowRollbackEditCount ) ||
!$wgShowRollbackEditCount > 0 ) {
1717 // Nothing has happened, indicate this by returning 'null'
1721 $dbr = wfGetDB( DB_REPLICA
);
1723 // Up to the value of $wgShowRollbackEditCount revisions are counted
1724 $res = $dbr->select(
1726 [ 'rev_user_text', 'rev_deleted' ],
1727 // $rev->getPage() returns null sometimes
1728 [ 'rev_page' => $rev->getTitle()->getArticleID() ],
1731 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
1732 'ORDER BY' => 'rev_timestamp DESC',
1733 'LIMIT' => $wgShowRollbackEditCount +
1
1739 foreach ( $res as $row ) {
1740 if ( $rev->getUserText( Revision
::RAW
) != $row->rev_user_text
) {
1742 ( $row->rev_deleted
& Revision
::DELETED_TEXT
1743 ||
$row->rev_deleted
& Revision
::DELETED_USER
1745 // If the user or the text of the revision we might rollback
1746 // to is deleted in some way we can't rollback. Similar to
1747 // the sanity checks in WikiPage::commitRollback.
1756 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1757 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1758 // and there weren't any other revisions. That means that the current user is the only
1759 // editor, so we can't rollback
1766 * Build a raw rollback link, useful for collections of "tool" links
1768 * @since 1.16.3. $context added in 1.20. $editCount added in 1.21
1769 * @param Revision $rev
1770 * @param IContextSource|null $context Context to use or null for the main context.
1771 * @param int $editCount Number of edits that would be reverted
1772 * @return string HTML fragment
1774 public static function buildRollbackLink( $rev, IContextSource
$context = null,
1777 global $wgShowRollbackEditCount, $wgMiserMode;
1779 // To config which pages are affected by miser mode
1780 $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
1782 if ( $context === null ) {
1783 $context = RequestContext
::getMain();
1786 $title = $rev->getTitle();
1788 'action' => 'rollback',
1789 'from' => $rev->getUserText(),
1790 'token' => $context->getUser()->getEditToken( 'rollback' ),
1793 'data-mw' => 'interface',
1794 'title' => $context->msg( 'tooltip-rollback' )->text(),
1796 $options = [ 'known', 'noclasses' ];
1798 if ( $context->getRequest()->getBool( 'bot' ) ) {
1799 $query['bot'] = '1';
1800 $query['hidediff'] = '1'; // T17999
1803 $disableRollbackEditCount = false;
1804 if ( $wgMiserMode ) {
1805 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1806 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1807 $disableRollbackEditCount = true;
1813 if ( !$disableRollbackEditCount
1814 && is_int( $wgShowRollbackEditCount )
1815 && $wgShowRollbackEditCount > 0
1817 if ( !is_numeric( $editCount ) ) {
1818 $editCount = self
::getRollbackEditCount( $rev, false );
1821 if ( $editCount > $wgShowRollbackEditCount ) {
1822 $html = $context->msg( 'rollbacklinkcount-morethan' )
1823 ->numParams( $wgShowRollbackEditCount )->parse();
1825 $html = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1828 return self
::link( $title, $html, $attrs, $query, $options );
1830 $html = $context->msg( 'rollbacklink' )->escaped();
1831 return self
::link( $title, $html, $attrs, $query, $options );
1836 * @deprecated since 1.28, use TemplatesOnThisPageFormatter directly
1838 * Returns HTML for the "templates used on this page" list.
1840 * Make an HTML list of templates, and then add a "More..." link at
1841 * the bottom. If $more is null, do not add a "More..." link. If $more
1842 * is a Title, make a link to that title and use it. If $more is a string,
1843 * directly paste it in as the link (escaping needs to be done manually).
1844 * Finally, if $more is a Message, call toString().
1846 * @since 1.16.3. $more added in 1.21
1847 * @param Title[] $templates Array of templates
1848 * @param bool $preview Whether this is for a preview
1849 * @param bool $section Whether this is for a section edit
1850 * @param Title|Message|string|null $more An escaped link for "More..." of the templates
1851 * @return string HTML output
1853 public static function formatTemplates( $templates, $preview = false,
1854 $section = false, $more = null
1856 wfDeprecated( __METHOD__
, '1.28' );
1861 } elseif ( $section ) {
1865 if ( $more instanceof Message
) {
1866 $more = $more->toString();
1869 $formatter = new TemplatesOnThisPageFormatter(
1870 RequestContext
::getMain(),
1871 MediaWikiServices
::getInstance()->getLinkRenderer()
1873 return $formatter->format( $templates, $type, $more );
1877 * Returns HTML for the "hidden categories on this page" list.
1880 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1882 * @return string HTML output
1884 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 * @deprecated since 1.28, use Language::formatSize() directly
1907 * Format a size in bytes for output, using an appropriate
1908 * unit (B, KB, MB or GB) according to the magnitude in question
1911 * @param int $size Size to format
1914 public static function formatSize( $size ) {
1915 wfDeprecated( __METHOD__
, '1.28' );
1918 return htmlspecialchars( $wgLang->formatSize( $size ) );
1922 * Given the id of an interface element, constructs the appropriate title
1923 * attribute from the system messages. (Note, this is usually the id but
1924 * isn't always, because sometimes the accesskey needs to go on a different
1925 * element than the id, for reverse-compatibility, etc.)
1927 * @since 1.16.3 $msgParams added in 1.27
1928 * @param string $name Id of the element, minus prefixes.
1929 * @param string|null $options Null or the string 'withaccess' to add an access-
1931 * @param array $msgParams Parameters to pass to the message
1933 * @return string Contents of the title attribute (which you must HTML-
1934 * escape), or false for no title attribute
1936 public static function titleAttrib( $name, $options = null, array $msgParams = [] ) {
1937 $message = wfMessage( "tooltip-$name", $msgParams );
1938 if ( !$message->exists() ) {
1941 $tooltip = $message->text();
1942 # Compatibility: formerly some tooltips had [alt-.] hardcoded
1943 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
1944 # Message equal to '-' means suppress it.
1945 if ( $tooltip == '-' ) {
1950 if ( $options == 'withaccess' ) {
1951 $accesskey = self
::accesskey( $name );
1952 if ( $accesskey !== false ) {
1953 // Should be build the same as in jquery.accessKeyLabel.js
1954 if ( $tooltip === false ||
$tooltip === '' ) {
1955 $tooltip = wfMessage( 'brackets', $accesskey )->text();
1957 $tooltip .= wfMessage( 'word-separator' )->text();
1958 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
1966 public static $accesskeycache;
1969 * Given the id of an interface element, constructs the appropriate
1970 * accesskey attribute from the system messages. (Note, this is usually
1971 * the id but isn't always, because sometimes the accesskey needs to go on
1972 * a different element than the id, for reverse-compatibility, etc.)
1975 * @param string $name Id of the element, minus prefixes.
1976 * @return string Contents of the accesskey attribute (which you must HTML-
1977 * escape), or false for no accesskey attribute
1979 public static function accesskey( $name ) {
1980 if ( isset( self
::$accesskeycache[$name] ) ) {
1981 return self
::$accesskeycache[$name];
1984 $message = wfMessage( "accesskey-$name" );
1986 if ( !$message->exists() ) {
1989 $accesskey = $message->plain();
1990 if ( $accesskey === '' ||
$accesskey === '-' ) {
1991 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
1992 # attribute, but this is broken for accesskey: that might be a useful
1998 self
::$accesskeycache[$name] = $accesskey;
1999 return self
::$accesskeycache[$name];
2003 * Get a revision-deletion link, or disabled link, or nothing, depending
2004 * on user permissions & the settings on the revision.
2006 * Will use forward-compatible revision ID in the Special:RevDelete link
2007 * if possible, otherwise the timestamp-based ID which may break after
2011 * @param Revision $rev
2012 * @param Title $title
2013 * @return string HTML fragment
2015 public static function getRevDeleteLink( User
$user, Revision
$rev, Title
$title ) {
2016 $canHide = $user->isAllowed( 'deleterevision' );
2017 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2021 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
2022 return Linker
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2024 if ( $rev->getId() ) {
2025 // RevDelete links using revision ID are stable across
2026 // page deletion and undeletion; use when possible.
2028 'type' => 'revision',
2029 'target' => $title->getPrefixedDBkey(),
2030 'ids' => $rev->getId()
2033 // Older deleted entries didn't save a revision ID.
2034 // We have to refer to these by timestamp, ick!
2036 'type' => 'archive',
2037 'target' => $title->getPrefixedDBkey(),
2038 'ids' => $rev->getTimestamp()
2041 return Linker
::revDeleteLink( $query,
2042 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
2047 * Creates a (show/hide) link for deleting revisions/log entries
2049 * @param array $query Query parameters to be passed to link()
2050 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2051 * @param bool $delete Set to true to use (show/hide) rather than (show)
2053 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2054 * span to allow for customization of appearance with CSS
2056 public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2057 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
2058 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2059 $html = wfMessage( $msgKey )->escaped();
2060 $tag = $restricted ?
'strong' : 'span';
2061 $link = self
::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2064 [ 'class' => 'mw-revdelundel-link' ],
2065 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2070 * Creates a dead (show/hide) link for deleting revisions/log entries
2073 * @param bool $delete Set to true to use (show/hide) rather than (show)
2075 * @return string HTML text wrapped in a span to allow for customization
2076 * of appearance with CSS
2078 public static function revDeleteLinkDisabled( $delete = true ) {
2079 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2080 $html = wfMessage( $msgKey )->escaped();
2081 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2082 return Xml
::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2085 /* Deprecated methods */
2088 * Returns the attributes for the tooltip and access key.
2090 * @since 1.16.3. $msgParams introduced in 1.27
2091 * @param string $name
2092 * @param array $msgParams Params for constructing the message
2096 public static function tooltipAndAccesskeyAttribs( $name, array $msgParams = [] ) {
2097 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2098 # no attribute" instead of "output '' as value for attribute", this
2099 # would be three lines.
2101 'title' => self
::titleAttrib( $name, 'withaccess', $msgParams ),
2102 'accesskey' => self
::accesskey( $name )
2104 if ( $attribs['title'] === false ) {
2105 unset( $attribs['title'] );
2107 if ( $attribs['accesskey'] === false ) {
2108 unset( $attribs['accesskey'] );
2114 * Returns raw bits of HTML, use titleAttrib()
2116 * @param string $name
2117 * @param array|null $options
2118 * @return null|string
2120 public static function tooltip( $name, $options = null ) {
2121 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2122 # no attribute" instead of "output '' as value for attribute", this
2123 # would be two lines.
2124 $tooltip = self
::titleAttrib( $name, $options );
2125 if ( $tooltip === false ) {
2128 return Xml
::expandAttributes( [