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
;
24 use MediaWiki\Storage\RevisionRecord
;
27 * Some internal bits split of from Skin.php. These functions are used
28 * for primarily page content: links, embedded images, table of contents. Links
29 * are also used in the skin.
31 * @todo turn this into a legacy interface for HtmlPageLinkRenderer and similar services.
37 * Flags for userToolLinks()
39 const TOOL_LINKS_NOBLOCK
= 1;
40 const TOOL_LINKS_EMAIL
= 2;
43 * This function returns an HTML link to the given target. It serves a few
45 * 1) If $target is a LinkTarget, the correct URL to link to will be figured
47 * 2) It automatically adds the usual classes for various types of link
48 * targets: "new" for red links, "stub" for short articles, etc.
49 * 3) It escapes all attribute values safely so there's no risk of XSS.
50 * 4) It provides a default tooltip if the target is a LinkTarget (the page
51 * name of the target).
52 * link() replaces the old functions in the makeLink() family.
54 * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
55 * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
57 * @param LinkTarget $target Can currently only be a LinkTarget, but this may
58 * change to support Images, literal URLs, etc.
59 * @param string $html The HTML contents of the <a> element, i.e.,
60 * the link text. This is raw HTML and will not be escaped. If null,
61 * defaults to the prefixed text of the LinkTarget; or if the LinkTarget is just a
62 * fragment, the contents of the fragment.
63 * @param array $customAttribs A key => value array of extra HTML attributes,
64 * such as title and class. (href is ignored.) Classes will be
65 * merged with the default classes, while other attributes will replace
66 * default attributes. All passed attribute values will be HTML-escaped.
67 * A false attribute value means to suppress that attribute.
68 * @param array $query The query string to append to the URL
69 * you're linking to, in key => value array form. Query keys and values
70 * will be URL-encoded.
71 * @param string|array $options String or array of strings:
72 * 'known': Page is known to exist, so don't check if it does.
73 * 'broken': Page is known not to exist, so don't check if it does.
74 * 'noclasses': Don't add any classes automatically (includes "new",
75 * "stub", "mw-redirect", "extiw"). Only use the class attribute
76 * provided, if any, so you get a simple blue link with no funny i-
78 * 'forcearticlepath': Use the article path always, even with a querystring.
79 * Has compatibility issues on some setups, so avoid wherever possible.
80 * 'http': Force a full URL with http:// as the scheme.
81 * 'https': Force a full URL with https:// as the scheme.
82 * 'stubThreshold' => (int): Stub threshold to use when determining link classes.
83 * @return string HTML <a> attribute
85 public static function link(
86 $target, $html = null, $customAttribs = [], $query = [], $options = []
88 if ( !$target instanceof LinkTarget
) {
89 wfWarn( __METHOD__
. ': Requires $target to be a LinkTarget object.', 2 );
90 return "<!-- ERROR -->$html";
93 $services = MediaWikiServices
::getInstance();
94 $options = (array)$options;
96 // Custom options, create new LinkRenderer
97 if ( !isset( $options['stubThreshold'] ) ) {
98 $defaultLinkRenderer = $services->getLinkRenderer();
99 $options['stubThreshold'] = $defaultLinkRenderer->getStubThreshold();
101 $linkRenderer = $services->getLinkRendererFactory()
102 ->createFromLegacyOptions( $options );
104 $linkRenderer = $services->getLinkRenderer();
107 if ( $html !== null ) {
108 $text = new HtmlArmor( $html );
113 if ( in_array( 'known', $options, true ) ) {
114 return $linkRenderer->makeKnownLink( $target, $text, $customAttribs, $query );
117 if ( in_array( 'broken', $options, true ) ) {
118 return $linkRenderer->makeBrokenLink( $target, $text, $customAttribs, $query );
121 if ( in_array( 'noclasses', $options, true ) ) {
122 return $linkRenderer->makePreloadedLink( $target, $text, '', $customAttribs, $query );
125 return $linkRenderer->makeLink( $target, $text, $customAttribs, $query );
129 * Identical to link(), except $options defaults to 'known'.
132 * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
134 * @param LinkTarget $target
135 * @param string $html
136 * @param array $customAttribs
137 * @param array $query
138 * @param string|array $options
141 public static function linkKnown(
142 $target, $html = null, $customAttribs = [],
143 $query = [], $options = [ 'known' ]
145 return self
::link( $target, $html, $customAttribs, $query, $options );
149 * Make appropriate markup for a link to the current article. This is since
150 * MediaWiki 1.29.0 rendered as an <a> tag without an href and with a class
151 * showing the link text. The calling sequence is the same as for the other
152 * make*LinkObj static functions, but $query is not used.
155 * @param LinkTarget $nt
156 * @param string $html [optional]
157 * @param string $query [optional]
158 * @param string $trail [optional]
159 * @param string $prefix [optional]
163 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
164 $nt = Title
::newFromLinkTarget( $nt );
165 $ret = "<a class=\"mw-selflink selflink\">{$prefix}{$html}</a>{$trail}";
166 if ( !Hooks
::run( 'SelfLinkBegin', [ $nt, &$html, &$trail, &$prefix, &$ret ] ) ) {
171 $html = htmlspecialchars( $nt->getPrefixedText() );
173 list( $inside, $trail ) = self
::splitTrail( $trail );
174 return "<a class=\"mw-selflink selflink\">{$prefix}{$html}{$inside}</a>{$trail}";
178 * Get a message saying that an invalid title was encountered.
179 * This should be called after a method like Title::makeTitleSafe() returned
180 * a value indicating that the title object is invalid.
182 * @param IContextSource $context Context to use to get the messages
183 * @param int $namespace Namespace number
184 * @param string $title Text of the title, without the namespace part
187 public static function getInvalidTitleDescription( IContextSource
$context, $namespace, $title ) {
188 // First we check whether the namespace exists or not.
189 if ( MediaWikiServices
::getInstance()->getNamespaceInfo()->exists( $namespace ) ) {
190 if ( $namespace == NS_MAIN
) {
191 $name = $context->msg( 'blanknamespace' )->text();
193 $name = MediaWikiServices
::getInstance()->getContentLanguage()->
194 getFormattedNsText( $namespace );
196 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
199 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
204 * @param LinkTarget $target
207 public static function normaliseSpecialPage( LinkTarget
$target ) {
208 if ( $target->getNamespace() == NS_SPECIAL
&& !$target->isExternal() ) {
209 list( $name, $subpage ) = MediaWikiServices
::getInstance()->getSpecialPageFactory()->
210 resolveAlias( $target->getDBkey() );
212 return SpecialPage
::getTitleValueFor( $name, $subpage, $target->getFragment() );
220 * Returns the filename part of an url.
221 * Used as alternative text for external images.
227 private static function fnamePart( $url ) {
228 $basename = strrchr( $url, '/' );
229 if ( $basename === false ) {
232 $basename = substr( $basename, 1 );
238 * Return the code for images which were added via external links,
239 * via Parser::maybeMakeExternalImage().
247 public static function makeExternalImage( $url, $alt = '' ) {
249 $alt = self
::fnamePart( $url );
252 $success = Hooks
::run( 'LinkerMakeExternalImage', [ &$url, &$alt, &$img ] );
254 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
255 . "with url {$url} and alt text {$alt} to {$img}\n", true );
258 return Html
::element( 'img',
267 * Given parameters derived from [[Image:Foo|options...]], generate the
268 * HTML that that syntax inserts in the page.
270 * @param Parser $parser
271 * @param LinkTarget $title LinkTarget object of the file (not the currently viewed page)
272 * @param File $file File object, or false if it doesn't exist
273 * @param array $frameParams Associative array of parameters external to the media handler.
274 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
275 * will often be false.
276 * thumbnail If present, downscale and frame
277 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
278 * framed Shows image in original size in a frame
279 * frameless Downscale but don't frame
280 * upright If present, tweak default sizes for portrait orientation
281 * upright_factor Fudge factor for "upright" tweak (default 0.75)
282 * border If present, show a border around the image
283 * align Horizontal alignment (left, right, center, none)
284 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
285 * bottom, text-bottom)
286 * alt Alternate text for image (i.e. alt attribute). Plain text.
287 * class HTML for image classes. Plain text.
288 * caption HTML for image caption.
289 * link-url URL to link to
290 * link-title LinkTarget object to link to
291 * link-target Value for the target attribute, only with link-url
292 * no-link Boolean, suppress description link
293 * targetlang (optional) Target language code, see Parser::getTargetLanguage()
295 * @param array $handlerParams Associative array of media handler parameters, to be passed
296 * to transform(). Typical keys are "width" and "page".
297 * @param string|bool $time Timestamp of the file, set as false for current
298 * @param string $query Query params for desc url
299 * @param int|null $widthOption Used by the parser to remember the user preference thumbnailsize
301 * @return string HTML for an image, with links, wrappers, etc.
303 public static function makeImageLink( Parser
$parser, LinkTarget
$title,
304 $file, $frameParams = [], $handlerParams = [], $time = false,
305 $query = "", $widthOption = null
307 $title = Title
::newFromLinkTarget( $title );
309 $dummy = new DummyLinker
;
310 if ( !Hooks
::run( 'ImageBeforeProduceHTML', [ &$dummy, &$title,
311 &$file, &$frameParams, &$handlerParams, &$time, &$res,
312 $parser, &$query, &$widthOption
317 if ( $file && !$file->allowInlineDisplay() ) {
318 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
319 return self
::link( $title );
322 // Clean up parameters
323 $page = $handlerParams['page'] ??
false;
324 if ( !isset( $frameParams['align'] ) ) {
325 $frameParams['align'] = '';
327 if ( !isset( $frameParams['alt'] ) ) {
328 $frameParams['alt'] = '';
330 if ( !isset( $frameParams['title'] ) ) {
331 $frameParams['title'] = '';
333 if ( !isset( $frameParams['class'] ) ) {
334 $frameParams['class'] = '';
337 $prefix = $postfix = '';
339 if ( $frameParams['align'] == 'center' ) {
340 $prefix = '<div class="center">';
342 $frameParams['align'] = 'none';
344 if ( $file && !isset( $handlerParams['width'] ) ) {
345 if ( isset( $handlerParams['height'] ) && $file->isVectorized() ) {
346 // If its a vector image, and user only specifies height
347 // we don't want it to be limited by its "normal" width.
348 global $wgSVGMaxSize;
349 $handlerParams['width'] = $wgSVGMaxSize;
351 $handlerParams['width'] = $file->getWidth( $page );
354 if ( isset( $frameParams['thumbnail'] )
355 ||
isset( $frameParams['manualthumb'] )
356 ||
isset( $frameParams['framed'] )
357 ||
isset( $frameParams['frameless'] )
358 ||
!$handlerParams['width']
360 global $wgThumbLimits, $wgThumbUpright;
362 if ( $widthOption === null ||
!isset( $wgThumbLimits[$widthOption] ) ) {
363 $widthOption = User
::getDefaultOption( 'thumbsize' );
366 // Reduce width for upright images when parameter 'upright' is used
367 if ( isset( $frameParams['upright'] ) && $frameParams['upright'] == 0 ) {
368 $frameParams['upright'] = $wgThumbUpright;
371 // For caching health: If width scaled down due to upright
372 // parameter, round to full __0 pixel to avoid the creation of a
373 // lot of odd thumbs.
374 $prefWidth = isset( $frameParams['upright'] ) ?
375 round( $wgThumbLimits[$widthOption] * $frameParams['upright'], -1 ) :
376 $wgThumbLimits[$widthOption];
378 // Use width which is smaller: real image width or user preference width
379 // Unless image is scalable vector.
380 if ( !isset( $handlerParams['height'] ) && ( $handlerParams['width'] <= 0 ||
381 $prefWidth < $handlerParams['width'] ||
$file->isVectorized() ) ) {
382 $handlerParams['width'] = $prefWidth;
387 if ( isset( $frameParams['thumbnail'] ) ||
isset( $frameParams['manualthumb'] )
388 ||
isset( $frameParams['framed'] )
390 # Create a thumbnail. Alignment depends on the writing direction of
391 # the page content language (right-aligned for LTR languages,
392 # left-aligned for RTL languages)
393 # If a thumbnail width has not been provided, it is set
394 # to the default user option as specified in Language*.php
395 if ( $frameParams['align'] == '' ) {
396 $frameParams['align'] = $parser->getTargetLanguage()->alignEnd();
399 self
::makeThumbLink2( $title, $file, $frameParams, $handlerParams, $time, $query ) .
403 if ( $file && isset( $frameParams['frameless'] ) ) {
404 $srcWidth = $file->getWidth( $page );
405 # For "frameless" option: do not present an image bigger than the
406 # source (for bitmap-style images). This is the same behavior as the
407 # "thumb" option does it already.
408 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
409 $handlerParams['width'] = $srcWidth;
413 if ( $file && isset( $handlerParams['width'] ) ) {
414 # Create a resized image, without the additional thumbnail features
415 $thumb = $file->transform( $handlerParams );
421 $s = self
::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
423 self
::processResponsiveImages( $file, $thumb, $handlerParams );
425 'alt' => $frameParams['alt'],
426 'title' => $frameParams['title'],
427 'valign' => $frameParams['valign'] ??
false,
428 'img-class' => $frameParams['class'] ];
429 if ( isset( $frameParams['border'] ) ) {
430 $params['img-class'] .= ( $params['img-class'] !== '' ?
' ' : '' ) . 'thumbborder';
432 $params = self
::getImageLinkMTOParams( $frameParams, $query, $parser ) +
$params;
434 $s = $thumb->toHtml( $params );
436 if ( $frameParams['align'] != '' ) {
437 $s = Html
::rawElement(
439 [ 'class' => 'float' . $frameParams['align'] ],
443 return str_replace( "\n", ' ', $prefix . $s . $postfix );
447 * Get the link parameters for MediaTransformOutput::toHtml() from given
448 * frame parameters supplied by the Parser.
449 * @param array $frameParams The frame parameters
450 * @param string $query An optional query string to add to description page links
451 * @param Parser|null $parser
454 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
456 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
457 $mtoParams['custom-url-link'] = $frameParams['link-url'];
458 if ( isset( $frameParams['link-target'] ) ) {
459 $mtoParams['custom-target-link'] = $frameParams['link-target'];
462 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
463 foreach ( $extLinkAttrs as $name => $val ) {
464 // Currently could include 'rel' and 'target'
465 $mtoParams['parser-extlink-' . $name] = $val;
468 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
469 $mtoParams['custom-title-link'] = Title
::newFromLinkTarget(
470 self
::normaliseSpecialPage( $frameParams['link-title'] )
472 } elseif ( !empty( $frameParams['no-link'] ) ) {
475 $mtoParams['desc-link'] = true;
476 $mtoParams['desc-query'] = $query;
482 * Make HTML for a thumbnail including image, border and caption
483 * @param LinkTarget $title
484 * @param File|bool $file File object or false if it doesn't exist
485 * @param string $label
487 * @param string $align
488 * @param array $params
489 * @param bool $framed
490 * @param string $manualthumb
493 public static function makeThumbLinkObj( LinkTarget
$title, $file, $label = '', $alt = '',
494 $align = 'right', $params = [], $framed = false, $manualthumb = ""
502 $frameParams['framed'] = true;
504 if ( $manualthumb ) {
505 $frameParams['manualthumb'] = $manualthumb;
507 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
511 * @param LinkTarget $title
513 * @param array $frameParams
514 * @param array $handlerParams
516 * @param string $query
519 public static function makeThumbLink2( LinkTarget
$title, $file, $frameParams = [],
520 $handlerParams = [], $time = false, $query = ""
522 $exists = $file && $file->exists();
524 $page = $handlerParams['page'] ??
false;
525 if ( !isset( $frameParams['align'] ) ) {
526 $frameParams['align'] = 'right';
528 if ( !isset( $frameParams['alt'] ) ) {
529 $frameParams['alt'] = '';
531 if ( !isset( $frameParams['title'] ) ) {
532 $frameParams['title'] = '';
534 if ( !isset( $frameParams['caption'] ) ) {
535 $frameParams['caption'] = '';
538 if ( empty( $handlerParams['width'] ) ) {
539 // Reduce width for upright images when parameter 'upright' is used
540 $handlerParams['width'] = isset( $frameParams['upright'] ) ?
130 : 180;
544 $manualthumb = false;
547 $outerWidth = $handlerParams['width'] +
2;
549 if ( isset( $frameParams['manualthumb'] ) ) {
550 # Use manually specified thumbnail
551 $manual_title = Title
::makeTitleSafe( NS_FILE
, $frameParams['manualthumb'] );
552 if ( $manual_title ) {
553 $manual_img = MediaWikiServices
::getInstance()->getRepoGroup()
554 ->findFile( $manual_title );
556 $thumb = $manual_img->getUnscaledThumb( $handlerParams );
562 } elseif ( isset( $frameParams['framed'] ) ) {
563 // Use image dimensions, don't scale
564 $thumb = $file->getUnscaledThumb( $handlerParams );
567 # Do not present an image bigger than the source, for bitmap-style images
568 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
569 $srcWidth = $file->getWidth( $page );
570 if ( $srcWidth && !$file->mustRender() && $handlerParams['width'] > $srcWidth ) {
571 $handlerParams['width'] = $srcWidth;
573 $thumb = $file->transform( $handlerParams );
577 $outerWidth = $thumb->getWidth() +
2;
579 $outerWidth = $handlerParams['width'] +
2;
583 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
584 # So we don't need to pass it here in $query. However, the URL for the
585 # zoom icon still needs it, so we make a unique query for it. See T16771
586 $url = Title
::newFromLinkTarget( $title )->getLocalURL( $query );
588 $url = wfAppendQuery( $url, [ 'page' => $page ] );
591 && !isset( $frameParams['link-title'] )
592 && !isset( $frameParams['link-url'] )
593 && !isset( $frameParams['no-link'] ) ) {
594 $frameParams['link-url'] = $url;
597 $s = "<div class=\"thumb t{$frameParams['align']}\">"
598 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
601 $s .= self
::makeBrokenImageLinkObj( $title, $frameParams['title'], '', '', '', $time == true );
603 } elseif ( !$thumb ) {
604 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
607 if ( !$noscale && !$manualthumb ) {
608 self
::processResponsiveImages( $file, $thumb, $handlerParams );
611 'alt' => $frameParams['alt'],
612 'title' => $frameParams['title'],
613 'img-class' => ( isset( $frameParams['class'] ) && $frameParams['class'] !== ''
614 ?
$frameParams['class'] . ' '
615 : '' ) . 'thumbimage'
617 $params = self
::getImageLinkMTOParams( $frameParams, $query ) +
$params;
618 $s .= $thumb->toHtml( $params );
619 if ( isset( $frameParams['framed'] ) ) {
622 $zoomIcon = Html
::rawElement( 'div', [ 'class' => 'magnify' ],
623 Html
::rawElement( 'a', [
625 'class' => 'internal',
626 'title' => wfMessage( 'thumbnail-more' )->text() ],
630 $s .= ' <div class="thumbcaption">' . $zoomIcon . $frameParams['caption'] . "</div></div></div>";
631 return str_replace( "\n", ' ', $s );
635 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
639 * @param MediaTransformOutput $thumb
640 * @param array $hp Image parameters
642 public static function processResponsiveImages( $file, $thumb, $hp ) {
643 global $wgResponsiveImages;
644 if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
646 $hp15['width'] = round( $hp['width'] * 1.5 );
648 $hp20['width'] = $hp['width'] * 2;
649 if ( isset( $hp['height'] ) ) {
650 $hp15['height'] = round( $hp['height'] * 1.5 );
651 $hp20['height'] = $hp['height'] * 2;
654 $thumb15 = $file->transform( $hp15 );
655 $thumb20 = $file->transform( $hp20 );
656 if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
657 $thumb->responsiveUrls
['1.5'] = $thumb15->getUrl();
659 if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
660 $thumb->responsiveUrls
['2'] = $thumb20->getUrl();
666 * Make a "broken" link to an image
669 * @param LinkTarget $title
670 * @param string $label Link label (plain text)
671 * @param string $query Query string
672 * @param string $unused1 Unused parameter kept for b/c
673 * @param string $unused2 Unused parameter kept for b/c
674 * @param bool $time A file of a certain timestamp was requested
677 public static function makeBrokenImageLinkObj( $title, $label = '',
678 $query = '', $unused1 = '', $unused2 = '', $time = false
680 if ( !$title instanceof LinkTarget
) {
681 wfWarn( __METHOD__
. ': Requires $title to be a LinkTarget object.' );
682 return "<!-- ERROR -->" . htmlspecialchars( $label );
685 $title = Title
::castFromLinkTarget( $title );
687 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
688 if ( $label == '' ) {
689 $label = $title->getPrefixedText();
691 $encLabel = htmlspecialchars( $label );
692 $currentExists = $time
693 && MediaWikiServices
::getInstance()->getRepoGroup()->findFile( $title ) !== false;
695 if ( ( $wgUploadMissingFileUrl ||
$wgUploadNavigationUrl ||
$wgEnableUploads )
698 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
701 // We already know it's a redirect, so mark it
706 [ 'class' => 'mw-redirect' ],
707 wfCgiToArray( $query ),
708 [ 'known', 'noclasses' ]
712 $href = self
::getUploadUrl( $title, $query );
714 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
715 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
719 return self
::link( $title, $encLabel, [], wfCgiToArray( $query ), [ 'known', 'noclasses' ] );
723 * Get the URL to upload a certain file
726 * @param LinkTarget $destFile LinkTarget object of the file to upload
727 * @param string $query Urlencoded query string to prepend
728 * @return string Urlencoded URL
730 protected static function getUploadUrl( $destFile, $query = '' ) {
731 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
732 $q = 'wpDestFile=' . Title
::castFromLinkTarget( $destFile )->getPartialURL();
733 if ( $query != '' ) {
737 if ( $wgUploadMissingFileUrl ) {
738 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
741 if ( $wgUploadNavigationUrl ) {
742 return wfAppendQuery( $wgUploadNavigationUrl, $q );
745 $upload = SpecialPage
::getTitleFor( 'Upload' );
747 return $upload->getLocalURL( $q );
751 * Create a direct link to a given uploaded file.
754 * @param LinkTarget $title
755 * @param string $html Pre-sanitized HTML
756 * @param string|false $time MW timestamp of file creation time
757 * @return string HTML
759 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
760 $img = MediaWikiServices
::getInstance()->getRepoGroup()->findFile(
761 $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 LinkTarget $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( LinkTarget
$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
::castFromLinkTarget( $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 )->escaped() );
828 * Make an external link
830 * @since 1.16.3. $title added in 1.21
831 * @param string $url URL to link to
832 * @param-taint $url escapes_html
833 * @param string $text Text of link
834 * @param-taint $text escapes_html
835 * @param bool $escape Do we escape the link text?
836 * @param-taint $escape none
837 * @param string $linktype Type of external link. Gets added to the classes
838 * @param-taint $linktype escapes_html
839 * @param array $attribs Array of extra attributes to <a>
840 * @param-taint $attribs escapes_html
841 * @param LinkTarget|null $title LinkTarget object used for title specific link attributes
842 * @param-taint $title none
845 public static function makeExternalLink( $url, $text, $escape = true,
846 $linktype = '', $attribs = [], $title = null
851 $class .= " $linktype";
853 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
854 $class .= " {$attribs['class']}";
856 $attribs['class'] = $class;
859 $text = htmlspecialchars( $text );
865 $newRel = Parser
::getExternalLinkRel( $url, $title );
866 if ( !isset( $attribs['rel'] ) ||
$attribs['rel'] === '' ) {
867 $attribs['rel'] = $newRel;
868 } elseif ( $newRel !== '' ) {
869 // Merge the rel attributes.
870 $newRels = explode( ' ', $newRel );
871 $oldRels = explode( ' ', $attribs['rel'] );
872 $combined = array_unique( array_merge( $newRels, $oldRels ) );
873 $attribs['rel'] = implode( ' ', $combined );
876 $success = Hooks
::run( 'LinkerMakeExternalLink',
877 [ &$url, &$text, &$link, &$attribs, $linktype ] );
879 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
880 . "with url {$url} and text {$text} to {$link}\n", true );
883 $attribs['href'] = $url;
884 return Html
::rawElement( 'a', $attribs, $text );
888 * Make user link (or user contributions for unregistered users)
889 * @param int $userId User id in database.
890 * @param string $userName User name in database.
891 * @param string $altUserName Text to display instead of the user name (optional)
892 * @return string HTML fragment
893 * @since 1.16.3. $altUserName was added in 1.19.
895 public static function userLink( $userId, $userName, $altUserName = false ) {
896 if ( $userName === '' ||
$userName === false ||
$userName === null ) {
897 wfDebug( __METHOD__
. ' received an empty username. Are there database errors ' .
898 'that need to be fixed?' );
899 return wfMessage( 'empty-username' )->parse();
902 $classes = 'mw-userlink';
904 if ( $userId == 0 ) {
905 $page = ExternalUserNames
::getUserLinkTitle( $userName );
907 if ( ExternalUserNames
::isExternal( $userName ) ) {
908 $classes .= ' mw-extuserlink';
909 } elseif ( $altUserName === false ) {
910 $altUserName = IP
::prettifyIP( $userName );
912 $classes .= ' mw-anonuserlink'; // Separate link class for anons (T45179)
914 $page = new TitleValue( NS_USER
, strtr( $userName, ' ', '_' ) );
917 // Wrap the output with <bdi> tags for directionality isolation
919 '<bdi>' . htmlspecialchars( $altUserName !== false ?
$altUserName : $userName ) . '</bdi>';
922 ? self
::link( $page, $linkText, [ 'class' => $classes ] )
923 : Html
::rawElement( 'span', [ 'class' => $classes ], $linkText );
927 * Generate standard user tool links (talk, contributions, block link, etc.)
930 * @param int $userId User identifier
931 * @param string $userText User name or IP address
932 * @param bool $redContribsWhenNoEdits Should the contributions link be
933 * red if the user has no edits?
934 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
935 * and Linker::TOOL_LINKS_EMAIL).
936 * @param int|null $edits User edit count (optional, for performance)
937 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
938 * @return string HTML fragment
940 public static function userToolLinks(
941 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null,
942 $useParentheses = true
944 if ( $userText === '' ) {
945 wfDebug( __METHOD__
. ' received an empty username. Are there database errors ' .
946 'that need to be fixed?' );
947 return ' ' . wfMessage( 'empty-username' )->parse();
950 global $wgUser, $wgDisableAnonTalk, $wgLang;
951 $talkable = !( $wgDisableAnonTalk && $userId == 0 );
952 $blockable = !( $flags & self
::TOOL_LINKS_NOBLOCK
);
953 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
&& $userId;
955 if ( $userId == 0 && ExternalUserNames
::isExternal( $userText ) ) {
956 // No tools for an external user
962 $items[] = self
::userTalkLink( $userId, $userText );
965 // check if the user has an edit
967 $attribs['class'] = 'mw-usertoollinks-contribs';
968 if ( $redContribsWhenNoEdits ) {
969 if ( intval( $edits ) === 0 && $edits !== 0 ) {
970 $user = User
::newFromId( $userId );
971 $edits = $user->getEditCount();
973 if ( $edits === 0 ) {
974 $attribs['class'] .= ' new';
977 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
979 $items[] = self
::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
981 $userCanBlock = MediaWikiServices
::getInstance()->getPermissionManager()
982 ->userHasRight( $wgUser, 'block' );
983 if ( $blockable && $userCanBlock ) {
984 $items[] = self
::blockLink( $userId, $userText );
987 if ( $addEmailLink && $wgUser->canSendEmail() ) {
988 $items[] = self
::emailLink( $userId, $userText );
991 Hooks
::run( 'UserToolLinksEdit', [ $userId, $userText, &$items ] );
997 if ( $useParentheses ) {
998 return wfMessage( 'word-separator' )->escaped()
999 . '<span class="mw-usertoollinks">'
1000 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1005 foreach ( $items as $tool ) {
1006 $tools[] = Html
::rawElement( 'span', [], $tool );
1008 return ' <span class="mw-usertoollinks mw-changeslist-links">' .
1009 implode( ' ', $tools ) . '</span>';
1013 * Alias for userToolLinks( $userId, $userText, true );
1015 * @param int $userId User identifier
1016 * @param string $userText User name or IP address
1017 * @param int|null $edits User edit count (optional, for performance)
1018 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
1021 public static function userToolLinksRedContribs(
1022 $userId, $userText, $edits = null, $useParentheses = true
1024 return self
::userToolLinks( $userId, $userText, true, 0, $edits, $useParentheses );
1029 * @param int $userId User id in database.
1030 * @param string $userText User name in database.
1031 * @return string HTML fragment with user talk link
1033 public static function userTalkLink( $userId, $userText ) {
1034 if ( $userText === '' ) {
1035 wfDebug( __METHOD__
. ' received an empty username. Are there database errors ' .
1036 'that need to be fixed?' );
1037 return wfMessage( 'empty-username' )->parse();
1040 $userTalkPage = new TitleValue( NS_USER_TALK
, strtr( $userText, ' ', '_' ) );
1041 $moreLinkAttribs['class'] = 'mw-usertoollinks-talk';
1043 return self
::link( $userTalkPage,
1044 wfMessage( 'talkpagelinktext' )->escaped(),
1051 * @param int $userId
1052 * @param string $userText User name in database.
1053 * @return string HTML fragment with block link
1055 public static function blockLink( $userId, $userText ) {
1056 if ( $userText === '' ) {
1057 wfDebug( __METHOD__
. ' received an empty username. Are there database errors ' .
1058 'that need to be fixed?' );
1059 return wfMessage( 'empty-username' )->parse();
1062 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1063 $moreLinkAttribs['class'] = 'mw-usertoollinks-block';
1065 return self
::link( $blockPage,
1066 wfMessage( 'blocklink' )->escaped(),
1072 * @param int $userId
1073 * @param string $userText User name in database.
1074 * @return string HTML fragment with e-mail user link
1076 public static function emailLink( $userId, $userText ) {
1077 if ( $userText === '' ) {
1078 wfLogWarning( __METHOD__
. ' received an empty username. Are there database errors ' .
1079 'that need to be fixed?' );
1080 return wfMessage( 'empty-username' )->parse();
1083 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1084 $moreLinkAttribs['class'] = 'mw-usertoollinks-mail';
1085 return self
::link( $emailPage,
1086 wfMessage( 'emaillink' )->escaped(),
1092 * Generate a user link if the current user is allowed to view it
1094 * @param Revision $rev
1095 * @param bool $isPublic Show only if all users can see it
1096 * @return string HTML fragment
1098 public static function revUserLink( $rev, $isPublic = false ) {
1099 if ( $rev->isDeleted( RevisionRecord
::DELETED_USER
) && $isPublic ) {
1100 $link = wfMessage( 'rev-deleted-user' )->escaped();
1101 } elseif ( $rev->userCan( RevisionRecord
::DELETED_USER
) ) {
1102 $link = self
::userLink( $rev->getUser( RevisionRecord
::FOR_THIS_USER
),
1103 $rev->getUserText( RevisionRecord
::FOR_THIS_USER
) );
1105 $link = wfMessage( 'rev-deleted-user' )->escaped();
1107 if ( $rev->isDeleted( RevisionRecord
::DELETED_USER
) ) {
1108 return '<span class="history-deleted">' . $link . '</span>';
1114 * Generate a user tool link cluster if the current user is allowed to view it
1116 * @param Revision $rev
1117 * @param bool $isPublic Show only if all users can see it
1118 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
1119 * @return string HTML
1121 public static function revUserTools( $rev, $isPublic = false, $useParentheses = true ) {
1122 if ( $rev->userCan( RevisionRecord
::DELETED_USER
) &&
1123 ( !$rev->isDeleted( RevisionRecord
::DELETED_USER
) ||
!$isPublic )
1125 $userId = $rev->getUser( RevisionRecord
::FOR_THIS_USER
);
1126 $userText = $rev->getUserText( RevisionRecord
::FOR_THIS_USER
);
1127 if ( $userId ||
(string)$userText !== '' ) {
1128 $link = self
::userLink( $userId, $userText )
1129 . self
::userToolLinks( $userId, $userText, false, 0, null,
1134 if ( !isset( $link ) ) {
1135 $link = wfMessage( 'rev-deleted-user' )->escaped();
1138 if ( $rev->isDeleted( RevisionRecord
::DELETED_USER
) ) {
1139 return ' <span class="history-deleted mw-userlink">' . $link . '</span>';
1145 * This function is called by all recent changes variants, by the page history,
1146 * and by the user contributions list. It is responsible for formatting edit
1147 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1148 * auto-generated comments (from section editing) and formats [[wikilinks]].
1150 * @author Erik Moeller <moeller@scireview.de>
1151 * @since 1.16.3. $wikiId added in 1.26
1153 * @param string $comment
1154 * @param LinkTarget|null $title LinkTarget object (to generate link to the section in
1155 * autocomment) or null
1156 * @param bool $local Whether section links should refer to local page
1157 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1158 * For use with external changes.
1160 * @return string HTML
1162 public static function formatComment(
1163 $comment, $title = null, $local = false, $wikiId = null
1165 # Sanitize text a bit:
1166 $comment = str_replace( "\n", " ", $comment );
1167 # Allow HTML entities (for T15815)
1168 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1170 # Render autocomments and make links:
1171 $comment = self
::formatAutocomments( $comment, $title, $local, $wikiId );
1172 return self
::formatLinksInComment( $comment, $title, $local, $wikiId );
1176 * Converts autogenerated comments in edit summaries into section links.
1178 * The pattern for autogen comments is / * foo * /, which makes for
1180 * We look for all comments, match any text before and after the comment,
1181 * add a separator where needed and format the comment itself with CSS
1182 * Called by Linker::formatComment.
1184 * @param string $comment Comment text
1185 * @param LinkTarget|null $title An optional LinkTarget object used to links to sections
1186 * @param bool $local Whether section links should refer to local page
1187 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1188 * as used by WikiMap.
1190 * @return string Formatted comment (wikitext)
1192 private static function formatAutocomments(
1193 $comment, $title = null, $local = false, $wikiId = null
1195 // @todo $append here is something of a hack to preserve the status
1196 // quo. Someone who knows more about bidi and such should decide
1197 // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1198 // wiki, both when autocomments exist and when they don't, and
1199 // (2) what markup will make that actually happen.
1201 $comment = preg_replace_callback(
1202 // To detect the presence of content before or after the
1203 // auto-comment, we use capturing groups inside optional zero-width
1204 // assertions. But older versions of PCRE can't directly make
1205 // zero-width assertions optional, so wrap them in a non-capturing
1207 '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1208 function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1211 // Ensure all match positions are defined
1212 $match +
= [ '', '', '', '' ];
1214 $pre = $match[1] !== '';
1216 $post = $match[3] !== '';
1220 'FormatAutocomments',
1221 [ &$comment, $pre, $auto, $post, Title
::castFromLinkTarget( $title ), $local,
1225 if ( $comment === null ) {
1228 # Remove links that a user may have manually put in the autosummary
1229 # This could be improved by copying as much of Parser::stripSectionName as desired.
1230 $section = str_replace( [
1236 // We don't want any links in the auto text to be linked, but we still
1237 // want to show any [[ ]]
1238 $sectionText = str_replace( '[[', '[[', $auto );
1240 $section = substr( Parser
::guessSectionNameFromStrippedText( $section ), 1 );
1241 // Support: HHVM (T222857)
1242 // The guessSectionNameFromStrippedText method returns a non-empty string
1243 // that starts with "#". Before PHP 7 (and still on HHVM) substr() would
1244 // return false if the start offset is the end of the string.
1245 // On PHP 7+, it gracefully returns empty string instead.
1246 if ( $section !== '' && $section !== false ) {
1248 $sectionTitle = new TitleValue( NS_MAIN
, '', $section );
1250 $sectionTitle = $title->createFragmentTarget( $section );
1252 $auto = Linker
::makeCommentLink(
1254 $wgLang->getArrow() . $wgLang->getDirMark() . $sectionText,
1261 # written summary $presep autocomment (summary /* section */)
1262 $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1265 # autocomment $postsep written summary (/* section */ summary)
1266 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1269 $auto = '<span dir="auto"><span class="autocomment">' . $auto . '</span>';
1270 $append .= '</span>';
1272 $comment = $pre . $auto;
1278 return $comment . $append;
1282 * Formats wiki links and media links in text; all other wiki formatting
1285 * @since 1.16.3. $wikiId added in 1.26
1286 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1288 * @param string $comment Text to format links in. WARNING! Since the output of this
1289 * function is html, $comment must be sanitized for use as html. You probably want
1290 * to pass $comment through Sanitizer::escapeHtmlAllowEntities() before calling
1292 * @param LinkTarget|null $title An optional LinkTarget object used to links to sections
1293 * @param bool $local Whether section links should refer to local page
1294 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1295 * as used by WikiMap.
1297 * @return string HTML
1298 * @return-taint onlysafefor_html
1300 public static function formatLinksInComment(
1301 $comment, $title = null, $local = false, $wikiId = null
1303 return preg_replace_callback(
1306 \s*+ # ignore leading whitespace, the *+ quantifier disallows backtracking
1307 :? # ignore optional leading colon
1308 ([^\]|]+) # 1. link target; page names cannot include ] or |
1311 # Stop matching at ]] without relying on backtracking.
1315 ([^[]*) # 3. link trail (the text up until the next link)
1317 function ( $match ) use ( $title, $local, $wikiId ) {
1318 $services = MediaWikiServices
::getInstance();
1321 $medians .= preg_quote(
1322 $services->getNamespaceInfo()->getCanonicalName( NS_MEDIA
), '/' );
1324 $medians .= preg_quote(
1325 MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( NS_MEDIA
),
1329 $comment = $match[0];
1331 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1332 if ( strpos( $match[1], '%' ) !== false ) {
1334 rawurldecode( $match[1] ),
1335 [ '<' => '<', '>' => '>' ]
1339 # Handle link renaming [[foo|text]] will show link as "text"
1340 if ( $match[2] != "" ) {
1347 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1348 # Media link; trail not supported.
1349 $linkRegexp = '/\[\[(.*?)\]\]/';
1350 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1352 $thelink = Linker
::makeMediaLinkObj( $title, $text );
1355 # Other kind of link
1356 # Make sure its target is non-empty
1357 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1358 $match[1] = substr( $match[1], 1 );
1360 if ( $match[1] !== false && $match[1] !== '' ) {
1362 MediaWikiServices
::getInstance()->getContentLanguage()->linkTrail(),
1366 $trail = $submatch[1];
1370 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1371 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1374 $linkTarget = Linker
::normalizeSubpageLink( $title, $match[1], $linkText );
1376 Title
::newFromText( $linkTarget );
1378 $target = MediaWikiServices
::getInstance()->getTitleParser()->
1379 parseTitle( $linkTarget );
1381 if ( $target->getText() == '' && !$target->isExternal()
1382 && !$local && $title
1384 $target = $title->createFragmentTarget( $target->getFragment() );
1387 $thelink = Linker
::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1388 } catch ( MalformedTitleException
$e ) {
1394 // If the link is still valid, go ahead and replace it in!
1395 $comment = preg_replace(
1397 StringUtils
::escapeRegexReplacement( $thelink ),
1410 * Generates a link to the given LinkTarget
1412 * @note This is only public for technical reasons. It's not intended for use outside Linker.
1414 * @param LinkTarget $linkTarget
1415 * @param string $text
1416 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1417 * as used by WikiMap.
1418 * @param string|string[] $options See the $options parameter in Linker::link.
1420 * @return string HTML link
1422 public static function makeCommentLink(
1423 LinkTarget
$linkTarget, $text, $wikiId = null, $options = []
1425 if ( $wikiId !== null && !$linkTarget->isExternal() ) {
1426 $link = self
::makeExternalLink(
1427 WikiMap
::getForeignURL(
1429 $linkTarget->getNamespace() === 0
1430 ?
$linkTarget->getDBkey()
1431 : MediaWikiServices
::getInstance()->getNamespaceInfo()->
1432 getCanonicalName( $linkTarget->getNamespace() ) .
1433 ':' . $linkTarget->getDBkey(),
1434 $linkTarget->getFragment()
1437 /* escape = */ false // Already escaped
1440 $link = self
::link( $linkTarget, $text, [], [], $options );
1447 * @param LinkTarget $contextTitle
1448 * @param string $target
1449 * @param string &$text
1452 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1455 # :Foobar -- override special treatment of prefix (images, language links)
1456 # /Foobar -- convert to CurrentPage/Foobar
1457 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1458 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1459 # ../Foobar -- convert to CurrentPage/Foobar,
1460 # (from CurrentPage/CurrentSubPage)
1461 # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1462 # (from CurrentPage/CurrentSubPage)
1464 $ret = $target; # default return value is no change
1466 # Some namespaces don't allow subpages,
1467 # so only perform processing if subpages are allowed
1469 $contextTitle && MediaWikiServices
::getInstance()->getNamespaceInfo()->
1470 hasSubpages( $contextTitle->getNamespace() )
1472 $hash = strpos( $target, '#' );
1473 if ( $hash !== false ) {
1474 $suffix = substr( $target, $hash );
1475 $target = substr( $target, 0, $hash );
1480 $target = trim( $target );
1481 $contextPrefixedText = MediaWikiServices
::getInstance()->getTitleFormatter()->
1482 getPrefixedText( $contextTitle );
1483 # Look at the first character
1484 if ( $target != '' && $target[0] === '/' ) {
1485 # / at end means we don't want the slash to be shown
1487 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1488 if ( $trailingSlashes ) {
1489 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1491 $noslash = substr( $target, 1 );
1494 $ret = $contextPrefixedText . '/' . trim( $noslash ) . $suffix;
1495 if ( $text === '' ) {
1496 $text = $target . $suffix;
1497 } # this might be changed for ugliness reasons
1499 # check for .. subpage backlinks
1501 $nodotdot = $target;
1502 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1504 $nodotdot = substr( $nodotdot, 3 );
1506 if ( $dotdotcount > 0 ) {
1507 $exploded = explode( '/', $contextPrefixedText );
1508 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1509 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1510 # / at the end means don't show full path
1511 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1512 $nodotdot = rtrim( $nodotdot, '/' );
1513 if ( $text === '' ) {
1514 $text = $nodotdot . $suffix;
1517 $nodotdot = trim( $nodotdot );
1518 if ( $nodotdot != '' ) {
1519 $ret .= '/' . $nodotdot;
1531 * Wrap a comment in standard punctuation and formatting if
1532 * it's non-empty, otherwise return empty string.
1534 * @since 1.16.3. $wikiId added in 1.26
1535 * @param string $comment
1536 * @param LinkTarget|null $title LinkTarget object (to generate link to section in autocomment)
1538 * @param bool $local Whether section links should refer to local page
1539 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1540 * For use with external changes.
1544 public static function commentBlock(
1545 $comment, $title = null, $local = false, $wikiId = null, $useParentheses = true
1547 // '*' used to be the comment inserted by the software way back
1548 // in antiquity in case none was provided, here for backwards
1549 // compatibility, acc. to brion -ævar
1550 if ( $comment == '' ||
$comment == '*' ) {
1553 $formatted = self
::formatComment( $comment, $title, $local, $wikiId );
1554 if ( $useParentheses ) {
1555 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1556 $classNames = 'comment';
1558 $classNames = 'comment comment--without-parentheses';
1560 return " <span class=\"$classNames\">$formatted</span>";
1564 * Wrap and format the given revision's comment block, if the current
1565 * user is allowed to view it.
1568 * @param Revision $rev
1569 * @param bool $local Whether section links should refer to local page
1570 * @param bool $isPublic Show only if all users can see it
1571 * @param bool $useParentheses (optional) Wrap comments in parentheses where needed
1572 * @return string HTML fragment
1574 public static function revComment( Revision
$rev, $local = false, $isPublic = false,
1575 $useParentheses = true
1577 if ( $rev->getComment( RevisionRecord
::RAW
) == "" ) {
1580 if ( $rev->isDeleted( RevisionRecord
::DELETED_COMMENT
) && $isPublic ) {
1581 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1582 } elseif ( $rev->userCan( RevisionRecord
::DELETED_COMMENT
) ) {
1583 $block = self
::commentBlock( $rev->getComment( RevisionRecord
::FOR_THIS_USER
),
1584 $rev->getTitle(), $local, null, $useParentheses );
1586 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1588 if ( $rev->isDeleted( RevisionRecord
::DELETED_COMMENT
) ) {
1589 return " <span class=\"history-deleted comment\">$block</span>";
1599 public static function formatRevisionSize( $size ) {
1601 $stxt = wfMessage( 'historyempty' )->escaped();
1603 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1605 return "<span class=\"history-size mw-diff-bytes\">$stxt</span>";
1609 * Add another level to the Table of Contents
1614 public static function tocIndent() {
1619 * Finish one or more sublevels on the Table of Contents
1625 public static function tocUnindent( $level ) {
1626 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1630 * parameter level defines if we are on an indentation level
1633 * @param string $anchor
1634 * @param string $tocline
1635 * @param string $tocnumber
1636 * @param string $level
1637 * @param string|bool $sectionIndex
1640 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1641 $classes = "toclevel-$level";
1642 if ( $sectionIndex !== false ) {
1643 $classes .= " tocsection-$sectionIndex";
1646 // <li class="$classes"><a href="#$anchor"><span class="tocnumber">
1647 // $tocnumber</span> <span class="toctext">$tocline</span></a>
1648 return Html
::openElement( 'li', [ 'class' => $classes ] )
1649 . Html
::rawElement( 'a',
1650 [ 'href' => "#$anchor" ],
1651 Html
::element( 'span', [ 'class' => 'tocnumber' ], $tocnumber )
1653 . Html
::rawElement( 'span', [ 'class' => 'toctext' ], $tocline )
1658 * End a Table Of Contents line.
1659 * tocUnindent() will be used instead if we're ending a line below
1664 public static function tocLineEnd() {
1669 * Wraps the TOC in a table and provides the hide/collapse javascript.
1672 * @param string $toc Html of the Table Of Contents
1673 * @param Language|null $lang Language for the toc title, defaults to user language
1674 * @return string Full html of the TOC
1676 public static function tocList( $toc, Language
$lang = null ) {
1677 $lang = $lang ?? RequestContext
::getMain()->getLanguage();
1679 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1681 return '<div id="toc" class="toc">'
1682 . Html
::element( 'input', [
1683 'type' => 'checkbox',
1685 'id' => 'toctogglecheckbox',
1686 'class' => 'toctogglecheckbox',
1687 'style' => 'display:none',
1689 . Html
::openElement( 'div', [
1690 'class' => 'toctitle',
1691 'lang' => $lang->getHtmlCode(),
1692 'dir' => $lang->getDir(),
1695 . '<span class="toctogglespan">'
1696 . Html
::label( '', 'toctogglecheckbox', [
1697 'class' => 'toctogglelabel',
1702 . "</ul>\n</div>\n";
1706 * Generate a table of contents from a section tree.
1708 * @since 1.16.3. $lang added in 1.17
1709 * @param array $tree Return value of ParserOutput::getSections()
1710 * @param Language|null $lang Language for the toc title, defaults to user language
1711 * @return string HTML fragment
1713 public static function generateTOC( $tree, Language
$lang = null ) {
1716 foreach ( $tree as $section ) {
1717 if ( $section['toclevel'] > $lastLevel ) {
1718 $toc .= self
::tocIndent();
1719 } elseif ( $section['toclevel'] < $lastLevel ) {
1720 $toc .= self
::tocUnindent(
1721 $lastLevel - $section['toclevel'] );
1723 $toc .= self
::tocLineEnd();
1726 $toc .= self
::tocLine( $section['anchor'],
1727 $section['line'], $section['number'],
1728 $section['toclevel'], $section['index'] );
1729 $lastLevel = $section['toclevel'];
1731 $toc .= self
::tocLineEnd();
1732 return self
::tocList( $toc, $lang );
1736 * Create a headline for content
1739 * @param int $level The level of the headline (1-6)
1740 * @param string $attribs Any attributes for the headline, starting with
1741 * a space and ending with '>'
1742 * This *must* be at least '>' for no attribs
1743 * @param string $anchor The anchor to give the headline (the bit after the #)
1744 * @param string $html HTML for the text of the header
1745 * @param string $link HTML to add for the section edit link
1746 * @param string|bool $fallbackAnchor A second, optional anchor to give for
1747 * backward compatibility (false to omit)
1749 * @return string HTML headline
1751 public static function makeHeadline( $level, $attribs, $anchor, $html,
1752 $link, $fallbackAnchor = false
1754 $anchorEscaped = htmlspecialchars( $anchor );
1756 if ( $fallbackAnchor !== false && $fallbackAnchor !== $anchor ) {
1757 $fallbackAnchor = htmlspecialchars( $fallbackAnchor );
1758 $fallback = "<span id=\"$fallbackAnchor\"></span>";
1760 return "<h$level$attribs"
1761 . "$fallback<span class=\"mw-headline\" id=\"$anchorEscaped\">$html</span>"
1767 * Split a link trail, return the "inside" portion and the remainder of the trail
1768 * as a two-element array
1769 * @param string $trail
1772 static function splitTrail( $trail ) {
1773 $regex = MediaWikiServices
::getInstance()->getContentLanguage()->linkTrail();
1775 if ( $trail !== '' && preg_match( $regex, $trail, $m ) ) {
1776 list( , $inside, $trail ) = $m;
1778 return [ $inside, $trail ];
1782 * Generate a rollback link for a given revision. Currently it's the
1783 * caller's responsibility to ensure that the revision is the top one. If
1784 * it's not, of course, the user will get an error message.
1786 * If the calling page is called with the parameter &bot=1, all rollback
1787 * links also get that parameter. It causes the edit itself and the rollback
1788 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1789 * changes, so this allows sysops to combat a busy vandal without bothering
1792 * If the option verify is set this function will return the link only in case the
1793 * revision can be reverted. Please note that due to performance limitations
1794 * it might be assumed that a user isn't the only contributor of a page while
1795 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1796 * work if $wgShowRollbackEditCount is disabled, so this can only function
1797 * as an additional check.
1799 * If the option noBrackets is set the rollback link wont be enclosed in "[]".
1801 * @since 1.16.3. $context added in 1.20. $options added in 1.21
1803 * @param Revision $rev
1804 * @param IContextSource|null $context Context to use or null for the main context.
1805 * @param array $options
1808 public static function generateRollback( $rev, IContextSource
$context = null,
1809 $options = [ 'verify' ]
1811 if ( $context === null ) {
1812 $context = RequestContext
::getMain();
1816 if ( in_array( 'verify', $options, true ) ) {
1817 $editCount = self
::getRollbackEditCount( $rev, true );
1818 if ( $editCount === false ) {
1823 $inner = self
::buildRollbackLink( $rev, $context, $editCount );
1825 if ( !in_array( 'noBrackets', $options, true ) ) {
1826 $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1829 if ( $context->getUser()->getBoolOption( 'showrollbackconfirmation' ) ) {
1830 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1831 $stats->increment( 'rollbackconfirmation.event.load' );
1832 $context->getOutput()->addModules( 'mediawiki.page.rollback.confirmation' );
1835 return '<span class="mw-rollback-link">' . $inner . '</span>';
1839 * This function will return the number of revisions which a rollback
1840 * would revert and, if $verify is set it will verify that a revision
1841 * can be reverted (that the user isn't the only contributor and the
1842 * revision we might rollback to isn't deleted). These checks can only
1843 * function as an additional check as this function only checks against
1844 * the last $wgShowRollbackEditCount edits.
1846 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1847 * is set and the user is the only contributor of the page.
1849 * @param Revision $rev
1850 * @param bool $verify Try to verify that this revision can really be rolled back
1851 * @return int|bool|null
1853 public static function getRollbackEditCount( $rev, $verify ) {
1854 global $wgShowRollbackEditCount;
1855 if ( !is_int( $wgShowRollbackEditCount ) ||
!$wgShowRollbackEditCount > 0 ) {
1856 // Nothing has happened, indicate this by returning 'null'
1860 $dbr = wfGetDB( DB_REPLICA
);
1862 // Up to the value of $wgShowRollbackEditCount revisions are counted
1863 $revQuery = Revision
::getQueryInfo();
1864 $res = $dbr->select(
1865 $revQuery['tables'],
1866 [ 'rev_user_text' => $revQuery['fields']['rev_user_text'], 'rev_deleted' ],
1867 // $rev->getPage() returns null sometimes
1868 [ 'rev_page' => $rev->getTitle()->getArticleID() ],
1871 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
1872 'ORDER BY' => 'rev_timestamp DESC',
1873 'LIMIT' => $wgShowRollbackEditCount +
1
1880 foreach ( $res as $row ) {
1881 if ( $rev->getUserText( RevisionRecord
::RAW
) != $row->rev_user_text
) {
1883 ( $row->rev_deleted
& RevisionRecord
::DELETED_TEXT
1884 ||
$row->rev_deleted
& RevisionRecord
::DELETED_USER
1886 // If the user or the text of the revision we might rollback
1887 // to is deleted in some way we can't rollback. Similar to
1888 // the sanity checks in WikiPage::commitRollback.
1897 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1898 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1899 // and there weren't any other revisions. That means that the current user is the only
1900 // editor, so we can't rollback
1907 * Build a raw rollback link, useful for collections of "tool" links
1909 * @since 1.16.3. $context added in 1.20. $editCount added in 1.21
1910 * @param Revision $rev
1911 * @param IContextSource|null $context Context to use or null for the main context.
1912 * @param int $editCount Number of edits that would be reverted
1913 * @return string HTML fragment
1915 public static function buildRollbackLink( $rev, IContextSource
$context = null,
1918 global $wgShowRollbackEditCount, $wgMiserMode;
1920 // To config which pages are affected by miser mode
1921 $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
1923 if ( $context === null ) {
1924 $context = RequestContext
::getMain();
1927 $title = $rev->getTitle();
1930 'action' => 'rollback',
1931 'from' => $rev->getUserText(),
1932 'token' => $context->getUser()->getEditToken( 'rollback' ),
1936 'data-mw' => 'interface',
1937 'title' => $context->msg( 'tooltip-rollback' )->text()
1940 $options = [ 'known', 'noclasses' ];
1942 if ( $context->getRequest()->getBool( 'bot' ) ) {
1944 $query['hidediff'] = '1';
1945 $query['bot'] = '1';
1948 $disableRollbackEditCount = false;
1949 if ( $wgMiserMode ) {
1950 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1951 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1952 $disableRollbackEditCount = true;
1958 if ( !$disableRollbackEditCount
1959 && is_int( $wgShowRollbackEditCount )
1960 && $wgShowRollbackEditCount > 0
1962 if ( !is_numeric( $editCount ) ) {
1963 $editCount = self
::getRollbackEditCount( $rev, false );
1966 if ( $editCount > $wgShowRollbackEditCount ) {
1967 $html = $context->msg( 'rollbacklinkcount-morethan' )
1968 ->numParams( $wgShowRollbackEditCount )->parse();
1970 $html = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1973 return self
::link( $title, $html, $attrs, $query, $options );
1976 $html = $context->msg( 'rollbacklink' )->escaped();
1977 return self
::link( $title, $html, $attrs, $query, $options );
1981 * Returns HTML for the "hidden categories on this page" list.
1984 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
1986 * @return string HTML output
1988 public static function formatHiddenCategories( $hiddencats ) {
1990 if ( count( $hiddencats ) > 0 ) {
1991 # Construct the HTML
1992 $outText = '<div class="mw-hiddenCategoriesExplanation">';
1993 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
1994 $outText .= "</div><ul>\n";
1996 foreach ( $hiddencats as $titleObj ) {
1997 # If it's hidden, it must exist - no need to check with a LinkBatch
1999 . self
::link( $titleObj, null, [], [], 'known' )
2002 $outText .= '</ul>';
2008 * Given the id of an interface element, constructs the appropriate title
2009 * attribute from the system messages. (Note, this is usually the id but
2010 * isn't always, because sometimes the accesskey needs to go on a different
2011 * element than the id, for reverse-compatibility, etc.)
2013 * @since 1.16.3 $msgParams added in 1.27
2014 * @param string $name Id of the element, minus prefixes.
2015 * @param string|array|null $options Null, string or array with some of the following options:
2016 * - 'withaccess' to add an access-key hint
2017 * - 'nonexisting' to add an accessibility hint that page does not exist
2018 * @param array $msgParams Parameters to pass to the message
2020 * @return string Contents of the title attribute (which you must HTML-
2021 * escape), or false for no title attribute
2023 public static function titleAttrib( $name, $options = null, array $msgParams = [] ) {
2024 $message = wfMessage( "tooltip-$name", $msgParams );
2025 if ( !$message->exists() ) {
2028 $tooltip = $message->text();
2029 # Compatibility: formerly some tooltips had [alt-.] hardcoded
2030 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2031 # Message equal to '-' means suppress it.
2032 if ( $tooltip == '-' ) {
2037 $options = (array)$options;
2039 if ( in_array( 'nonexisting', $options ) ) {
2040 $tooltip = wfMessage( 'red-link-title', $tooltip ?
: '' )->text();
2042 if ( in_array( 'withaccess', $options ) ) {
2043 $accesskey = self
::accesskey( $name );
2044 if ( $accesskey !== false ) {
2045 // Should be build the same as in jquery.accessKeyLabel.js
2046 if ( $tooltip === false ||
$tooltip === '' ) {
2047 $tooltip = wfMessage( 'brackets', $accesskey )->text();
2049 $tooltip .= wfMessage( 'word-separator' )->text();
2050 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
2058 public static $accesskeycache;
2061 * Given the id of an interface element, constructs the appropriate
2062 * accesskey attribute from the system messages. (Note, this is usually
2063 * the id but isn't always, because sometimes the accesskey needs to go on
2064 * a different element than the id, for reverse-compatibility, etc.)
2067 * @param string $name Id of the element, minus prefixes.
2068 * @return string Contents of the accesskey attribute (which you must HTML-
2069 * escape), or false for no accesskey attribute
2071 public static function accesskey( $name ) {
2072 if ( isset( self
::$accesskeycache[$name] ) ) {
2073 return self
::$accesskeycache[$name];
2076 $message = wfMessage( "accesskey-$name" );
2078 if ( !$message->exists() ) {
2081 $accesskey = $message->plain();
2082 if ( $accesskey === '' ||
$accesskey === '-' ) {
2083 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2084 # attribute, but this is broken for accesskey: that might be a useful
2090 self
::$accesskeycache[$name] = $accesskey;
2091 return self
::$accesskeycache[$name];
2095 * Get a revision-deletion link, or disabled link, or nothing, depending
2096 * on user permissions & the settings on the revision.
2098 * Will use forward-compatible revision ID in the Special:RevDelete link
2099 * if possible, otherwise the timestamp-based ID which may break after
2103 * @param Revision $rev
2104 * @param LinkTarget $title
2105 * @return string HTML fragment
2107 public static function getRevDeleteLink( User
$user, Revision
$rev, LinkTarget
$title ) {
2108 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
2109 $canHide = $permissionManager->userHasRight( $user, 'deleterevision' );
2110 $canHideHistory = $permissionManager->userHasRight( $user, 'deletedhistory' );
2111 if ( !$canHide && !( $rev->getVisibility() && $canHideHistory ) ) {
2115 if ( !$rev->userCan( RevisionRecord
::DELETED_RESTRICTED
, $user ) ) {
2116 return self
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2118 $prefixedDbKey = MediaWikiServices
::getInstance()->getTitleFormatter()->
2119 getPrefixedDBkey( $title );
2120 if ( $rev->getId() ) {
2121 // RevDelete links using revision ID are stable across
2122 // page deletion and undeletion; use when possible.
2124 'type' => 'revision',
2125 'target' => $prefixedDbKey,
2126 'ids' => $rev->getId()
2129 // Older deleted entries didn't save a revision ID.
2130 // We have to refer to these by timestamp, ick!
2132 'type' => 'archive',
2133 'target' => $prefixedDbKey,
2134 'ids' => $rev->getTimestamp()
2137 return self
::revDeleteLink( $query,
2138 $rev->isDeleted( RevisionRecord
::DELETED_RESTRICTED
), $canHide );
2142 * Creates a (show/hide) link for deleting revisions/log entries
2144 * @param array $query Query parameters to be passed to link()
2145 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2146 * @param bool $delete Set to true to use (show/hide) rather than (show)
2148 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2149 * span to allow for customization of appearance with CSS
2151 public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2152 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
2153 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2154 $html = wfMessage( $msgKey )->escaped();
2155 $tag = $restricted ?
'strong' : 'span';
2156 $link = self
::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2159 [ 'class' => 'mw-revdelundel-link' ],
2160 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2165 * Creates a dead (show/hide) link for deleting revisions/log entries
2168 * @param bool $delete Set to true to use (show/hide) rather than (show)
2170 * @return string HTML text wrapped in a span to allow for customization
2171 * of appearance with CSS
2173 public static function revDeleteLinkDisabled( $delete = true ) {
2174 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2175 $html = wfMessage( $msgKey )->escaped();
2176 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2177 return Xml
::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2181 * Returns the attributes for the tooltip and access key.
2183 * @since 1.16.3. $msgParams introduced in 1.27
2184 * @param string $name
2185 * @param array $msgParams Params for constructing the message
2186 * @param string|array|null $options Options to be passed to titleAttrib.
2188 * @see Linker::titleAttrib for what options could be passed to $options.
2192 public static function tooltipAndAccesskeyAttribs(
2194 array $msgParams = [],
2197 $options = (array)$options;
2198 $options[] = 'withaccess';
2201 'title' => self
::titleAttrib( $name, $options, $msgParams ),
2202 'accesskey' => self
::accesskey( $name )
2204 if ( $attribs['title'] === false ) {
2205 unset( $attribs['title'] );
2207 if ( $attribs['accesskey'] === false ) {
2208 unset( $attribs['accesskey'] );
2214 * Returns raw bits of HTML, use titleAttrib()
2216 * @param string $name
2217 * @param array|null $options
2218 * @return null|string
2220 public static function tooltip( $name, $options = null ) {
2221 $tooltip = self
::titleAttrib( $name, $options );
2222 if ( $tooltip === false ) {
2225 return Xml
::expandAttributes( [