3 * Methods to make links and related items.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 use MediaWiki\Linker\LinkTarget
;
23 use MediaWiki\MediaWikiServices
;
26 * Some internal bits split of from Skin.php. These functions are used
27 * for primarily page content: links, embedded images, table of contents. Links
28 * are also used in the skin.
30 * @todo turn this into a legacy interface for HtmlPageLinkRenderer and similar services.
36 * Flags for userToolLinks()
38 const TOOL_LINKS_NOBLOCK
= 1;
39 const TOOL_LINKS_EMAIL
= 2;
42 * This function returns an HTML link to the given target. It serves a few
44 * 1) If $target is a LinkTarget, the correct URL to link to will be figured
46 * 2) It automatically adds the usual classes for various types of link
47 * targets: "new" for red links, "stub" for short articles, etc.
48 * 3) It escapes all attribute values safely so there's no risk of XSS.
49 * 4) It provides a default tooltip if the target is a LinkTarget (the page
50 * name of the target).
51 * link() replaces the old functions in the makeLink() family.
53 * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
54 * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
56 * @param LinkTarget $target Can currently only be a LinkTarget, but this may
57 * change to support Images, literal URLs, etc.
58 * @param string $html The HTML contents of the <a> element, i.e.,
59 * the link text. This is raw HTML and will not be escaped. If null,
60 * defaults to the prefixed text of the LinkTarget; or if the LinkTarget is just a
61 * fragment, the contents of the fragment.
62 * @param array $customAttribs A key => value array of extra HTML attributes,
63 * such as title and class. (href is ignored.) Classes will be
64 * merged with the default classes, while other attributes will replace
65 * default attributes. All passed attribute values will be HTML-escaped.
66 * A false attribute value means to suppress that attribute.
67 * @param array $query The query string to append to the URL
68 * you're linking to, in key => value array form. Query keys and values
69 * will be URL-encoded.
70 * @param string|array $options String or array of strings:
71 * 'known': Page is known to exist, so don't check if it does.
72 * 'broken': Page is known not to exist, so don't check if it does.
73 * 'noclasses': Don't add any classes automatically (includes "new",
74 * "stub", "mw-redirect", "extiw"). Only use the class attribute
75 * provided, if any, so you get a simple blue link with no funny i-
77 * 'forcearticlepath': Use the article path always, even with a querystring.
78 * Has compatibility issues on some setups, so avoid wherever possible.
79 * 'http': Force a full URL with http:// as the scheme.
80 * 'https': Force a full URL with https:// as the scheme.
81 * 'stubThreshold' => (int): Stub threshold to use when determining link classes.
82 * @return string HTML <a> attribute
84 public static function link(
85 $target, $html = null, $customAttribs = [], $query = [], $options = []
87 if ( !$target instanceof LinkTarget
) {
88 wfWarn( __METHOD__
. ': Requires $target to be a LinkTarget object.', 2 );
89 return "<!-- ERROR -->$html";
92 $services = MediaWikiServices
::getInstance();
93 $options = (array)$options;
95 // Custom options, create new LinkRenderer
96 if ( !isset( $options['stubThreshold'] ) ) {
97 $defaultLinkRenderer = $services->getLinkRenderer();
98 $options['stubThreshold'] = $defaultLinkRenderer->getStubThreshold();
100 $linkRenderer = $services->getLinkRendererFactory()
101 ->createFromLegacyOptions( $options );
103 $linkRenderer = $services->getLinkRenderer();
106 if ( $html !== null ) {
107 $text = new HtmlArmor( $html );
112 if ( in_array( 'known', $options, true ) ) {
113 return $linkRenderer->makeKnownLink( $target, $text, $customAttribs, $query );
116 if ( in_array( 'broken', $options, true ) ) {
117 return $linkRenderer->makeBrokenLink( $target, $text, $customAttribs, $query );
120 if ( in_array( 'noclasses', $options, true ) ) {
121 return $linkRenderer->makePreloadedLink( $target, $text, '', $customAttribs, $query );
124 return $linkRenderer->makeLink( $target, $text, $customAttribs, $query );
128 * Identical to link(), except $options defaults to 'known'.
131 * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
133 * @param LinkTarget $target
134 * @param string $html
135 * @param array $customAttribs
136 * @param array $query
137 * @param string|array $options
140 public static function linkKnown(
141 $target, $html = null, $customAttribs = [],
142 $query = [], $options = [ 'known' ]
144 return self
::link( $target, $html, $customAttribs, $query, $options );
148 * Make appropriate markup for a link to the current article. This is since
149 * MediaWiki 1.29.0 rendered as an <a> tag without an href and with a class
150 * showing the link text. The calling sequence is the same as for the other
151 * make*LinkObj static functions, but $query is not used.
154 * @param LinkTarget $nt
155 * @param string $html [optional]
156 * @param string $query [optional]
157 * @param string $trail [optional]
158 * @param string $prefix [optional]
162 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
163 $nt = Title
::newFromLinkTarget( $nt );
164 $ret = "<a class=\"mw-selflink selflink\">{$prefix}{$html}</a>{$trail}";
165 if ( !Hooks
::run( 'SelfLinkBegin', [ $nt, &$html, &$trail, &$prefix, &$ret ] ) ) {
170 $html = htmlspecialchars( $nt->getPrefixedText() );
172 list( $inside, $trail ) = self
::splitTrail( $trail );
173 return "<a class=\"mw-selflink selflink\">{$prefix}{$html}{$inside}</a>{$trail}";
177 * Get a message saying that an invalid title was encountered.
178 * This should be called after a method like Title::makeTitleSafe() returned
179 * a value indicating that the title object is invalid.
181 * @param IContextSource $context Context to use to get the messages
182 * @param int $namespace Namespace number
183 * @param string $title Text of the title, without the namespace part
186 public static function getInvalidTitleDescription( IContextSource
$context, $namespace, $title ) {
187 // First we check whether the namespace exists or not.
188 if ( MediaWikiServices
::getInstance()->getNamespaceInfo()->exists( $namespace ) ) {
189 if ( $namespace == NS_MAIN
) {
190 $name = $context->msg( 'blanknamespace' )->text();
192 $name = MediaWikiServices
::getInstance()->getContentLanguage()->
193 getFormattedNsText( $namespace );
195 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
198 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
203 * @param LinkTarget $target
206 public static function normaliseSpecialPage( LinkTarget
$target ) {
207 if ( $target->getNamespace() == NS_SPECIAL
&& !$target->isExternal() ) {
208 list( $name, $subpage ) = MediaWikiServices
::getInstance()->getSpecialPageFactory()->
209 resolveAlias( $target->getDBkey() );
211 return SpecialPage
::getTitleValueFor( $name, $subpage, $target->getFragment() );
219 * Returns the filename part of an url.
220 * Used as alternative text for external images.
226 private static function fnamePart( $url ) {
227 $basename = strrchr( $url, '/' );
228 if ( $basename === false ) {
231 $basename = substr( $basename, 1 );
237 * Return the code for images which were added via external links,
238 * via Parser::maybeMakeExternalImage().
246 public static function makeExternalImage( $url, $alt = '' ) {
248 $alt = self
::fnamePart( $url );
251 $success = Hooks
::run( 'LinkerMakeExternalImage', [ &$url, &$alt, &$img ] );
253 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
254 . "with url {$url} and alt text {$alt} to {$img}\n", true );
257 return Html
::element( 'img',
266 * Given parameters derived from [[Image:Foo|options...]], generate the
267 * HTML that that syntax inserts in the page.
269 * @param Parser $parser
270 * @param LinkTarget $title LinkTarget object of the file (not the currently viewed page)
271 * @param File $file File object, or false if it doesn't exist
272 * @param array $frameParams Associative array of parameters external to the media handler.
273 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
274 * will often be false.
275 * thumbnail If present, downscale and frame
276 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
277 * framed Shows image in original size in a frame
278 * frameless Downscale but don't frame
279 * upright If present, tweak default sizes for portrait orientation
280 * upright_factor Fudge factor for "upright" tweak (default 0.75)
281 * border If present, show a border around the image
282 * align Horizontal alignment (left, right, center, none)
283 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
284 * bottom, text-bottom)
285 * alt Alternate text for image (i.e. alt attribute). Plain text.
286 * class HTML for image classes. Plain text.
287 * caption HTML for image caption.
288 * link-url URL to link to
289 * link-title LinkTarget object to link to
290 * link-target Value for the target attribute, only with link-url
291 * no-link Boolean, suppress description link
292 * targetlang (optional) Target language code, see Parser::getTargetLanguage()
294 * @param array $handlerParams Associative array of media handler parameters, to be passed
295 * to transform(). Typical keys are "width" and "page".
296 * @param string|bool $time Timestamp of the file, set as false for current
297 * @param string $query Query params for desc url
298 * @param int|null $widthOption Used by the parser to remember the user preference thumbnailsize
300 * @return string HTML for an image, with links, wrappers, etc.
302 public static function makeImageLink( Parser
$parser, LinkTarget
$title,
303 $file, $frameParams = [], $handlerParams = [], $time = false,
304 $query = "", $widthOption = null
306 $title = Title
::newFromLinkTarget( $title );
308 $dummy = new DummyLinker
;
309 if ( !Hooks
::run( 'ImageBeforeProduceHTML', [ &$dummy, &$title,
310 &$file, &$frameParams, &$handlerParams, &$time, &$res,
311 $parser, &$query, &$widthOption
316 if ( $file && !$file->allowInlineDisplay() ) {
317 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
318 return self
::link( $title );
321 // Clean up parameters
322 $page = $handlerParams['page'] ??
false;
323 if ( !isset( $frameParams['align'] ) ) {
324 $frameParams['align'] = '';
326 if ( !isset( $frameParams['alt'] ) ) {
327 $frameParams['alt'] = '';
329 if ( !isset( $frameParams['title'] ) ) {
330 $frameParams['title'] = '';
332 if ( !isset( $frameParams['class'] ) ) {
333 $frameParams['class'] = '';
336 $prefix = $postfix = '';
338 if ( $frameParams['align'] == 'center' ) {
339 $prefix = '<div class="center">';
341 $frameParams['align'] = 'none';
343 if ( $file && !isset( $handlerParams['width'] ) ) {
344 if ( isset( $handlerParams['height'] ) && $file->isVectorized() ) {
345 // If its a vector image, and user only specifies height
346 // we don't want it to be limited by its "normal" width.
347 global $wgSVGMaxSize;
348 $handlerParams['width'] = $wgSVGMaxSize;
350 $handlerParams['width'] = $file->getWidth( $page );
353 if ( isset( $frameParams['thumbnail'] )
354 ||
isset( $frameParams['manualthumb'] )
355 ||
isset( $frameParams['framed'] )
356 ||
isset( $frameParams['frameless'] )
357 ||
!$handlerParams['width']
359 global $wgThumbLimits, $wgThumbUpright;
361 if ( $widthOption === null ||
!isset( $wgThumbLimits[$widthOption] ) ) {
362 $widthOption = User
::getDefaultOption( 'thumbsize' );
365 // Reduce width for upright images when parameter 'upright' is used
366 if ( isset( $frameParams['upright'] ) && $frameParams['upright'] == 0 ) {
367 $frameParams['upright'] = $wgThumbUpright;
370 // For caching health: If width scaled down due to upright
371 // parameter, round to full __0 pixel to avoid the creation of a
372 // lot of odd thumbs.
373 $prefWidth = isset( $frameParams['upright'] ) ?
374 round( $wgThumbLimits[$widthOption] * $frameParams['upright'], -1 ) :
375 $wgThumbLimits[$widthOption];
377 // Use width which is smaller: real image width or user preference width
378 // Unless image is scalable vector.
379 if ( !isset( $handlerParams['height'] ) && ( $handlerParams['width'] <= 0 ||
380 $prefWidth < $handlerParams['width'] ||
$file->isVectorized() ) ) {
381 $handlerParams['width'] = $prefWidth;
386 if ( isset( $frameParams['thumbnail'] ) ||
isset( $frameParams['manualthumb'] )
387 ||
isset( $frameParams['framed'] )
389 # Create a thumbnail. Alignment depends on the writing direction of
390 # the page content language (right-aligned for LTR languages,
391 # left-aligned for RTL languages)
392 # If a thumbnail width has not been provided, it is set
393 # to the default user option as specified in Language*.php
394 if ( $frameParams['align'] == '' ) {
395 $frameParams['align'] = $parser->getTargetLanguage()->alignEnd();
398 self
::makeThumbLink2( $title, $file, $frameParams, $handlerParams, $time, $query ) .
402 if ( $file && isset( $frameParams['frameless'] ) ) {
403 $srcWidth = $file->getWidth( $page );
404 # For "frameless" option: do not present an image bigger than the
405 # source (for bitmap-style images). This is the same behavior as the
406 # "thumb" option does it already.
407 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
408 $handlerParams['width'] = $srcWidth;
412 if ( $file && isset( $handlerParams['width'] ) ) {
413 # Create a resized image, without the additional thumbnail features
414 $thumb = $file->transform( $handlerParams );
420 $s = self
::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
422 self
::processResponsiveImages( $file, $thumb, $handlerParams );
424 'alt' => $frameParams['alt'],
425 'title' => $frameParams['title'],
426 'valign' => $frameParams['valign'] ??
false,
427 'img-class' => $frameParams['class'] ];
428 if ( isset( $frameParams['border'] ) ) {
429 $params['img-class'] .= ( $params['img-class'] !== '' ?
' ' : '' ) . 'thumbborder';
431 $params = self
::getImageLinkMTOParams( $frameParams, $query, $parser ) +
$params;
433 $s = $thumb->toHtml( $params );
435 if ( $frameParams['align'] != '' ) {
436 $s = Html
::rawElement(
438 [ 'class' => 'float' . $frameParams['align'] ],
442 return str_replace( "\n", ' ', $prefix . $s . $postfix );
446 * Get the link parameters for MediaTransformOutput::toHtml() from given
447 * frame parameters supplied by the Parser.
448 * @param array $frameParams The frame parameters
449 * @param string $query An optional query string to add to description page links
450 * @param Parser|null $parser
453 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
455 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
456 $mtoParams['custom-url-link'] = $frameParams['link-url'];
457 if ( isset( $frameParams['link-target'] ) ) {
458 $mtoParams['custom-target-link'] = $frameParams['link-target'];
461 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
462 foreach ( $extLinkAttrs as $name => $val ) {
463 // Currently could include 'rel' and 'target'
464 $mtoParams['parser-extlink-' . $name] = $val;
467 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
468 $mtoParams['custom-title-link'] = Title
::newFromLinkTarget(
469 self
::normaliseSpecialPage( $frameParams['link-title'] )
471 } elseif ( !empty( $frameParams['no-link'] ) ) {
474 $mtoParams['desc-link'] = true;
475 $mtoParams['desc-query'] = $query;
481 * Make HTML for a thumbnail including image, border and caption
482 * @param LinkTarget $title
483 * @param File|bool $file File object or false if it doesn't exist
484 * @param string $label
486 * @param string $align
487 * @param array $params
488 * @param bool $framed
489 * @param string $manualthumb
492 public static function makeThumbLinkObj( LinkTarget
$title, $file, $label = '', $alt = '',
493 $align = 'right', $params = [], $framed = false, $manualthumb = ""
501 $frameParams['framed'] = true;
503 if ( $manualthumb ) {
504 $frameParams['manualthumb'] = $manualthumb;
506 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
510 * @param LinkTarget $title
512 * @param array $frameParams
513 * @param array $handlerParams
515 * @param string $query
518 public static function makeThumbLink2( LinkTarget
$title, $file, $frameParams = [],
519 $handlerParams = [], $time = false, $query = ""
521 $exists = $file && $file->exists();
523 $page = $handlerParams['page'] ??
false;
524 if ( !isset( $frameParams['align'] ) ) {
525 $frameParams['align'] = 'right';
527 if ( !isset( $frameParams['alt'] ) ) {
528 $frameParams['alt'] = '';
530 if ( !isset( $frameParams['title'] ) ) {
531 $frameParams['title'] = '';
533 if ( !isset( $frameParams['caption'] ) ) {
534 $frameParams['caption'] = '';
537 if ( empty( $handlerParams['width'] ) ) {
538 // Reduce width for upright images when parameter 'upright' is used
539 $handlerParams['width'] = isset( $frameParams['upright'] ) ?
130 : 180;
543 $manualthumb = false;
546 $outerWidth = $handlerParams['width'] +
2;
548 if ( isset( $frameParams['manualthumb'] ) ) {
549 # Use manually specified thumbnail
550 $manual_title = Title
::makeTitleSafe( NS_FILE
, $frameParams['manualthumb'] );
551 if ( $manual_title ) {
552 $manual_img = MediaWikiServices
::getInstance()->getRepoGroup()
553 ->findFile( $manual_title );
555 $thumb = $manual_img->getUnscaledThumb( $handlerParams );
561 } elseif ( isset( $frameParams['framed'] ) ) {
562 // Use image dimensions, don't scale
563 $thumb = $file->getUnscaledThumb( $handlerParams );
566 # Do not present an image bigger than the source, for bitmap-style images
567 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
568 $srcWidth = $file->getWidth( $page );
569 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
570 $handlerParams['width'] = $srcWidth;
572 $thumb = $file->transform( $handlerParams );
576 $outerWidth = $thumb->getWidth() +
2;
578 $outerWidth = $handlerParams['width'] +
2;
582 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
583 # So we don't need to pass it here in $query. However, the URL for the
584 # zoom icon still needs it, so we make a unique query for it. See T16771
585 $url = Title
::newFromLinkTarget( $title )->getLocalURL( $query );
587 $url = wfAppendQuery( $url, [ 'page' => $page ] );
590 && !isset( $frameParams['link-title'] )
591 && !isset( $frameParams['link-url'] )
592 && !isset( $frameParams['no-link'] ) ) {
593 $frameParams['link-url'] = $url;
596 $s = "<div class=\"thumb t{$frameParams['align']}\">"
597 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
600 $s .= self
::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
602 } elseif ( !$thumb ) {
603 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
606 if ( !$noscale && !$manualthumb ) {
607 self
::processResponsiveImages( $file, $thumb, $handlerParams );
610 'alt' => $frameParams['alt'],
611 'title' => $frameParams['title'],
612 'img-class' => ( isset( $frameParams['class'] ) && $frameParams['class'] !== ''
613 ?
$frameParams['class'] . ' '
614 : '' ) . 'thumbimage'
616 $params = self
::getImageLinkMTOParams( $frameParams, $query ) +
$params;
617 $s .= $thumb->toHtml( $params );
618 if ( isset( $frameParams['framed'] ) ) {
621 $zoomIcon = Html
::rawElement( 'div', [ 'class' => 'magnify' ],
622 Html
::rawElement( 'a', [
624 'class' => 'internal',
625 'title' => wfMessage( 'thumbnail-more' )->text() ],
629 $s .= ' <div class="thumbcaption">' . $zoomIcon . $frameParams['caption'] . "</div></div></div>";
630 return str_replace( "\n", ' ', $s );
634 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
638 * @param MediaTransformOutput $thumb
639 * @param array $hp Image parameters
641 public static function processResponsiveImages( $file, $thumb, $hp ) {
642 global $wgResponsiveImages;
643 if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
645 $hp15['width'] = round( $hp['width'] * 1.5 );
647 $hp20['width'] = $hp['width'] * 2;
648 if ( isset( $hp['height'] ) ) {
649 $hp15['height'] = round( $hp['height'] * 1.5 );
650 $hp20['height'] = $hp['height'] * 2;
653 $thumb15 = $file->transform( $hp15 );
654 $thumb20 = $file->transform( $hp20 );
655 if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
656 $thumb->responsiveUrls
['1.5'] = $thumb15->getUrl();
658 if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
659 $thumb->responsiveUrls
['2'] = $thumb20->getUrl();
665 * Make a "broken" link to an image
668 * @param LinkTarget $title
669 * @param string $label Link label (plain text)
670 * @param string $query Query string
671 * @param string $unused1 Unused parameter kept for b/c
672 * @param string $unused2 Unused parameter kept for b/c
673 * @param bool $time A file of a certain timestamp was requested
676 public static function makeBrokenImageLinkObj( $title, $label = '',
677 $query = '', $unused1 = '', $unused2 = '', $time = false
679 if ( !$title instanceof LinkTarget
) {
680 wfWarn( __METHOD__
. ': Requires $title to be a LinkTarget object.' );
681 return "<!-- ERROR -->" . htmlspecialchars( $label );
684 $title = Title
::castFromLinkTarget( $title );
686 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
687 if ( $label == '' ) {
688 $label = $title->getPrefixedText();
690 $encLabel = htmlspecialchars( $label );
691 $currentExists = $time
692 && MediaWikiServices
::getInstance()->getRepoGroup()->findFile( $title ) !== 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 LinkTarget $destFile LinkTarget 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=' . Title
::castFromLinkTarget( $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 LinkTarget $title
754 * @param string $html Pre-sanitized HTML
755 * @param string|false $time MW timestamp of file creation time
756 * @return string HTML
758 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
759 $img = MediaWikiServices
::getInstance()->getRepoGroup()->findFile(
760 $title, [ 'time' => $time ]
762 return self
::makeMediaLinkFile( $title, $img, $html );
766 * Create a direct link to a given uploaded file.
767 * This will make a broken link if $file is false.
770 * @param LinkTarget $title
771 * @param File|bool $file File object or false
772 * @param string $html Pre-sanitized HTML
773 * @return string HTML
775 * @todo Handle invalid or missing images better.
777 public static function makeMediaLinkFile( LinkTarget
$title, $file, $html = '' ) {
778 if ( $file && $file->exists() ) {
779 $url = $file->getUrl();
782 $url = self
::getUploadUrl( $title );
786 $alt = $title->getText();
798 if ( !Hooks
::run( 'LinkerMakeMediaLinkFile',
799 [ Title
::castFromLinkTarget( $title ), $file, &$html, &$attribs, &$ret ] ) ) {
800 wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
801 . "with url {$url} and text {$html} to {$ret}\n", true );
805 return Html
::rawElement( 'a', $attribs, $html );
809 * Make a link to a special page given its name and, optionally,
810 * a message key from the link text.
811 * Usage example: Linker::specialLink( 'Recentchanges' )
814 * @param string $name
818 public static function specialLink( $name, $key = '' ) {
820 $key = strtolower( $name );
823 return self
::linkKnown( SpecialPage
::getTitleFor( $name ), wfMessage( $key )->escaped() );
827 * Make an external link
829 * @since 1.16.3. $title added in 1.21
830 * @param string $url URL to link to
831 * @param-taint $url escapes_html
832 * @param string $text Text of link
833 * @param-taint $text escapes_html
834 * @param bool $escape Do we escape the link text?
835 * @param-taint $escape none
836 * @param string $linktype Type of external link. Gets added to the classes
837 * @param-taint $linktype escapes_html
838 * @param array $attribs Array of extra attributes to <a>
839 * @param-taint $attribs escapes_html
840 * @param LinkTarget|null $title LinkTarget object used for title specific link attributes
841 * @param-taint $title none
844 public static function makeExternalLink( $url, $text, $escape = true,
845 $linktype = '', $attribs = [], $title = null
850 $class .= " $linktype";
852 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
853 $class .= " {$attribs['class']}";
855 $attribs['class'] = $class;
858 $text = htmlspecialchars( $text );
864 $newRel = Parser
::getExternalLinkRel( $url, $title );
865 if ( !isset( $attribs['rel'] ) ||
$attribs['rel'] === '' ) {
866 $attribs['rel'] = $newRel;
867 } elseif ( $newRel !== '' ) {
868 // Merge the rel attributes.
869 $newRels = explode( ' ', $newRel );
870 $oldRels = explode( ' ', $attribs['rel'] );
871 $combined = array_unique( array_merge( $newRels, $oldRels ) );
872 $attribs['rel'] = implode( ' ', $combined );
875 $success = Hooks
::run( 'LinkerMakeExternalLink',
876 [ &$url, &$text, &$link, &$attribs, $linktype ] );
878 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
879 . "with url {$url} and text {$text} to {$link}\n", true );
882 $attribs['href'] = $url;
883 return Html
::rawElement( 'a', $attribs, $text );
887 * Make user link (or user contributions for unregistered users)
888 * @param int $userId User id in database.
889 * @param string $userName User name in database.
890 * @param string $altUserName Text to display instead of the user name (optional)
891 * @return string HTML fragment
892 * @since 1.16.3. $altUserName was added in 1.19.
894 public static function userLink( $userId, $userName, $altUserName = false ) {
895 if ( $userName === '' ||
$userName === false ||
$userName === null ) {
896 wfDebug( __METHOD__
. ' received an empty username. Are there database errors ' .
897 'that need to be fixed?' );
898 return wfMessage( 'empty-username' )->parse();
901 $classes = 'mw-userlink';
903 if ( $userId == 0 ) {
904 $page = ExternalUserNames
::getUserLinkTitle( $userName );
906 if ( ExternalUserNames
::isExternal( $userName ) ) {
907 $classes .= ' mw-extuserlink';
908 } elseif ( $altUserName === false ) {
909 $altUserName = IP
::prettifyIP( $userName );
911 $classes .= ' mw-anonuserlink'; // Separate link class for anons (T45179)
913 $page = new TitleValue( NS_USER
, strtr( $userName, ' ', '_' ) );
916 // Wrap the output with <bdi> tags for directionality isolation
918 '<bdi>' . htmlspecialchars( $altUserName !== false ?
$altUserName : $userName ) . '</bdi>';
921 ? self
::link( $page, $linkText, [ 'class' => $classes ] )
922 : Html
::rawElement( 'span', [ 'class' => $classes ], $linkText );
926 * Generate standard user tool links (talk, contributions, block link, etc.)
929 * @param int $userId User identifier
930 * @param string $userText User name or IP address
931 * @param bool $redContribsWhenNoEdits Should the contributions link be
932 * red if the user has no edits?
933 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
934 * and Linker::TOOL_LINKS_EMAIL).
935 * @param int|null $edits User edit count (optional, for performance)
936 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
937 * @return string HTML fragment
939 public static function userToolLinks(
940 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null,
941 $useParentheses = true
943 if ( $userText === '' ) {
944 wfDebug( __METHOD__
. ' received an empty username. Are there database errors ' .
945 'that need to be fixed?' );
946 return ' ' . wfMessage( 'empty-username' )->parse();
949 global $wgUser, $wgDisableAnonTalk, $wgLang;
950 $talkable = !( $wgDisableAnonTalk && $userId == 0 );
951 $blockable = !( $flags & self
::TOOL_LINKS_NOBLOCK
);
952 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
&& $userId;
954 if ( $userId == 0 && ExternalUserNames
::isExternal( $userText ) ) {
955 // No tools for an external user
961 $items[] = self
::userTalkLink( $userId, $userText );
964 // check if the user has an edit
966 $attribs['class'] = 'mw-usertoollinks-contribs';
967 if ( $redContribsWhenNoEdits ) {
968 if ( intval( $edits ) === 0 && $edits !== 0 ) {
969 $user = User
::newFromId( $userId );
970 $edits = $user->getEditCount();
972 if ( $edits === 0 ) {
973 $attribs['class'] .= ' new';
976 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
978 $items[] = self
::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
980 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
981 $items[] = self
::blockLink( $userId, $userText );
984 if ( $addEmailLink && $wgUser->canSendEmail() ) {
985 $items[] = self
::emailLink( $userId, $userText );
988 Hooks
::run( 'UserToolLinksEdit', [ $userId, $userText, &$items ] );
994 if ( $useParentheses ) {
995 return wfMessage( 'word-separator' )->escaped()
996 . '<span class="mw-usertoollinks">'
997 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1002 foreach ( $items as $tool ) {
1003 $tools[] = Html
::rawElement( 'span', [], $tool );
1005 return ' <span class="mw-usertoollinks mw-changeslist-links">' .
1006 implode( ' ', $tools ) . '</span>';
1010 * Alias for userToolLinks( $userId, $userText, true );
1012 * @param int $userId User identifier
1013 * @param string $userText User name or IP address
1014 * @param int|null $edits User edit count (optional, for performance)
1015 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
1018 public static function userToolLinksRedContribs(
1019 $userId, $userText, $edits = null, $useParentheses = true
1021 return self
::userToolLinks( $userId, $userText, true, 0, $edits, $useParentheses );
1026 * @param int $userId User id in database.
1027 * @param string $userText User name in database.
1028 * @return string HTML fragment with user talk link
1030 public static function userTalkLink( $userId, $userText ) {
1031 if ( $userText === '' ) {
1032 wfDebug( __METHOD__
. ' received an empty username. Are there database errors ' .
1033 'that need to be fixed?' );
1034 return wfMessage( 'empty-username' )->parse();
1037 $userTalkPage = new TitleValue( NS_USER_TALK
, strtr( $userText, ' ', '_' ) );
1038 $moreLinkAttribs['class'] = 'mw-usertoollinks-talk';
1040 return self
::link( $userTalkPage,
1041 wfMessage( 'talkpagelinktext' )->escaped(),
1048 * @param int $userId
1049 * @param string $userText User name in database.
1050 * @return string HTML fragment with block link
1052 public static function blockLink( $userId, $userText ) {
1053 if ( $userText === '' ) {
1054 wfDebug( __METHOD__
. ' received an empty username. Are there database errors ' .
1055 'that need to be fixed?' );
1056 return wfMessage( 'empty-username' )->parse();
1059 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1060 $moreLinkAttribs['class'] = 'mw-usertoollinks-block';
1062 return self
::link( $blockPage,
1063 wfMessage( 'blocklink' )->escaped(),
1069 * @param int $userId
1070 * @param string $userText User name in database.
1071 * @return string HTML fragment with e-mail user link
1073 public static function emailLink( $userId, $userText ) {
1074 if ( $userText === '' ) {
1075 wfLogWarning( __METHOD__
. ' received an empty username. Are there database errors ' .
1076 'that need to be fixed?' );
1077 return wfMessage( 'empty-username' )->parse();
1080 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1081 $moreLinkAttribs['class'] = 'mw-usertoollinks-mail';
1082 return self
::link( $emailPage,
1083 wfMessage( 'emaillink' )->escaped(),
1089 * Generate a user link if the current user is allowed to view it
1091 * @param Revision $rev
1092 * @param bool $isPublic Show only if all users can see it
1093 * @return string HTML fragment
1095 public static function revUserLink( $rev, $isPublic = false ) {
1096 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1097 $link = wfMessage( 'rev-deleted-user' )->escaped();
1098 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1099 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1100 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1102 $link = wfMessage( 'rev-deleted-user' )->escaped();
1104 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1105 return '<span class="history-deleted">' . $link . '</span>';
1111 * Generate a user tool link cluster if the current user is allowed to view it
1113 * @param Revision $rev
1114 * @param bool $isPublic Show only if all users can see it
1115 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
1116 * @return string HTML
1118 public static function revUserTools( $rev, $isPublic = false, $useParentheses = true ) {
1119 if ( $rev->userCan( Revision
::DELETED_USER
) &&
1120 ( !$rev->isDeleted( Revision
::DELETED_USER
) ||
!$isPublic )
1122 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1123 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1124 if ( $userId ||
(string)$userText !== '' ) {
1125 $link = self
::userLink( $userId, $userText )
1126 . self
::userToolLinks( $userId, $userText, false, 0, null,
1131 if ( !isset( $link ) ) {
1132 $link = wfMessage( 'rev-deleted-user' )->escaped();
1135 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1136 return ' <span class="history-deleted mw-userlink">' . $link . '</span>';
1142 * This function is called by all recent changes variants, by the page history,
1143 * and by the user contributions list. It is responsible for formatting edit
1144 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1145 * auto-generated comments (from section editing) and formats [[wikilinks]].
1147 * @author Erik Moeller <moeller@scireview.de>
1148 * @since 1.16.3. $wikiId added in 1.26
1150 * @param string $comment
1151 * @param LinkTarget|null $title LinkTarget object (to generate link to the section in
1152 * autocomment) or null
1153 * @param bool $local Whether section links should refer to local page
1154 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1155 * For use with external changes.
1157 * @return string HTML
1159 public static function formatComment(
1160 $comment, $title = null, $local = false, $wikiId = null
1162 # Sanitize text a bit:
1163 $comment = str_replace( "\n", " ", $comment );
1164 # Allow HTML entities (for T15815)
1165 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1167 # Render autocomments and make links:
1168 $comment = self
::formatAutocomments( $comment, $title, $local, $wikiId );
1169 return self
::formatLinksInComment( $comment, $title, $local, $wikiId );
1173 * Converts autogenerated comments in edit summaries into section links.
1175 * The pattern for autogen comments is / * foo * /, which makes for
1177 * We look for all comments, match any text before and after the comment,
1178 * add a separator where needed and format the comment itself with CSS
1179 * Called by Linker::formatComment.
1181 * @param string $comment Comment text
1182 * @param LinkTarget|null $title An optional LinkTarget object used to links to sections
1183 * @param bool $local Whether section links should refer to local page
1184 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1185 * as used by WikiMap.
1187 * @return string Formatted comment (wikitext)
1189 private static function formatAutocomments(
1190 $comment, $title = null, $local = false, $wikiId = null
1192 // @todo $append here is something of a hack to preserve the status
1193 // quo. Someone who knows more about bidi and such should decide
1194 // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1195 // wiki, both when autocomments exist and when they don't, and
1196 // (2) what markup will make that actually happen.
1198 $comment = preg_replace_callback(
1199 // To detect the presence of content before or after the
1200 // auto-comment, we use capturing groups inside optional zero-width
1201 // assertions. But older versions of PCRE can't directly make
1202 // zero-width assertions optional, so wrap them in a non-capturing
1204 '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1205 function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1208 // Ensure all match positions are defined
1209 $match +
= [ '', '', '', '' ];
1211 $pre = $match[1] !== '';
1213 $post = $match[3] !== '';
1217 'FormatAutocomments',
1218 [ &$comment, $pre, $auto, $post, Title
::castFromLinkTarget( $title ), $local,
1222 if ( $comment === null ) {
1225 # Remove links that a user may have manually put in the autosummary
1226 # This could be improved by copying as much of Parser::stripSectionName as desired.
1227 $section = str_replace( [
1233 // We don't want any links in the auto text to be linked, but we still
1234 // want to show any [[ ]]
1235 $sectionText = str_replace( '[[', '[[', $auto );
1237 $section = substr( Parser
::guessSectionNameFromStrippedText( $section ), 1 );
1238 // Support: HHVM (T222857)
1239 // The guessSectionNameFromStrippedText method returns a non-empty string
1240 // that starts with "#". Before PHP 7 (and still on HHVM) substr() would
1241 // return false if the start offset is the end of the string.
1242 // On PHP 7+, it gracefully returns empty string instead.
1243 if ( $section !== '' && $section !== false ) {
1245 $sectionTitle = new TitleValue( NS_MAIN
, '', $section );
1247 $sectionTitle = $title->createFragmentTarget( $section );
1249 $auto = Linker
::makeCommentLink(
1251 $wgLang->getArrow() . $wgLang->getDirMark() . $sectionText,
1258 # written summary $presep autocomment (summary /* section */)
1259 $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1262 # autocomment $postsep written summary (/* section */ summary)
1263 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1266 $auto = '<span dir="auto"><span class="autocomment">' . $auto . '</span>';
1267 $append .= '</span>';
1269 $comment = $pre . $auto;
1275 return $comment . $append;
1279 * Formats wiki links and media links in text; all other wiki formatting
1282 * @since 1.16.3. $wikiId added in 1.26
1283 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1285 * @param string $comment Text to format links in. WARNING! Since the output of this
1286 * function is html, $comment must be sanitized for use as html. You probably want
1287 * to pass $comment through Sanitizer::escapeHtmlAllowEntities() before calling
1289 * @param LinkTarget|null $title An optional LinkTarget object used to links to sections
1290 * @param bool $local Whether section links should refer to local page
1291 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1292 * as used by WikiMap.
1294 * @return string HTML
1295 * @return-taint onlysafefor_html
1297 public static function formatLinksInComment(
1298 $comment, $title = null, $local = false, $wikiId = null
1300 return preg_replace_callback(
1303 \s*+ # ignore leading whitespace, the *+ quantifier disallows backtracking
1304 :? # ignore optional leading colon
1305 ([^\]|]+) # 1. link target; page names cannot include ] or |
1308 # Stop matching at ]] without relying on backtracking.
1312 ([^[]*) # 3. link trail (the text up until the next link)
1314 function ( $match ) use ( $title, $local, $wikiId ) {
1315 $services = MediaWikiServices
::getInstance();
1318 $medians .= preg_quote(
1319 $services->getNamespaceInfo()->getCanonicalName( NS_MEDIA
), '/' );
1321 $medians .= preg_quote(
1322 MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( NS_MEDIA
),
1326 $comment = $match[0];
1328 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1329 if ( strpos( $match[1], '%' ) !== false ) {
1331 rawurldecode( $match[1] ),
1332 [ '<' => '<', '>' => '>' ]
1336 # Handle link renaming [[foo|text]] will show link as "text"
1337 if ( $match[2] != "" ) {
1344 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1345 # Media link; trail not supported.
1346 $linkRegexp = '/\[\[(.*?)\]\]/';
1347 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1349 $thelink = Linker
::makeMediaLinkObj( $title, $text );
1352 # Other kind of link
1353 # Make sure its target is non-empty
1354 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1355 $match[1] = substr( $match[1], 1 );
1357 if ( $match[1] !== false && $match[1] !== '' ) {
1359 MediaWikiServices
::getInstance()->getContentLanguage()->linkTrail(),
1363 $trail = $submatch[1];
1367 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1368 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1371 $linkTarget = Linker
::normalizeSubpageLink( $title, $match[1], $linkText );
1373 Title
::newFromText( $linkTarget );
1375 $target = MediaWikiServices
::getInstance()->getTitleParser()->
1376 parseTitle( $linkTarget );
1378 if ( $target->getText() == '' && !$target->isExternal()
1379 && !$local && $title
1381 $target = $title->createFragmentTarget( $target->getFragment() );
1384 $thelink = Linker
::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1385 } catch ( MalformedTitleException
$e ) {
1391 // If the link is still valid, go ahead and replace it in!
1392 $comment = preg_replace(
1394 StringUtils
::escapeRegexReplacement( $thelink ),
1407 * Generates a link to the given LinkTarget
1409 * @note This is only public for technical reasons. It's not intended for use outside Linker.
1411 * @param LinkTarget $linkTarget
1412 * @param string $text
1413 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1414 * as used by WikiMap.
1415 * @param string|string[] $options See the $options parameter in Linker::link.
1417 * @return string HTML link
1419 public static function makeCommentLink(
1420 LinkTarget
$linkTarget, $text, $wikiId = null, $options = []
1422 if ( $wikiId !== null && !$linkTarget->isExternal() ) {
1423 $link = self
::makeExternalLink(
1424 WikiMap
::getForeignURL(
1426 $linkTarget->getNamespace() === 0
1427 ?
$linkTarget->getDBkey()
1428 : MediaWikiServices
::getInstance()->getNamespaceInfo()->
1429 getCanonicalName( $linkTarget->getNamespace() ) .
1430 ':' . $linkTarget->getDBkey(),
1431 $linkTarget->getFragment()
1434 /* escape = */ false // Already escaped
1437 $link = self
::link( $linkTarget, $text, [], [], $options );
1444 * @param LinkTarget $contextTitle
1445 * @param string $target
1446 * @param string &$text
1449 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1452 # :Foobar -- override special treatment of prefix (images, language links)
1453 # /Foobar -- convert to CurrentPage/Foobar
1454 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1455 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1456 # ../Foobar -- convert to CurrentPage/Foobar,
1457 # (from CurrentPage/CurrentSubPage)
1458 # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1459 # (from CurrentPage/CurrentSubPage)
1461 $ret = $target; # default return value is no change
1463 # Some namespaces don't allow subpages,
1464 # so only perform processing if subpages are allowed
1466 $contextTitle && MediaWikiServices
::getInstance()->getNamespaceInfo()->
1467 hasSubpages( $contextTitle->getNamespace() )
1469 $hash = strpos( $target, '#' );
1470 if ( $hash !== false ) {
1471 $suffix = substr( $target, $hash );
1472 $target = substr( $target, 0, $hash );
1477 $target = trim( $target );
1478 $contextPrefixedText = MediaWikiServices
::getInstance()->getTitleFormatter()->
1479 getPrefixedText( $contextTitle );
1480 # Look at the first character
1481 if ( $target != '' && $target[0] === '/' ) {
1482 # / at end means we don't want the slash to be shown
1484 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1485 if ( $trailingSlashes ) {
1486 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1488 $noslash = substr( $target, 1 );
1491 $ret = $contextPrefixedText . '/' . trim( $noslash ) . $suffix;
1492 if ( $text === '' ) {
1493 $text = $target . $suffix;
1494 } # this might be changed for ugliness reasons
1496 # check for .. subpage backlinks
1498 $nodotdot = $target;
1499 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1501 $nodotdot = substr( $nodotdot, 3 );
1503 if ( $dotdotcount > 0 ) {
1504 $exploded = explode( '/', $contextPrefixedText );
1505 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1506 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1507 # / at the end means don't show full path
1508 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1509 $nodotdot = rtrim( $nodotdot, '/' );
1510 if ( $text === '' ) {
1511 $text = $nodotdot . $suffix;
1514 $nodotdot = trim( $nodotdot );
1515 if ( $nodotdot != '' ) {
1516 $ret .= '/' . $nodotdot;
1528 * Wrap a comment in standard punctuation and formatting if
1529 * it's non-empty, otherwise return empty string.
1531 * @since 1.16.3. $wikiId added in 1.26
1532 * @param string $comment
1533 * @param LinkTarget|null $title LinkTarget object (to generate link to section in autocomment)
1535 * @param bool $local Whether section links should refer to local page
1536 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1537 * For use with external changes.
1541 public static function commentBlock(
1542 $comment, $title = null, $local = false, $wikiId = null, $useParentheses = true
1544 // '*' used to be the comment inserted by the software way back
1545 // in antiquity in case none was provided, here for backwards
1546 // compatibility, acc. to brion -ævar
1547 if ( $comment == '' ||
$comment == '*' ) {
1550 $formatted = self
::formatComment( $comment, $title, $local, $wikiId );
1551 if ( $useParentheses ) {
1552 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1553 $classNames = 'comment';
1555 $classNames = 'comment comment--without-parentheses';
1557 return " <span class=\"$classNames\">$formatted</span>";
1561 * Wrap and format the given revision's comment block, if the current
1562 * user is allowed to view it.
1565 * @param Revision $rev
1566 * @param bool $local Whether section links should refer to local page
1567 * @param bool $isPublic Show only if all users can see it
1568 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
1569 * @return string HTML fragment
1571 public static function revComment( Revision
$rev, $local = false, $isPublic = false,
1572 $useParentheses = true
1574 if ( $rev->getComment( Revision
::RAW
) == "" ) {
1577 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1578 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1579 } elseif ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1580 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1581 $rev->getTitle(), $local, null, $useParentheses );
1583 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1585 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1586 return " <span class=\"history-deleted comment\">$block</span>";
1596 public static function formatRevisionSize( $size ) {
1598 $stxt = wfMessage( 'historyempty' )->escaped();
1600 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1602 return "<span class=\"history-size mw-diff-bytes\">$stxt</span>";
1606 * Add another level to the Table of Contents
1611 public static function tocIndent() {
1616 * Finish one or more sublevels on the Table of Contents
1622 public static function tocUnindent( $level ) {
1623 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1627 * parameter level defines if we are on an indentation level
1630 * @param string $anchor
1631 * @param string $tocline
1632 * @param string $tocnumber
1633 * @param string $level
1634 * @param string|bool $sectionIndex
1637 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1638 $classes = "toclevel-$level";
1639 if ( $sectionIndex !== false ) {
1640 $classes .= " tocsection-$sectionIndex";
1643 // <li class="$classes"><a href="#$anchor"><span class="tocnumber">
1644 // $tocnumber</span> <span class="toctext">$tocline</span></a>
1645 return Html
::openElement( 'li', [ 'class' => $classes ] )
1646 . Html
::rawElement( 'a',
1647 [ 'href' => "#$anchor" ],
1648 Html
::element( 'span', [ 'class' => 'tocnumber' ], $tocnumber )
1650 . Html
::rawElement( 'span', [ 'class' => 'toctext' ], $tocline )
1655 * End a Table Of Contents line.
1656 * tocUnindent() will be used instead if we're ending a line below
1661 public static function tocLineEnd() {
1666 * Wraps the TOC in a table and provides the hide/collapse javascript.
1669 * @param string $toc Html of the Table Of Contents
1670 * @param Language|null $lang Language for the toc title, defaults to user language
1671 * @return string Full html of the TOC
1673 public static function tocList( $toc, Language
$lang = null ) {
1674 $lang = $lang ?? RequestContext
::getMain()->getLanguage();
1676 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1678 return '<div id="toc" class="toc">'
1679 . Html
::element( 'input', [
1680 'type' => 'checkbox',
1682 'id' => 'toctogglecheckbox',
1683 'class' => 'toctogglecheckbox',
1684 'style' => 'display:none',
1686 . Html
::openElement( 'div', [
1687 'class' => 'toctitle',
1688 'lang' => $lang->getHtmlCode(),
1689 'dir' => $lang->getDir(),
1692 . '<span class="toctogglespan">'
1693 . Html
::label( '', 'toctogglecheckbox', [
1694 'class' => 'toctogglelabel',
1699 . "</ul>\n</div>\n";
1703 * Generate a table of contents from a section tree.
1705 * @since 1.16.3. $lang added in 1.17
1706 * @param array $tree Return value of ParserOutput::getSections()
1707 * @param Language|null $lang Language for the toc title, defaults to user language
1708 * @return string HTML fragment
1710 public static function generateTOC( $tree, Language
$lang = null ) {
1713 foreach ( $tree as $section ) {
1714 if ( $section['toclevel'] > $lastLevel ) {
1715 $toc .= self
::tocIndent();
1716 } elseif ( $section['toclevel'] < $lastLevel ) {
1717 $toc .= self
::tocUnindent(
1718 $lastLevel - $section['toclevel'] );
1720 $toc .= self
::tocLineEnd();
1723 $toc .= self
::tocLine( $section['anchor'],
1724 $section['line'], $section['number'],
1725 $section['toclevel'], $section['index'] );
1726 $lastLevel = $section['toclevel'];
1728 $toc .= self
::tocLineEnd();
1729 return self
::tocList( $toc, $lang );
1733 * Create a headline for content
1736 * @param int $level The level of the headline (1-6)
1737 * @param string $attribs Any attributes for the headline, starting with
1738 * a space and ending with '>'
1739 * This *must* be at least '>' for no attribs
1740 * @param string $anchor The anchor to give the headline (the bit after the #)
1741 * @param string $html HTML for the text of the header
1742 * @param string $link HTML to add for the section edit link
1743 * @param string|bool $fallbackAnchor A second, optional anchor to give for
1744 * backward compatibility (false to omit)
1746 * @return string HTML headline
1748 public static function makeHeadline( $level, $attribs, $anchor, $html,
1749 $link, $fallbackAnchor = false
1751 $anchorEscaped = htmlspecialchars( $anchor );
1753 if ( $fallbackAnchor !== false && $fallbackAnchor !== $anchor ) {
1754 $fallbackAnchor = htmlspecialchars( $fallbackAnchor );
1755 $fallback = "<span id=\"$fallbackAnchor\"></span>";
1757 return "<h$level$attribs"
1758 . "$fallback<span class=\"mw-headline\" id=\"$anchorEscaped\">$html</span>"
1764 * Split a link trail, return the "inside" portion and the remainder of the trail
1765 * as a two-element array
1766 * @param string $trail
1769 static function splitTrail( $trail ) {
1770 $regex = MediaWikiServices
::getInstance()->getContentLanguage()->linkTrail();
1772 if ( $trail !== '' && preg_match( $regex, $trail, $m ) ) {
1773 list( , $inside, $trail ) = $m;
1775 return [ $inside, $trail ];
1779 * Generate a rollback link for a given revision. Currently it's the
1780 * caller's responsibility to ensure that the revision is the top one. If
1781 * it's not, of course, the user will get an error message.
1783 * If the calling page is called with the parameter &bot=1, all rollback
1784 * links also get that parameter. It causes the edit itself and the rollback
1785 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1786 * changes, so this allows sysops to combat a busy vandal without bothering
1789 * If the option verify is set this function will return the link only in case the
1790 * revision can be reverted. Please note that due to performance limitations
1791 * it might be assumed that a user isn't the only contributor of a page while
1792 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1793 * work if $wgShowRollbackEditCount is disabled, so this can only function
1794 * as an additional check.
1796 * If the option noBrackets is set the rollback link wont be enclosed in "[]".
1798 * @since 1.16.3. $context added in 1.20. $options added in 1.21
1800 * @param Revision $rev
1801 * @param IContextSource|null $context Context to use or null for the main context.
1802 * @param array $options
1805 public static function generateRollback( $rev, IContextSource
$context = null,
1806 $options = [ 'verify' ]
1808 if ( $context === null ) {
1809 $context = RequestContext
::getMain();
1813 if ( in_array( 'verify', $options, true ) ) {
1814 $editCount = self
::getRollbackEditCount( $rev, true );
1815 if ( $editCount === false ) {
1820 $inner = self
::buildRollbackLink( $rev, $context, $editCount );
1822 if ( !in_array( 'noBrackets', $options, true ) ) {
1823 $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1826 if ( $context->getUser()->getBoolOption( 'showrollbackconfirmation' ) ) {
1827 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1828 $stats->increment( 'rollbackconfirmation.event.load' );
1829 $context->getOutput()->addModules( 'mediawiki.page.rollback.confirmation' );
1832 return '<span class="mw-rollback-link">' . $inner . '</span>';
1836 * This function will return the number of revisions which a rollback
1837 * would revert and, if $verify is set it will verify that a revision
1838 * can be reverted (that the user isn't the only contributor and the
1839 * revision we might rollback to isn't deleted). These checks can only
1840 * function as an additional check as this function only checks against
1841 * the last $wgShowRollbackEditCount edits.
1843 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1844 * is set and the user is the only contributor of the page.
1846 * @param Revision $rev
1847 * @param bool $verify Try to verify that this revision can really be rolled back
1848 * @return int|bool|null
1850 public static function getRollbackEditCount( $rev, $verify ) {
1851 global $wgShowRollbackEditCount;
1852 if ( !is_int( $wgShowRollbackEditCount ) ||
!$wgShowRollbackEditCount > 0 ) {
1853 // Nothing has happened, indicate this by returning 'null'
1857 $dbr = wfGetDB( DB_REPLICA
);
1859 // Up to the value of $wgShowRollbackEditCount revisions are counted
1860 $revQuery = Revision
::getQueryInfo();
1861 $res = $dbr->select(
1862 $revQuery['tables'],
1863 [ 'rev_user_text' => $revQuery['fields']['rev_user_text'], 'rev_deleted' ],
1864 // $rev->getPage() returns null sometimes
1865 [ 'rev_page' => $rev->getTitle()->getArticleID() ],
1868 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
1869 'ORDER BY' => 'rev_timestamp DESC',
1870 'LIMIT' => $wgShowRollbackEditCount +
1
1877 foreach ( $res as $row ) {
1878 if ( $rev->getUserText( Revision
::RAW
) != $row->rev_user_text
) {
1880 ( $row->rev_deleted
& Revision
::DELETED_TEXT
1881 ||
$row->rev_deleted
& Revision
::DELETED_USER
1883 // If the user or the text of the revision we might rollback
1884 // to is deleted in some way we can't rollback. Similar to
1885 // the sanity checks in WikiPage::commitRollback.
1894 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1895 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1896 // and there weren't any other revisions. That means that the current user is the only
1897 // editor, so we can't rollback
1904 * Build a raw rollback link, useful for collections of "tool" links
1906 * @since 1.16.3. $context added in 1.20. $editCount added in 1.21
1907 * @param Revision $rev
1908 * @param IContextSource|null $context Context to use or null for the main context.
1909 * @param int $editCount Number of edits that would be reverted
1910 * @return string HTML fragment
1912 public static function buildRollbackLink( $rev, IContextSource
$context = null,
1915 global $wgShowRollbackEditCount, $wgMiserMode;
1917 // To config which pages are affected by miser mode
1918 $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
1920 if ( $context === null ) {
1921 $context = RequestContext
::getMain();
1924 $title = $rev->getTitle();
1927 'action' => 'rollback',
1928 'from' => $rev->getUserText(),
1929 'token' => $context->getUser()->getEditToken( 'rollback' ),
1933 'data-mw' => 'interface',
1934 'title' => $context->msg( 'tooltip-rollback' )->text()
1937 $options = [ 'known', 'noclasses' ];
1939 if ( $context->getRequest()->getBool( 'bot' ) ) {
1941 $query['hidediff'] = '1';
1942 $query['bot'] = '1';
1945 $disableRollbackEditCount = false;
1946 if ( $wgMiserMode ) {
1947 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1948 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1949 $disableRollbackEditCount = true;
1955 if ( !$disableRollbackEditCount
1956 && is_int( $wgShowRollbackEditCount )
1957 && $wgShowRollbackEditCount > 0
1959 if ( !is_numeric( $editCount ) ) {
1960 $editCount = self
::getRollbackEditCount( $rev, false );
1963 if ( $editCount > $wgShowRollbackEditCount ) {
1964 $html = $context->msg( 'rollbacklinkcount-morethan' )
1965 ->numParams( $wgShowRollbackEditCount )->parse();
1967 $html = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1970 return self
::link( $title, $html, $attrs, $query, $options );
1973 $html = $context->msg( 'rollbacklink' )->escaped();
1974 return self
::link( $title, $html, $attrs, $query, $options );
1978 * Returns HTML for the "hidden categories on this page" list.
1981 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1983 * @return string HTML output
1985 public static function formatHiddenCategories( $hiddencats ) {
1987 if ( count( $hiddencats ) > 0 ) {
1988 # Construct the HTML
1989 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1990 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
1991 $outText .= "</div><ul>\n";
1993 foreach ( $hiddencats as $titleObj ) {
1994 # If it's hidden, it must exist - no need to check with a LinkBatch
1996 . self
::link( $titleObj, null, [], [], 'known' )
1999 $outText .= '</ul>';
2005 * Given the id of an interface element, constructs the appropriate title
2006 * attribute from the system messages. (Note, this is usually the id but
2007 * isn't always, because sometimes the accesskey needs to go on a different
2008 * element than the id, for reverse-compatibility, etc.)
2010 * @since 1.16.3 $msgParams added in 1.27
2011 * @param string $name Id of the element, minus prefixes.
2012 * @param string|array|null $options Null, string or array with some of the following options:
2013 * - 'withaccess' to add an access-key hint
2014 * - 'nonexisting' to add an accessibility hint that page does not exist
2015 * @param array $msgParams Parameters to pass to the message
2017 * @return string Contents of the title attribute (which you must HTML-
2018 * escape), or false for no title attribute
2020 public static function titleAttrib( $name, $options = null, array $msgParams = [] ) {
2021 $message = wfMessage( "tooltip-$name", $msgParams );
2022 if ( !$message->exists() ) {
2025 $tooltip = $message->text();
2026 # Compatibility: formerly some tooltips had [alt-.] hardcoded
2027 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2028 # Message equal to '-' means suppress it.
2029 if ( $tooltip == '-' ) {
2034 $options = (array)$options;
2036 if ( in_array( 'nonexisting', $options ) ) {
2037 $tooltip = wfMessage( 'red-link-title', $tooltip ?
: '' )->text();
2039 if ( in_array( 'withaccess', $options ) ) {
2040 $accesskey = self
::accesskey( $name );
2041 if ( $accesskey !== false ) {
2042 // Should be build the same as in jquery.accessKeyLabel.js
2043 if ( $tooltip === false ||
$tooltip === '' ) {
2044 $tooltip = wfMessage( 'brackets', $accesskey )->text();
2046 $tooltip .= wfMessage( 'word-separator' )->text();
2047 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
2055 public static $accesskeycache;
2058 * Given the id of an interface element, constructs the appropriate
2059 * accesskey attribute from the system messages. (Note, this is usually
2060 * the id but isn't always, because sometimes the accesskey needs to go on
2061 * a different element than the id, for reverse-compatibility, etc.)
2064 * @param string $name Id of the element, minus prefixes.
2065 * @return string Contents of the accesskey attribute (which you must HTML-
2066 * escape), or false for no accesskey attribute
2068 public static function accesskey( $name ) {
2069 if ( isset( self
::$accesskeycache[$name] ) ) {
2070 return self
::$accesskeycache[$name];
2073 $message = wfMessage( "accesskey-$name" );
2075 if ( !$message->exists() ) {
2078 $accesskey = $message->plain();
2079 if ( $accesskey === '' ||
$accesskey === '-' ) {
2080 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2081 # attribute, but this is broken for accesskey: that might be a useful
2087 self
::$accesskeycache[$name] = $accesskey;
2088 return self
::$accesskeycache[$name];
2092 * Get a revision-deletion link, or disabled link, or nothing, depending
2093 * on user permissions & the settings on the revision.
2095 * Will use forward-compatible revision ID in the Special:RevDelete link
2096 * if possible, otherwise the timestamp-based ID which may break after
2100 * @param Revision $rev
2101 * @param LinkTarget $title
2102 * @return string HTML fragment
2104 public static function getRevDeleteLink( User
$user, Revision
$rev, LinkTarget
$title ) {
2105 $canHide = $user->isAllowed( 'deleterevision' );
2106 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2110 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
2111 return self
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2113 $prefixedDbKey = MediaWikiServices
::getInstance()->getTitleFormatter()->
2114 getPrefixedDBkey( $title );
2115 if ( $rev->getId() ) {
2116 // RevDelete links using revision ID are stable across
2117 // page deletion and undeletion; use when possible.
2119 'type' => 'revision',
2120 'target' => $prefixedDbKey,
2121 'ids' => $rev->getId()
2124 // Older deleted entries didn't save a revision ID.
2125 // We have to refer to these by timestamp, ick!
2127 'type' => 'archive',
2128 'target' => $prefixedDbKey,
2129 'ids' => $rev->getTimestamp()
2132 return self
::revDeleteLink( $query,
2133 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
2137 * Creates a (show/hide) link for deleting revisions/log entries
2139 * @param array $query Query parameters to be passed to link()
2140 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2141 * @param bool $delete Set to true to use (show/hide) rather than (show)
2143 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2144 * span to allow for customization of appearance with CSS
2146 public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2147 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
2148 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2149 $html = wfMessage( $msgKey )->escaped();
2150 $tag = $restricted ?
'strong' : 'span';
2151 $link = self
::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2154 [ 'class' => 'mw-revdelundel-link' ],
2155 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2160 * Creates a dead (show/hide) link for deleting revisions/log entries
2163 * @param bool $delete Set to true to use (show/hide) rather than (show)
2165 * @return string HTML text wrapped in a span to allow for customization
2166 * of appearance with CSS
2168 public static function revDeleteLinkDisabled( $delete = true ) {
2169 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2170 $html = wfMessage( $msgKey )->escaped();
2171 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2172 return Xml
::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2176 * Returns the attributes for the tooltip and access key.
2178 * @since 1.16.3. $msgParams introduced in 1.27
2179 * @param string $name
2180 * @param array $msgParams Params for constructing the message
2181 * @param string|array|null $options Options to be passed to titleAttrib.
2183 * @see Linker::titleAttrib for what options could be passed to $options.
2187 public static function tooltipAndAccesskeyAttribs(
2189 array $msgParams = [],
2192 $options = (array)$options;
2193 $options[] = 'withaccess';
2196 'title' => self
::titleAttrib( $name, $options, $msgParams ),
2197 'accesskey' => self
::accesskey( $name )
2199 if ( $attribs['title'] === false ) {
2200 unset( $attribs['title'] );
2202 if ( $attribs['accesskey'] === false ) {
2203 unset( $attribs['accesskey'] );
2209 * Returns raw bits of HTML, use titleAttrib()
2211 * @param string $name
2212 * @param array|null $options
2213 * @return null|string
2215 public static function tooltip( $name, $options = null ) {
2216 $tooltip = self
::titleAttrib( $name, $options );
2217 if ( $tooltip === false ) {
2220 return Xml
::expandAttributes( [