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 * Get the appropriate HTML attributes to add to the "a" element of an interwiki link.
45 * @deprecated since 1.25
47 * @param string $title The title text for the link, URL-encoded (???) but
49 * @param string $unused Unused
50 * @param string $class The contents of the class attribute; if an empty
51 * string is passed, which is the default value, defaults to 'external'.
54 static function getInterwikiLinkAttributes( $title, $unused = null, $class = 'external' ) {
57 wfDeprecated( __METHOD__
, '1.25' );
59 # @todo FIXME: We have a whole bunch of handling here that doesn't happen in
60 # getExternalLinkAttributes, why?
61 $title = urldecode( $title );
62 $title = $wgContLang->checkTitleEncoding( $title );
63 $title = preg_replace( '/[\\x00-\\x1f]/', ' ', $title );
65 return self
::getLinkAttributesInternal( $title, $class );
69 * Get the appropriate HTML attributes to add to the "a" element of an internal link.
72 * @deprecated since 1.25
74 * @param string $title The title text for the link, URL-encoded (???) but
76 * @param string $unused Unused
77 * @param string $class The contents of the class attribute, default none
80 static function getInternalLinkAttributes( $title, $unused = null, $class = '' ) {
81 wfDeprecated( __METHOD__
, '1.25' );
83 $title = urldecode( $title );
84 $title = strtr( $title, '_', ' ' );
85 return self
::getLinkAttributesInternal( $title, $class );
89 * Get the appropriate HTML attributes to add to the "a" element of an internal
90 * link, given the Title object for the page we want to link to.
93 * @deprecated since 1.25
96 * @param string $unused Unused
97 * @param string $class The contents of the class attribute, default none
98 * @param string|bool $title Optional (unescaped) string to use in the title
99 * attribute; if false, default to the name of the page we're linking to
102 static function getInternalLinkAttributesObj( $nt, $unused = null, $class = '', $title = false ) {
103 wfDeprecated( __METHOD__
, '1.25' );
105 if ( $title === false ) {
106 $title = $nt->getPrefixedText();
108 return self
::getLinkAttributesInternal( $title, $class );
112 * Common code for getLinkAttributesX functions
115 * @deprecated since 1.25
117 * @param string $title
118 * @param string $class
122 private static function getLinkAttributesInternal( $title, $class ) {
123 wfDeprecated( __METHOD__
, '1.25' );
125 $title = htmlspecialchars( $title );
126 $class = htmlspecialchars( $class );
128 if ( $class != '' ) {
129 $r .= " class=\"$class\"";
131 if ( $title != '' ) {
132 $r .= " title=\"$title\"";
138 * Return the CSS colour of a known link
140 * @deprecated since 1.28, use LinkRenderer::getLinkClasses() instead
143 * @param LinkTarget $t
144 * @param int $threshold User defined threshold
145 * @return string CSS class
147 public static function getLinkColour( LinkTarget
$t, $threshold ) {
148 wfDeprecated( __METHOD__
, '1.28' );
149 $services = MediaWikiServices
::getInstance();
150 $linkRenderer = $services->getLinkRenderer();
151 if ( $threshold !== $linkRenderer->getStubThreshold() ) {
152 // Need to create a new instance with the right stub threshold...
153 $linkRenderer = $services->getLinkRendererFactory()->create();
154 $linkRenderer->setStubThreshold( $threshold );
157 return $linkRenderer->getLinkClasses( $t );
161 * This function returns an HTML link to the given target. It serves a few
163 * 1) If $target is a Title, the correct URL to link to will be figured
165 * 2) It automatically adds the usual classes for various types of link
166 * targets: "new" for red links, "stub" for short articles, etc.
167 * 3) It escapes all attribute values safely so there's no risk of XSS.
168 * 4) It provides a default tooltip if the target is a Title (the page
169 * name of the target).
170 * link() replaces the old functions in the makeLink() family.
172 * @since 1.18 Method exists since 1.16 as non-static, made static in 1.18.
173 * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
175 * @param Title $target Can currently only be a Title, but this may
176 * change to support Images, literal URLs, etc.
177 * @param string $html The HTML contents of the <a> element, i.e.,
178 * the link text. This is raw HTML and will not be escaped. If null,
179 * defaults to the prefixed text of the Title; or if the Title is just a
180 * fragment, the contents of the fragment.
181 * @param array $customAttribs A key => value array of extra HTML attributes,
182 * such as title and class. (href is ignored.) Classes will be
183 * merged with the default classes, while other attributes will replace
184 * default attributes. All passed attribute values will be HTML-escaped.
185 * A false attribute value means to suppress that attribute.
186 * @param array $query The query string to append to the URL
187 * you're linking to, in key => value array form. Query keys and values
188 * will be URL-encoded.
189 * @param string|array $options String or array of strings:
190 * 'known': Page is known to exist, so don't check if it does.
191 * 'broken': Page is known not to exist, so don't check if it does.
192 * 'noclasses': Don't add any classes automatically (includes "new",
193 * "stub", "mw-redirect", "extiw"). Only use the class attribute
194 * provided, if any, so you get a simple blue link with no funny i-
196 * 'forcearticlepath': Use the article path always, even with a querystring.
197 * Has compatibility issues on some setups, so avoid wherever possible.
198 * 'http': Force a full URL with http:// as the scheme.
199 * 'https': Force a full URL with https:// as the scheme.
200 * 'stubThreshold' => (int): Stub threshold to use when determining link classes.
201 * @return string HTML <a> attribute
203 public static function link(
204 $target, $html = null, $customAttribs = [], $query = [], $options = []
206 if ( !$target instanceof Title
) {
207 wfWarn( __METHOD__
. ': Requires $target to be a Title object.', 2 );
208 return "<!-- ERROR -->$html";
211 if ( is_string( $query ) ) {
212 // some functions withing core using this still hand over query strings
213 wfDeprecated( __METHOD__
. ' with parameter $query as string (should be array)', '1.20' );
214 $query = wfCgiToArray( $query );
217 $services = MediaWikiServices
::getInstance();
218 $options = (array)$options;
220 // Custom options, create new LinkRenderer
221 if ( !isset( $options['stubThreshold'] ) ) {
222 $defaultLinkRenderer = $services->getLinkRenderer();
223 $options['stubThreshold'] = $defaultLinkRenderer->getStubThreshold();
225 $linkRenderer = $services->getLinkRendererFactory()
226 ->createFromLegacyOptions( $options );
228 $linkRenderer = $services->getLinkRenderer();
231 if ( $html !== null ) {
232 $text = new HtmlArmor( $html );
234 $text = $html; // null
236 if ( in_array( 'known', $options, true ) ) {
237 return $linkRenderer->makeKnownLink( $target, $text, $customAttribs, $query );
238 } elseif ( in_array( 'broken', $options, true ) ) {
239 return $linkRenderer->makeBrokenLink( $target, $text, $customAttribs, $query );
240 } elseif ( in_array( 'noclasses', $options, true ) ) {
241 return $linkRenderer->makePreloadedLink( $target, $text, '', $customAttribs, $query );
243 return $linkRenderer->makeLink( $target, $text, $customAttribs, $query );
248 * Identical to link(), except $options defaults to 'known'.
251 * @deprecated since 1.28, use MediaWiki\Linker\LinkRenderer instead
255 public static function linkKnown(
256 $target, $html = null, $customAttribs = [],
257 $query = [], $options = [ 'known' ]
259 return self
::link( $target, $html, $customAttribs, $query, $options );
263 * Make appropriate markup for a link to the current article. This is
264 * currently rendered as the bold link text. The calling sequence is the
265 * same as the other make*LinkObj static functions, despite $query not
270 * @param string $html [optional]
271 * @param string $query [optional]
272 * @param string $trail [optional]
273 * @param string $prefix [optional]
277 public static function makeSelfLinkObj( $nt, $html = '', $query = '', $trail = '', $prefix = '' ) {
278 $ret = "<strong class=\"selflink\">{$prefix}{$html}</strong>{$trail}";
279 if ( !Hooks
::run( 'SelfLinkBegin', [ $nt, &$html, &$trail, &$prefix, &$ret ] ) ) {
284 $html = htmlspecialchars( $nt->getPrefixedText() );
286 list( $inside, $trail ) = self
::splitTrail( $trail );
287 return "<strong class=\"selflink\">{$prefix}{$html}{$inside}</strong>{$trail}";
291 * Get a message saying that an invalid title was encountered.
292 * This should be called after a method like Title::makeTitleSafe() returned
293 * a value indicating that the title object is invalid.
295 * @param IContextSource $context Context to use to get the messages
296 * @param int $namespace Namespace number
297 * @param string $title Text of the title, without the namespace part
300 public static function getInvalidTitleDescription( IContextSource
$context, $namespace, $title ) {
303 // First we check whether the namespace exists or not.
304 if ( MWNamespace
::exists( $namespace ) ) {
305 if ( $namespace == NS_MAIN
) {
306 $name = $context->msg( 'blanknamespace' )->text();
308 $name = $wgContLang->getFormattedNsText( $namespace );
310 return $context->msg( 'invalidtitle-knownnamespace', $namespace, $name, $title )->text();
312 return $context->msg( 'invalidtitle-unknownnamespace', $namespace, $title )->text();
318 * @param LinkTarget $target
319 * @return LinkTarget|Title You will get back the same type you passed in, or a Title object
321 public static function normaliseSpecialPage( LinkTarget
$target ) {
322 if ( $target->getNamespace() == NS_SPECIAL
) {
323 list( $name, $subpage ) = SpecialPageFactory
::resolveAlias( $target->getDBkey() );
327 $ret = SpecialPage
::getTitleFor( $name, $subpage, $target->getFragment() );
335 * Returns the filename part of an url.
336 * Used as alternative text for external images.
342 private static function fnamePart( $url ) {
343 $basename = strrchr( $url, '/' );
344 if ( false === $basename ) {
347 $basename = substr( $basename, 1 );
353 * Return the code for images which were added via external links,
354 * via Parser::maybeMakeExternalImage().
362 public static function makeExternalImage( $url, $alt = '' ) {
364 $alt = self
::fnamePart( $url );
367 $success = Hooks
::run( 'LinkerMakeExternalImage', [ &$url, &$alt, &$img ] );
369 wfDebug( "Hook LinkerMakeExternalImage changed the output of external image "
370 . "with url {$url} and alt text {$alt} to {$img}\n", true );
373 return Html
::element( 'img',
380 * Given parameters derived from [[Image:Foo|options...]], generate the
381 * HTML that that syntax inserts in the page.
383 * @param Parser $parser
384 * @param Title $title Title object of the file (not the currently viewed page)
385 * @param File $file File object, or false if it doesn't exist
386 * @param array $frameParams Associative array of parameters external to the media handler.
387 * Boolean parameters are indicated by presence or absence, the value is arbitrary and
388 * will often be false.
389 * thumbnail If present, downscale and frame
390 * manualthumb Image name to use as a thumbnail, instead of automatic scaling
391 * framed Shows image in original size in a frame
392 * frameless Downscale but don't frame
393 * upright If present, tweak default sizes for portrait orientation
394 * upright_factor Fudge factor for "upright" tweak (default 0.75)
395 * border If present, show a border around the image
396 * align Horizontal alignment (left, right, center, none)
397 * valign Vertical alignment (baseline, sub, super, top, text-top, middle,
398 * bottom, text-bottom)
399 * alt Alternate text for image (i.e. alt attribute). Plain text.
400 * class HTML for image classes. Plain text.
401 * caption HTML for image caption.
402 * link-url URL to link to
403 * link-title Title object to link to
404 * link-target Value for the target attribute, only with link-url
405 * no-link Boolean, suppress description link
407 * @param array $handlerParams Associative array of media handler parameters, to be passed
408 * to transform(). Typical keys are "width" and "page".
409 * @param string|bool $time Timestamp of the file, set as false for current
410 * @param string $query Query params for desc url
411 * @param int|null $widthOption Used by the parser to remember the user preference thumbnailsize
413 * @return string HTML for an image, with links, wrappers, etc.
415 public static function makeImageLink( Parser
$parser, Title
$title,
416 $file, $frameParams = [], $handlerParams = [], $time = false,
417 $query = "", $widthOption = null
420 $dummy = new DummyLinker
;
421 if ( !Hooks
::run( 'ImageBeforeProduceHTML', [ &$dummy, &$title,
422 &$file, &$frameParams, &$handlerParams, &$time, &$res ] ) ) {
426 if ( $file && !$file->allowInlineDisplay() ) {
427 wfDebug( __METHOD__
. ': ' . $title->getPrefixedDBkey() . " does not allow inline display\n" );
428 return self
::link( $title );
433 $hp =& $handlerParams;
435 // Clean up parameters
436 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
437 if ( !isset( $fp['align'] ) ) {
440 if ( !isset( $fp['alt'] ) ) {
443 if ( !isset( $fp['title'] ) ) {
446 if ( !isset( $fp['class'] ) ) {
450 $prefix = $postfix = '';
452 if ( 'center' == $fp['align'] ) {
453 $prefix = '<div class="center">';
455 $fp['align'] = 'none';
457 if ( $file && !isset( $hp['width'] ) ) {
458 if ( isset( $hp['height'] ) && $file->isVectorized() ) {
459 // If its a vector image, and user only specifies height
460 // we don't want it to be limited by its "normal" width.
461 global $wgSVGMaxSize;
462 $hp['width'] = $wgSVGMaxSize;
464 $hp['width'] = $file->getWidth( $page );
467 if ( isset( $fp['thumbnail'] )
468 ||
isset( $fp['manualthumb'] )
469 ||
isset( $fp['framed'] )
470 ||
isset( $fp['frameless'] )
473 global $wgThumbLimits, $wgThumbUpright;
475 if ( $widthOption === null ||
!isset( $wgThumbLimits[$widthOption] ) ) {
476 $widthOption = User
::getDefaultOption( 'thumbsize' );
479 // Reduce width for upright images when parameter 'upright' is used
480 if ( isset( $fp['upright'] ) && $fp['upright'] == 0 ) {
481 $fp['upright'] = $wgThumbUpright;
484 // For caching health: If width scaled down due to upright
485 // parameter, round to full __0 pixel to avoid the creation of a
486 // lot of odd thumbs.
487 $prefWidth = isset( $fp['upright'] ) ?
488 round( $wgThumbLimits[$widthOption] * $fp['upright'], -1 ) :
489 $wgThumbLimits[$widthOption];
491 // Use width which is smaller: real image width or user preference width
492 // Unless image is scalable vector.
493 if ( !isset( $hp['height'] ) && ( $hp['width'] <= 0 ||
494 $prefWidth < $hp['width'] ||
$file->isVectorized() ) ) {
495 $hp['width'] = $prefWidth;
500 if ( isset( $fp['thumbnail'] ) ||
isset( $fp['manualthumb'] ) ||
isset( $fp['framed'] ) ) {
501 # Create a thumbnail. Alignment depends on the writing direction of
502 # the page content language (right-aligned for LTR languages,
503 # left-aligned for RTL languages)
504 # If a thumbnail width has not been provided, it is set
505 # to the default user option as specified in Language*.php
506 if ( $fp['align'] == '' ) {
507 $fp['align'] = $parser->getTargetLanguage()->alignEnd();
509 return $prefix . self
::makeThumbLink2( $title, $file, $fp, $hp, $time, $query ) . $postfix;
512 if ( $file && isset( $fp['frameless'] ) ) {
513 $srcWidth = $file->getWidth( $page );
514 # For "frameless" option: do not present an image bigger than the
515 # source (for bitmap-style images). This is the same behavior as the
516 # "thumb" option does it already.
517 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
518 $hp['width'] = $srcWidth;
522 if ( $file && isset( $hp['width'] ) ) {
523 # Create a resized image, without the additional thumbnail features
524 $thumb = $file->transform( $hp );
530 $s = self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
532 self
::processResponsiveImages( $file, $thumb, $hp );
535 'title' => $fp['title'],
536 'valign' => isset( $fp['valign'] ) ?
$fp['valign'] : false,
537 'img-class' => $fp['class'] ];
538 if ( isset( $fp['border'] ) ) {
539 $params['img-class'] .= ( $params['img-class'] !== '' ?
' ' : '' ) . 'thumbborder';
541 $params = self
::getImageLinkMTOParams( $fp, $query, $parser ) +
$params;
543 $s = $thumb->toHtml( $params );
545 if ( $fp['align'] != '' ) {
546 $s = "<div class=\"float{$fp['align']}\">{$s}</div>";
548 return str_replace( "\n", ' ', $prefix . $s . $postfix );
552 * Get the link parameters for MediaTransformOutput::toHtml() from given
553 * frame parameters supplied by the Parser.
554 * @param array $frameParams The frame parameters
555 * @param string $query An optional query string to add to description page links
556 * @param Parser|null $parser
559 private static function getImageLinkMTOParams( $frameParams, $query = '', $parser = null ) {
561 if ( isset( $frameParams['link-url'] ) && $frameParams['link-url'] !== '' ) {
562 $mtoParams['custom-url-link'] = $frameParams['link-url'];
563 if ( isset( $frameParams['link-target'] ) ) {
564 $mtoParams['custom-target-link'] = $frameParams['link-target'];
567 $extLinkAttrs = $parser->getExternalLinkAttribs( $frameParams['link-url'] );
568 foreach ( $extLinkAttrs as $name => $val ) {
569 // Currently could include 'rel' and 'target'
570 $mtoParams['parser-extlink-' . $name] = $val;
573 } elseif ( isset( $frameParams['link-title'] ) && $frameParams['link-title'] !== '' ) {
574 $mtoParams['custom-title-link'] = self
::normaliseSpecialPage( $frameParams['link-title'] );
575 } elseif ( !empty( $frameParams['no-link'] ) ) {
578 $mtoParams['desc-link'] = true;
579 $mtoParams['desc-query'] = $query;
585 * Make HTML for a thumbnail including image, border and caption
586 * @param Title $title
587 * @param File|bool $file File object or false if it doesn't exist
588 * @param string $label
590 * @param string $align
591 * @param array $params
592 * @param bool $framed
593 * @param string $manualthumb
596 public static function makeThumbLinkObj( Title
$title, $file, $label = '', $alt,
597 $align = 'right', $params = [], $framed = false, $manualthumb = ""
605 $frameParams['framed'] = true;
607 if ( $manualthumb ) {
608 $frameParams['manualthumb'] = $manualthumb;
610 return self
::makeThumbLink2( $title, $file, $frameParams, $params );
614 * @param Title $title
616 * @param array $frameParams
617 * @param array $handlerParams
619 * @param string $query
622 public static function makeThumbLink2( Title
$title, $file, $frameParams = [],
623 $handlerParams = [], $time = false, $query = ""
625 $exists = $file && $file->exists();
629 $hp =& $handlerParams;
631 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
632 if ( !isset( $fp['align'] ) ) {
633 $fp['align'] = 'right';
635 if ( !isset( $fp['alt'] ) ) {
638 if ( !isset( $fp['title'] ) ) {
641 if ( !isset( $fp['caption'] ) ) {
645 if ( empty( $hp['width'] ) ) {
646 // Reduce width for upright images when parameter 'upright' is used
647 $hp['width'] = isset( $fp['upright'] ) ?
130 : 180;
651 $manualthumb = false;
654 $outerWidth = $hp['width'] +
2;
656 if ( isset( $fp['manualthumb'] ) ) {
657 # Use manually specified thumbnail
658 $manual_title = Title
::makeTitleSafe( NS_FILE
, $fp['manualthumb'] );
659 if ( $manual_title ) {
660 $manual_img = wfFindFile( $manual_title );
662 $thumb = $manual_img->getUnscaledThumb( $hp );
668 } elseif ( isset( $fp['framed'] ) ) {
669 // Use image dimensions, don't scale
670 $thumb = $file->getUnscaledThumb( $hp );
673 # Do not present an image bigger than the source, for bitmap-style images
674 # This is a hack to maintain compatibility with arbitrary pre-1.10 behavior
675 $srcWidth = $file->getWidth( $page );
676 if ( $srcWidth && !$file->mustRender() && $hp['width'] > $srcWidth ) {
677 $hp['width'] = $srcWidth;
679 $thumb = $file->transform( $hp );
683 $outerWidth = $thumb->getWidth() +
2;
685 $outerWidth = $hp['width'] +
2;
689 # ThumbnailImage::toHtml() already adds page= onto the end of DjVu URLs
690 # So we don't need to pass it here in $query. However, the URL for the
691 # zoom icon still needs it, so we make a unique query for it. See bug 14771
692 $url = $title->getLocalURL( $query );
694 $url = wfAppendQuery( $url, [ 'page' => $page ] );
697 && !isset( $fp['link-title'] )
698 && !isset( $fp['link-url'] )
699 && !isset( $fp['no-link'] ) ) {
700 $fp['link-url'] = $url;
703 $s = "<div class=\"thumb t{$fp['align']}\">"
704 . "<div class=\"thumbinner\" style=\"width:{$outerWidth}px;\">";
707 $s .= self
::makeBrokenImageLinkObj( $title, $fp['title'], '', '', '', $time == true );
709 } elseif ( !$thumb ) {
710 $s .= wfMessage( 'thumbnail_error', '' )->escaped();
713 if ( !$noscale && !$manualthumb ) {
714 self
::processResponsiveImages( $file, $thumb, $hp );
718 'title' => $fp['title'],
719 'img-class' => ( isset( $fp['class'] ) && $fp['class'] !== ''
721 : '' ) . 'thumbimage'
723 $params = self
::getImageLinkMTOParams( $fp, $query ) +
$params;
724 $s .= $thumb->toHtml( $params );
725 if ( isset( $fp['framed'] ) ) {
728 $zoomIcon = Html
::rawElement( 'div', [ 'class' => 'magnify' ],
729 Html
::rawElement( 'a', [
731 'class' => 'internal',
732 'title' => wfMessage( 'thumbnail-more' )->text() ],
736 $s .= ' <div class="thumbcaption">' . $zoomIcon . $fp['caption'] . "</div></div></div>";
737 return str_replace( "\n", ' ', $s );
741 * Process responsive images: add 1.5x and 2x subimages to the thumbnail, where
745 * @param MediaTransformOutput $thumb
746 * @param array $hp Image parameters
748 public static function processResponsiveImages( $file, $thumb, $hp ) {
749 global $wgResponsiveImages;
750 if ( $wgResponsiveImages && $thumb && !$thumb->isError() ) {
752 $hp15['width'] = round( $hp['width'] * 1.5 );
754 $hp20['width'] = $hp['width'] * 2;
755 if ( isset( $hp['height'] ) ) {
756 $hp15['height'] = round( $hp['height'] * 1.5 );
757 $hp20['height'] = $hp['height'] * 2;
760 $thumb15 = $file->transform( $hp15 );
761 $thumb20 = $file->transform( $hp20 );
762 if ( $thumb15 && !$thumb15->isError() && $thumb15->getUrl() !== $thumb->getUrl() ) {
763 $thumb->responsiveUrls
['1.5'] = $thumb15->getUrl();
765 if ( $thumb20 && !$thumb20->isError() && $thumb20->getUrl() !== $thumb->getUrl() ) {
766 $thumb->responsiveUrls
['2'] = $thumb20->getUrl();
772 * Make a "broken" link to an image
775 * @param Title $title
776 * @param string $label Link label (plain text)
777 * @param string $query Query string
778 * @param string $unused1 Unused parameter kept for b/c
779 * @param string $unused2 Unused parameter kept for b/c
780 * @param bool $time A file of a certain timestamp was requested
783 public static function makeBrokenImageLinkObj( $title, $label = '',
784 $query = '', $unused1 = '', $unused2 = '', $time = false
786 if ( !$title instanceof Title
) {
787 wfWarn( __METHOD__
. ': Requires $title to be a Title object.' );
788 return "<!-- ERROR -->" . htmlspecialchars( $label );
791 global $wgEnableUploads, $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
792 if ( $label == '' ) {
793 $label = $title->getPrefixedText();
795 $encLabel = htmlspecialchars( $label );
796 $currentExists = $time ?
( wfFindFile( $title ) != false ) : false;
798 if ( ( $wgUploadMissingFileUrl ||
$wgUploadNavigationUrl ||
$wgEnableUploads )
801 $redir = RepoGroup
::singleton()->getLocalRepo()->checkRedirect( $title );
804 // We already know it's a redirect, so mark it
809 [ 'class' => 'mw-redirect' ],
810 wfCgiToArray( $query ),
811 [ 'known', 'noclasses' ]
815 $href = self
::getUploadUrl( $title, $query );
817 return '<a href="' . htmlspecialchars( $href ) . '" class="new" title="' .
818 htmlspecialchars( $title->getPrefixedText(), ENT_QUOTES
) . '">' .
822 return self
::link( $title, $encLabel, [], wfCgiToArray( $query ), [ 'known', 'noclasses' ] );
826 * Get the URL to upload a certain file
829 * @param Title $destFile Title object of the file to upload
830 * @param string $query Urlencoded query string to prepend
831 * @return string Urlencoded URL
833 protected static function getUploadUrl( $destFile, $query = '' ) {
834 global $wgUploadMissingFileUrl, $wgUploadNavigationUrl;
835 $q = 'wpDestFile=' . $destFile->getPartialURL();
836 if ( $query != '' ) {
840 if ( $wgUploadMissingFileUrl ) {
841 return wfAppendQuery( $wgUploadMissingFileUrl, $q );
842 } elseif ( $wgUploadNavigationUrl ) {
843 return wfAppendQuery( $wgUploadNavigationUrl, $q );
845 $upload = SpecialPage
::getTitleFor( 'Upload' );
846 return $upload->getLocalURL( $q );
851 * Create a direct link to a given uploaded file.
854 * @param Title $title
855 * @param string $html Pre-sanitized HTML
856 * @param string $time MW timestamp of file creation time
857 * @return string HTML
859 public static function makeMediaLinkObj( $title, $html = '', $time = false ) {
860 $img = wfFindFile( $title, [ 'time' => $time ] );
861 return self
::makeMediaLinkFile( $title, $img, $html );
865 * Create a direct link to a given uploaded file.
866 * This will make a broken link if $file is false.
869 * @param Title $title
870 * @param File|bool $file File object or false
871 * @param string $html Pre-sanitized HTML
872 * @return string HTML
874 * @todo Handle invalid or missing images better.
876 public static function makeMediaLinkFile( Title
$title, $file, $html = '' ) {
877 if ( $file && $file->exists() ) {
878 $url = $file->getUrl();
881 $url = self
::getUploadUrl( $title );
885 $alt = $title->getText();
897 if ( !Hooks
::run( 'LinkerMakeMediaLinkFile',
898 [ $title, $file, &$html, &$attribs, &$ret ] ) ) {
899 wfDebug( "Hook LinkerMakeMediaLinkFile changed the output of link "
900 . "with url {$url} and text {$html} to {$ret}\n", true );
904 return Html
::rawElement( 'a', $attribs, $html );
908 * Make a link to a special page given its name and, optionally,
909 * a message key from the link text.
910 * Usage example: Linker::specialLink( 'Recentchanges' )
913 * @param string $name
917 public static function specialLink( $name, $key = '' ) {
919 $key = strtolower( $name );
922 return self
::linkKnown( SpecialPage
::getTitleFor( $name ), wfMessage( $key )->text() );
926 * Make an external link
927 * @since 1.16.3. $title added in 1.21
928 * @param string $url URL to link to
929 * @param string $text Text of link
930 * @param bool $escape Do we escape the link text?
931 * @param string $linktype Type of external link. Gets added to the classes
932 * @param array $attribs Array of extra attributes to <a>
933 * @param Title|null $title Title object used for title specific link attributes
936 public static function makeExternalLink( $url, $text, $escape = true,
937 $linktype = '', $attribs = [], $title = null
942 $class .= " $linktype";
944 if ( isset( $attribs['class'] ) && $attribs['class'] ) {
945 $class .= " {$attribs['class']}";
947 $attribs['class'] = $class;
950 $text = htmlspecialchars( $text );
956 $newRel = Parser
::getExternalLinkRel( $url, $title );
957 if ( !isset( $attribs['rel'] ) ||
$attribs['rel'] === '' ) {
958 $attribs['rel'] = $newRel;
959 } elseif ( $newRel !== '' ) {
960 // Merge the rel attributes.
961 $newRels = explode( ' ', $newRel );
962 $oldRels = explode( ' ', $attribs['rel'] );
963 $combined = array_unique( array_merge( $newRels, $oldRels ) );
964 $attribs['rel'] = implode( ' ', $combined );
967 $success = Hooks
::run( 'LinkerMakeExternalLink',
968 [ &$url, &$text, &$link, &$attribs, $linktype ] );
970 wfDebug( "Hook LinkerMakeExternalLink changed the output of link "
971 . "with url {$url} and text {$text} to {$link}\n", true );
974 $attribs['href'] = $url;
975 return Html
::rawElement( 'a', $attribs, $text );
979 * Make user link (or user contributions for unregistered users)
980 * @param int $userId User id in database.
981 * @param string $userName User name in database.
982 * @param string $altUserName Text to display instead of the user name (optional)
983 * @return string HTML fragment
984 * @since 1.16.3. $altUserName was added in 1.19.
986 public static function userLink( $userId, $userName, $altUserName = false ) {
987 $classes = 'mw-userlink';
988 if ( $userId == 0 ) {
989 $page = SpecialPage
::getTitleFor( 'Contributions', $userName );
990 if ( $altUserName === false ) {
991 $altUserName = IP
::prettifyIP( $userName );
993 $classes .= ' mw-anonuserlink'; // Separate link class for anons (bug 43179)
995 $page = Title
::makeTitle( NS_USER
, $userName );
1000 htmlspecialchars( $altUserName !== false ?
$altUserName : $userName ),
1001 [ 'class' => $classes ]
1006 * Generate standard user tool links (talk, contributions, block link, etc.)
1009 * @param int $userId User identifier
1010 * @param string $userText User name or IP address
1011 * @param bool $redContribsWhenNoEdits Should the contributions link be
1012 * red if the user has no edits?
1013 * @param int $flags Customisation flags (e.g. Linker::TOOL_LINKS_NOBLOCK
1014 * and Linker::TOOL_LINKS_EMAIL).
1015 * @param int $edits User edit count (optional, for performance)
1016 * @return string HTML fragment
1018 public static function userToolLinks(
1019 $userId, $userText, $redContribsWhenNoEdits = false, $flags = 0, $edits = null
1021 global $wgUser, $wgDisableAnonTalk, $wgLang;
1022 $talkable = !( $wgDisableAnonTalk && 0 == $userId );
1023 $blockable = !( $flags & self
::TOOL_LINKS_NOBLOCK
);
1024 $addEmailLink = $flags & self
::TOOL_LINKS_EMAIL
&& $userId;
1028 $items[] = self
::userTalkLink( $userId, $userText );
1031 // check if the user has an edit
1033 if ( $redContribsWhenNoEdits ) {
1034 if ( intval( $edits ) === 0 && $edits !== 0 ) {
1035 $user = User
::newFromId( $userId );
1036 $edits = $user->getEditCount();
1038 if ( $edits === 0 ) {
1039 $attribs['class'] = 'new';
1042 $contribsPage = SpecialPage
::getTitleFor( 'Contributions', $userText );
1044 $items[] = self
::link( $contribsPage, wfMessage( 'contribslink' )->escaped(), $attribs );
1046 if ( $blockable && $wgUser->isAllowed( 'block' ) ) {
1047 $items[] = self
::blockLink( $userId, $userText );
1050 if ( $addEmailLink && $wgUser->canSendEmail() ) {
1051 $items[] = self
::emailLink( $userId, $userText );
1054 Hooks
::run( 'UserToolLinksEdit', [ $userId, $userText, &$items ] );
1057 return wfMessage( 'word-separator' )->escaped()
1058 . '<span class="mw-usertoollinks">'
1059 . wfMessage( 'parentheses' )->rawParams( $wgLang->pipeList( $items ) )->escaped()
1067 * Alias for userToolLinks( $userId, $userText, true );
1069 * @param int $userId User identifier
1070 * @param string $userText User name or IP address
1071 * @param int $edits User edit count (optional, for performance)
1074 public static function userToolLinksRedContribs( $userId, $userText, $edits = null ) {
1075 return self
::userToolLinks( $userId, $userText, true, 0, $edits );
1080 * @param int $userId User id in database.
1081 * @param string $userText User name in database.
1082 * @return string HTML fragment with user talk link
1084 public static function userTalkLink( $userId, $userText ) {
1085 $userTalkPage = Title
::makeTitle( NS_USER_TALK
, $userText );
1086 $userTalkLink = self
::link( $userTalkPage, wfMessage( 'talkpagelinktext' )->escaped() );
1087 return $userTalkLink;
1092 * @param int $userId Userid
1093 * @param string $userText User name in database.
1094 * @return string HTML fragment with block link
1096 public static function blockLink( $userId, $userText ) {
1097 $blockPage = SpecialPage
::getTitleFor( 'Block', $userText );
1098 $blockLink = self
::link( $blockPage, wfMessage( 'blocklink' )->escaped() );
1103 * @param int $userId Userid
1104 * @param string $userText User name in database.
1105 * @return string HTML fragment with e-mail user link
1107 public static function emailLink( $userId, $userText ) {
1108 $emailPage = SpecialPage
::getTitleFor( 'Emailuser', $userText );
1109 $emailLink = self
::link( $emailPage, wfMessage( 'emaillink' )->escaped() );
1114 * Generate a user link 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 * @return string HTML fragment
1120 public static function revUserLink( $rev, $isPublic = false ) {
1121 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1122 $link = wfMessage( 'rev-deleted-user' )->escaped();
1123 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1124 $link = self
::userLink( $rev->getUser( Revision
::FOR_THIS_USER
),
1125 $rev->getUserText( Revision
::FOR_THIS_USER
) );
1127 $link = wfMessage( 'rev-deleted-user' )->escaped();
1129 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1130 return '<span class="history-deleted">' . $link . '</span>';
1136 * Generate a user tool link cluster if the current user is allowed to view it
1138 * @param Revision $rev
1139 * @param bool $isPublic Show only if all users can see it
1140 * @return string HTML
1142 public static function revUserTools( $rev, $isPublic = false ) {
1143 if ( $rev->isDeleted( Revision
::DELETED_USER
) && $isPublic ) {
1144 $link = wfMessage( 'rev-deleted-user' )->escaped();
1145 } elseif ( $rev->userCan( Revision
::DELETED_USER
) ) {
1146 $userId = $rev->getUser( Revision
::FOR_THIS_USER
);
1147 $userText = $rev->getUserText( Revision
::FOR_THIS_USER
);
1148 $link = self
::userLink( $userId, $userText )
1149 . self
::userToolLinks( $userId, $userText );
1151 $link = wfMessage( 'rev-deleted-user' )->escaped();
1153 if ( $rev->isDeleted( Revision
::DELETED_USER
) ) {
1154 return ' <span class="history-deleted">' . $link . '</span>';
1160 * This function is called by all recent changes variants, by the page history,
1161 * and by the user contributions list. It is responsible for formatting edit
1162 * summaries. It escapes any HTML in the summary, but adds some CSS to format
1163 * auto-generated comments (from section editing) and formats [[wikilinks]].
1165 * @author Erik Moeller <moeller@scireview.de>
1166 * @since 1.16.3. $wikiId added in 1.26
1168 * Note: there's not always a title to pass to this function.
1169 * Since you can't set a default parameter for a reference, I've turned it
1170 * temporarily to a value pass. Should be adjusted further. --brion
1172 * @param string $comment
1173 * @param Title|null $title Title object (to generate link to the section in autocomment)
1175 * @param bool $local Whether section links should refer to local page
1176 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1177 * For use with external changes.
1179 * @return mixed|string
1181 public static function formatComment(
1182 $comment, $title = null, $local = false, $wikiId = null
1184 # Sanitize text a bit:
1185 $comment = str_replace( "\n", " ", $comment );
1186 # Allow HTML entities (for bug 13815)
1187 $comment = Sanitizer
::escapeHtmlAllowEntities( $comment );
1189 # Render autocomments and make links:
1190 $comment = self
::formatAutocomments( $comment, $title, $local, $wikiId );
1191 $comment = self
::formatLinksInComment( $comment, $title, $local, $wikiId );
1197 * Converts autogenerated comments in edit summaries into section links.
1199 * The pattern for autogen comments is / * foo * /, which makes for
1201 * We look for all comments, match any text before and after the comment,
1202 * add a separator where needed and format the comment itself with CSS
1203 * Called by Linker::formatComment.
1205 * @param string $comment Comment text
1206 * @param Title|null $title An optional title object used to links to sections
1207 * @param bool $local Whether section links should refer to local page
1208 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1209 * as used by WikiMap.
1211 * @return string Formatted comment (wikitext)
1213 private static function formatAutocomments(
1214 $comment, $title = null, $local = false, $wikiId = null
1216 // @todo $append here is something of a hack to preserve the status
1217 // quo. Someone who knows more about bidi and such should decide
1218 // (1) what sane rendering even *is* for an LTR edit summary on an RTL
1219 // wiki, both when autocomments exist and when they don't, and
1220 // (2) what markup will make that actually happen.
1222 $comment = preg_replace_callback(
1223 // To detect the presence of content before or after the
1224 // auto-comment, we use capturing groups inside optional zero-width
1225 // assertions. But older versions of PCRE can't directly make
1226 // zero-width assertions optional, so wrap them in a non-capturing
1228 '!(?:(?<=(.)))?/\*\s*(.*?)\s*\*/(?:(?=(.)))?!',
1229 function ( $match ) use ( $title, $local, $wikiId, &$append ) {
1232 // Ensure all match positions are defined
1233 $match +
= [ '', '', '', '' ];
1235 $pre = $match[1] !== '';
1237 $post = $match[3] !== '';
1241 'FormatAutocomments',
1242 [ &$comment, $pre, $auto, $post, $title, $local, $wikiId ]
1245 if ( $comment === null ) {
1249 # Remove links that a user may have manually put in the autosummary
1250 # This could be improved by copying as much of Parser::stripSectionName as desired.
1251 $section = str_replace( '[[:', '', $section );
1252 $section = str_replace( '[[', '', $section );
1253 $section = str_replace( ']]', '', $section );
1255 $section = Sanitizer
::normalizeSectionNameWhitespace( $section ); # bug 22784
1257 $sectionTitle = Title
::newFromText( '#' . $section );
1259 $sectionTitle = Title
::makeTitleSafe( $title->getNamespace(),
1260 $title->getDBkey(), $section );
1262 if ( $sectionTitle ) {
1263 $link = Linker
::makeCommentLink( $sectionTitle, $wgLang->getArrow(), $wikiId, 'noclasses' );
1269 # written summary $presep autocomment (summary /* section */)
1270 $pre = wfMessage( 'autocomment-prefix' )->inContentLanguage()->escaped();
1273 # autocomment $postsep written summary (/* section */ summary)
1274 $auto .= wfMessage( 'colon-separator' )->inContentLanguage()->escaped();
1276 $auto = '<span class="autocomment">' . $auto . '</span>';
1277 $comment = $pre . $link . $wgLang->getDirMark()
1278 . '<span dir="auto">' . $auto;
1279 $append .= '</span>';
1285 return $comment . $append;
1289 * Formats wiki links and media links in text; all other wiki formatting
1292 * @since 1.16.3. $wikiId added in 1.26
1293 * @todo FIXME: Doesn't handle sub-links as in image thumb texts like the main parser
1295 * @param string $comment Text to format links in. WARNING! Since the output of this
1296 * function is html, $comment must be sanitized for use as html. You probably want
1297 * to pass $comment through Sanitizer::escapeHtmlAllowEntities() before calling
1299 * @param Title|null $title An optional title object used to links to sections
1300 * @param bool $local Whether section links should refer to local page
1301 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1302 * as used by WikiMap.
1306 public static function formatLinksInComment(
1307 $comment, $title = null, $local = false, $wikiId = null
1309 return preg_replace_callback(
1312 :? # ignore optional leading colon
1313 ([^\]|]+) # 1. link target; page names cannot include ] or |
1315 # 2. a pipe-separated substring; only the last is captured
1316 # Stop matching at | and ]] without relying on backtracking.
1320 ([^[]*) # 3. link trail (the text up until the next link)
1322 function ( $match ) use ( $title, $local, $wikiId ) {
1325 $medians = '(?:' . preg_quote( MWNamespace
::getCanonicalName( NS_MEDIA
), '/' ) . '|';
1326 $medians .= preg_quote( $wgContLang->getNsText( NS_MEDIA
), '/' ) . '):';
1328 $comment = $match[0];
1330 # fix up urlencoded title texts (copied from Parser::replaceInternalLinks)
1331 if ( strpos( $match[1], '%' ) !== false ) {
1333 rawurldecode( $match[1] ),
1334 [ '<' => '<', '>' => '>' ]
1338 # Handle link renaming [[foo|text]] will show link as "text"
1339 if ( $match[2] != "" ) {
1346 if ( preg_match( '/^' . $medians . '(.*)$/i', $match[1], $submatch ) ) {
1347 # Media link; trail not supported.
1348 $linkRegexp = '/\[\[(.*?)\]\]/';
1349 $title = Title
::makeTitleSafe( NS_FILE
, $submatch[1] );
1351 $thelink = Linker
::makeMediaLinkObj( $title, $text );
1354 # Other kind of link
1355 # Make sure its target is non-empty
1356 if ( isset( $match[1][0] ) && $match[1][0] == ':' ) {
1357 $match[1] = substr( $match[1], 1 );
1359 if ( $match[1] !== false && $match[1] !== '' ) {
1360 if ( preg_match( $wgContLang->linkTrail(), $match[3], $submatch ) ) {
1361 $trail = $submatch[1];
1365 $linkRegexp = '/\[\[(.*?)\]\]' . preg_quote( $trail, '/' ) . '/';
1366 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1369 $linkTarget = Linker
::normalizeSubpageLink( $title, $match[1], $linkText );
1371 $target = Title
::newFromText( $linkTarget );
1373 if ( $target->getText() == '' && !$target->isExternal()
1374 && !$local && $title
1376 $newTarget = clone $title;
1377 $newTarget->setFragment( '#' . $target->getFragment() );
1378 $target = $newTarget;
1381 $thelink = Linker
::makeCommentLink( $target, $linkText . $inside, $wikiId ) . $trail;
1386 // If the link is still valid, go ahead and replace it in!
1387 $comment = preg_replace(
1389 StringUtils
::escapeRegexReplacement( $thelink ),
1402 * Generates a link to the given Title
1404 * @note This is only public for technical reasons. It's not intended for use outside Linker.
1406 * @param Title $title
1407 * @param string $text
1408 * @param string|null $wikiId Id of the wiki to link to (if not the local wiki),
1409 * as used by WikiMap.
1410 * @param string|string[] $options See the $options parameter in Linker::link.
1412 * @return string HTML link
1414 public static function makeCommentLink(
1415 Title
$title, $text, $wikiId = null, $options = []
1417 if ( $wikiId !== null && !$title->isExternal() ) {
1418 $link = Linker
::makeExternalLink(
1419 WikiMap
::getForeignURL(
1421 $title->getPrefixedText(),
1422 $title->getFragment()
1425 /* escape = */ false // Already escaped
1428 $link = Linker
::link( $title, $text, [], [], $options );
1435 * @param Title $contextTitle
1436 * @param string $target
1437 * @param string $text
1440 public static function normalizeSubpageLink( $contextTitle, $target, &$text ) {
1443 # :Foobar -- override special treatment of prefix (images, language links)
1444 # /Foobar -- convert to CurrentPage/Foobar
1445 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial and final / from text
1446 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1447 # ../Foobar -- convert to CurrentPage/Foobar,
1448 # (from CurrentPage/CurrentSubPage)
1449 # ../Foobar/ -- convert to CurrentPage/Foobar, use 'Foobar' as text
1450 # (from CurrentPage/CurrentSubPage)
1452 $ret = $target; # default return value is no change
1454 # Some namespaces don't allow subpages,
1455 # so only perform processing if subpages are allowed
1456 if ( $contextTitle && MWNamespace
::hasSubpages( $contextTitle->getNamespace() ) ) {
1457 $hash = strpos( $target, '#' );
1458 if ( $hash !== false ) {
1459 $suffix = substr( $target, $hash );
1460 $target = substr( $target, 0, $hash );
1465 $target = trim( $target );
1466 # Look at the first character
1467 if ( $target != '' && $target[0] === '/' ) {
1468 # / at end means we don't want the slash to be shown
1470 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1471 if ( $trailingSlashes ) {
1472 $noslash = $target = substr( $target, 1, -strlen( $m[0][0] ) );
1474 $noslash = substr( $target, 1 );
1477 $ret = $contextTitle->getPrefixedText() . '/' . trim( $noslash ) . $suffix;
1478 if ( $text === '' ) {
1479 $text = $target . $suffix;
1480 } # this might be changed for ugliness reasons
1482 # check for .. subpage backlinks
1484 $nodotdot = $target;
1485 while ( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1487 $nodotdot = substr( $nodotdot, 3 );
1489 if ( $dotdotcount > 0 ) {
1490 $exploded = explode( '/', $contextTitle->getPrefixedText() );
1491 if ( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1492 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1493 # / at the end means don't show full path
1494 if ( substr( $nodotdot, -1, 1 ) === '/' ) {
1495 $nodotdot = rtrim( $nodotdot, '/' );
1496 if ( $text === '' ) {
1497 $text = $nodotdot . $suffix;
1500 $nodotdot = trim( $nodotdot );
1501 if ( $nodotdot != '' ) {
1502 $ret .= '/' . $nodotdot;
1514 * Wrap a comment in standard punctuation and formatting if
1515 * it's non-empty, otherwise return empty string.
1517 * @since 1.16.3. $wikiId added in 1.26
1518 * @param string $comment
1519 * @param Title|null $title Title object (to generate link to section in autocomment) or null
1520 * @param bool $local Whether section links should refer to local page
1521 * @param string|null $wikiId Id (as used by WikiMap) of the wiki to generate links to.
1522 * For use with external changes.
1526 public static function commentBlock(
1527 $comment, $title = null, $local = false, $wikiId = null
1529 // '*' used to be the comment inserted by the software way back
1530 // in antiquity in case none was provided, here for backwards
1531 // compatibility, acc. to brion -ævar
1532 if ( $comment == '' ||
$comment == '*' ) {
1535 $formatted = self
::formatComment( $comment, $title, $local, $wikiId );
1536 $formatted = wfMessage( 'parentheses' )->rawParams( $formatted )->escaped();
1537 return " <span class=\"comment\">$formatted</span>";
1542 * Wrap and format the given revision's comment block, if the current
1543 * user is allowed to view it.
1546 * @param Revision $rev
1547 * @param bool $local Whether section links should refer to local page
1548 * @param bool $isPublic Show only if all users can see it
1549 * @return string HTML fragment
1551 public static function revComment( Revision
$rev, $local = false, $isPublic = false ) {
1552 if ( $rev->getComment( Revision
::RAW
) == "" ) {
1555 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) && $isPublic ) {
1556 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1557 } elseif ( $rev->userCan( Revision
::DELETED_COMMENT
) ) {
1558 $block = self
::commentBlock( $rev->getComment( Revision
::FOR_THIS_USER
),
1559 $rev->getTitle(), $local );
1561 $block = " <span class=\"comment\">" . wfMessage( 'rev-deleted-comment' )->escaped() . "</span>";
1563 if ( $rev->isDeleted( Revision
::DELETED_COMMENT
) ) {
1564 return " <span class=\"history-deleted\">$block</span>";
1574 public static function formatRevisionSize( $size ) {
1576 $stxt = wfMessage( 'historyempty' )->escaped();
1578 $stxt = wfMessage( 'nbytes' )->numParams( $size )->escaped();
1579 $stxt = wfMessage( 'parentheses' )->rawParams( $stxt )->escaped();
1581 return "<span class=\"history-size\">$stxt</span>";
1585 * Add another level to the Table of Contents
1590 public static function tocIndent() {
1595 * Finish one or more sublevels on the Table of Contents
1601 public static function tocUnindent( $level ) {
1602 return "</li>\n" . str_repeat( "</ul>\n</li>\n", $level > 0 ?
$level : 0 );
1606 * parameter level defines if we are on an indentation level
1609 * @param string $anchor
1610 * @param string $tocline
1611 * @param string $tocnumber
1612 * @param string $level
1613 * @param string|bool $sectionIndex
1616 public static function tocLine( $anchor, $tocline, $tocnumber, $level, $sectionIndex = false ) {
1617 $classes = "toclevel-$level";
1618 if ( $sectionIndex !== false ) {
1619 $classes .= " tocsection-$sectionIndex";
1621 return "\n<li class=\"$classes\"><a href=\"#" .
1622 $anchor . '"><span class="tocnumber">' .
1623 $tocnumber . '</span> <span class="toctext">' .
1624 $tocline . '</span></a>';
1628 * End a Table Of Contents line.
1629 * tocUnindent() will be used instead if we're ending a line below
1634 public static function tocLineEnd() {
1639 * Wraps the TOC in a table and provides the hide/collapse javascript.
1642 * @param string $toc Html of the Table Of Contents
1643 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1644 * @return string Full html of the TOC
1646 public static function tocList( $toc, $lang = false ) {
1647 $lang = wfGetLangObj( $lang );
1648 $title = wfMessage( 'toc' )->inLanguage( $lang )->escaped();
1650 return '<div id="toc" class="toc">'
1651 . '<div id="toctitle"><h2>' . $title . "</h2></div>\n"
1653 . "</ul>\n</div>\n";
1657 * Generate a table of contents from a section tree.
1659 * @since 1.16.3. $lang added in 1.17
1660 * @param array $tree Return value of ParserOutput::getSections()
1661 * @param string|Language|bool $lang Language for the toc title, defaults to user language
1662 * @return string HTML fragment
1664 public static function generateTOC( $tree, $lang = false ) {
1667 foreach ( $tree as $section ) {
1668 if ( $section['toclevel'] > $lastLevel ) {
1669 $toc .= self
::tocIndent();
1670 } elseif ( $section['toclevel'] < $lastLevel ) {
1671 $toc .= self
::tocUnindent(
1672 $lastLevel - $section['toclevel'] );
1674 $toc .= self
::tocLineEnd();
1677 $toc .= self
::tocLine( $section['anchor'],
1678 $section['line'], $section['number'],
1679 $section['toclevel'], $section['index'] );
1680 $lastLevel = $section['toclevel'];
1682 $toc .= self
::tocLineEnd();
1683 return self
::tocList( $toc, $lang );
1687 * Create a headline for content
1690 * @param int $level The level of the headline (1-6)
1691 * @param string $attribs Any attributes for the headline, starting with
1692 * a space and ending with '>'
1693 * This *must* be at least '>' for no attribs
1694 * @param string $anchor The anchor to give the headline (the bit after the #)
1695 * @param string $html Html for the text of the header
1696 * @param string $link HTML to add for the section edit link
1697 * @param bool|string $legacyAnchor A second, optional anchor to give for
1698 * backward compatibility (false to omit)
1700 * @return string HTML headline
1702 public static function makeHeadline( $level, $attribs, $anchor, $html,
1703 $link, $legacyAnchor = false
1705 $ret = "<h$level$attribs"
1706 . "<span class=\"mw-headline\" id=\"$anchor\">$html</span>"
1709 if ( $legacyAnchor !== false ) {
1710 $ret = "<div id=\"$legacyAnchor\"></div>$ret";
1716 * Split a link trail, return the "inside" portion and the remainder of the trail
1717 * as a two-element array
1718 * @param string $trail
1721 static function splitTrail( $trail ) {
1723 $regex = $wgContLang->linkTrail();
1725 if ( $trail !== '' ) {
1727 if ( preg_match( $regex, $trail, $m ) ) {
1732 return [ $inside, $trail ];
1736 * Generate a rollback link for a given revision. Currently it's the
1737 * caller's responsibility to ensure that the revision is the top one. If
1738 * it's not, of course, the user will get an error message.
1740 * If the calling page is called with the parameter &bot=1, all rollback
1741 * links also get that parameter. It causes the edit itself and the rollback
1742 * to be marked as "bot" edits. Bot edits are hidden by default from recent
1743 * changes, so this allows sysops to combat a busy vandal without bothering
1746 * If the option verify is set this function will return the link only in case the
1747 * revision can be reverted. Please note that due to performance limitations
1748 * it might be assumed that a user isn't the only contributor of a page while
1749 * (s)he is, which will lead to useless rollback links. Furthermore this wont
1750 * work if $wgShowRollbackEditCount is disabled, so this can only function
1751 * as an additional check.
1753 * If the option noBrackets is set the rollback link wont be enclosed in "[]".
1755 * @since 1.16.3. $context added in 1.20. $options added in 1.21
1757 * @param Revision $rev
1758 * @param IContextSource $context Context to use or null for the main context.
1759 * @param array $options
1762 public static function generateRollback( $rev, IContextSource
$context = null,
1763 $options = [ 'verify' ]
1765 if ( $context === null ) {
1766 $context = RequestContext
::getMain();
1770 if ( in_array( 'verify', $options, true ) ) {
1771 $editCount = self
::getRollbackEditCount( $rev, true );
1772 if ( $editCount === false ) {
1777 $inner = self
::buildRollbackLink( $rev, $context, $editCount );
1779 if ( !in_array( 'noBrackets', $options, true ) ) {
1780 $inner = $context->msg( 'brackets' )->rawParams( $inner )->escaped();
1783 return '<span class="mw-rollback-link">' . $inner . '</span>';
1787 * This function will return the number of revisions which a rollback
1788 * would revert and, if $verify is set it will verify that a revision
1789 * can be reverted (that the user isn't the only contributor and the
1790 * revision we might rollback to isn't deleted). These checks can only
1791 * function as an additional check as this function only checks against
1792 * the last $wgShowRollbackEditCount edits.
1794 * Returns null if $wgShowRollbackEditCount is disabled or false if $verify
1795 * is set and the user is the only contributor of the page.
1797 * @param Revision $rev
1798 * @param bool $verify Try to verify that this revision can really be rolled back
1799 * @return int|bool|null
1801 public static function getRollbackEditCount( $rev, $verify ) {
1802 global $wgShowRollbackEditCount;
1803 if ( !is_int( $wgShowRollbackEditCount ) ||
!$wgShowRollbackEditCount > 0 ) {
1804 // Nothing has happened, indicate this by returning 'null'
1808 $dbr = wfGetDB( DB_SLAVE
);
1810 // Up to the value of $wgShowRollbackEditCount revisions are counted
1811 $res = $dbr->select(
1813 [ 'rev_user_text', 'rev_deleted' ],
1814 // $rev->getPage() returns null sometimes
1815 [ 'rev_page' => $rev->getTitle()->getArticleID() ],
1818 'USE INDEX' => [ 'revision' => 'page_timestamp' ],
1819 'ORDER BY' => 'rev_timestamp DESC',
1820 'LIMIT' => $wgShowRollbackEditCount +
1
1826 foreach ( $res as $row ) {
1827 if ( $rev->getUserText( Revision
::RAW
) != $row->rev_user_text
) {
1829 ( $row->rev_deleted
& Revision
::DELETED_TEXT
1830 ||
$row->rev_deleted
& Revision
::DELETED_USER
1832 // If the user or the text of the revision we might rollback
1833 // to is deleted in some way we can't rollback. Similar to
1834 // the sanity checks in WikiPage::commitRollback.
1843 if ( $verify && $editCount <= $wgShowRollbackEditCount && !$moreRevs ) {
1844 // We didn't find at least $wgShowRollbackEditCount revisions made by the current user
1845 // and there weren't any other revisions. That means that the current user is the only
1846 // editor, so we can't rollback
1853 * Build a raw rollback link, useful for collections of "tool" links
1855 * @since 1.16.3. $context added in 1.20. $editCount added in 1.21
1856 * @param Revision $rev
1857 * @param IContextSource|null $context Context to use or null for the main context.
1858 * @param int $editCount Number of edits that would be reverted
1859 * @return string HTML fragment
1861 public static function buildRollbackLink( $rev, IContextSource
$context = null,
1864 global $wgShowRollbackEditCount, $wgMiserMode;
1866 // To config which pages are affected by miser mode
1867 $disableRollbackEditCountSpecialPage = [ 'Recentchanges', 'Watchlist' ];
1869 if ( $context === null ) {
1870 $context = RequestContext
::getMain();
1873 $title = $rev->getTitle();
1875 'action' => 'rollback',
1876 'from' => $rev->getUserText(),
1877 'token' => $context->getUser()->getEditToken( 'rollback' ),
1880 'data-mw' => 'interface',
1881 'title' => $context->msg( 'tooltip-rollback' )->text(),
1883 $options = [ 'known', 'noclasses' ];
1885 if ( $context->getRequest()->getBool( 'bot' ) ) {
1886 $query['bot'] = '1';
1887 $query['hidediff'] = '1'; // bug 15999
1890 $disableRollbackEditCount = false;
1891 if ( $wgMiserMode ) {
1892 foreach ( $disableRollbackEditCountSpecialPage as $specialPage ) {
1893 if ( $context->getTitle()->isSpecial( $specialPage ) ) {
1894 $disableRollbackEditCount = true;
1900 if ( !$disableRollbackEditCount
1901 && is_int( $wgShowRollbackEditCount )
1902 && $wgShowRollbackEditCount > 0
1904 if ( !is_numeric( $editCount ) ) {
1905 $editCount = self
::getRollbackEditCount( $rev, false );
1908 if ( $editCount > $wgShowRollbackEditCount ) {
1909 $html = $context->msg( 'rollbacklinkcount-morethan' )
1910 ->numParams( $wgShowRollbackEditCount )->parse();
1912 $html = $context->msg( 'rollbacklinkcount' )->numParams( $editCount )->parse();
1915 return self
::link( $title, $html, $attrs, $query, $options );
1917 $html = $context->msg( 'rollbacklink' )->escaped();
1918 return self
::link( $title, $html, $attrs, $query, $options );
1923 * Returns HTML for the "templates used on this page" list.
1925 * Make an HTML list of templates, and then add a "More..." link at
1926 * the bottom. If $more is null, do not add a "More..." link. If $more
1927 * is a Title, make a link to that title and use it. If $more is a string,
1928 * directly paste it in as the link (escaping needs to be done manually).
1929 * Finally, if $more is a Message, call toString().
1931 * @since 1.16.3. $more added in 1.21
1932 * @param Title[] $templates Array of templates
1933 * @param bool $preview Whether this is for a preview
1934 * @param bool $section Whether this is for a section edit
1935 * @param Title|Message|string|null $more An escaped link for "More..." of the templates
1936 * @return string HTML output
1938 public static function formatTemplates( $templates, $preview = false,
1939 $section = false, $more = null
1944 if ( count( $templates ) > 0 ) {
1945 # Do a batch existence check
1946 $batch = new LinkBatch
;
1947 foreach ( $templates as $title ) {
1948 $batch->addObj( $title );
1952 # Construct the HTML
1953 $outText = '<div class="mw-templatesUsedExplanation">';
1955 $outText .= wfMessage( 'templatesusedpreview' )->numParams( count( $templates ) )
1957 } elseif ( $section ) {
1958 $outText .= wfMessage( 'templatesusedsection' )->numParams( count( $templates ) )
1961 $outText .= wfMessage( 'templatesused' )->numParams( count( $templates ) )
1964 $outText .= "</div><ul>\n";
1966 usort( $templates, 'Title::compare' );
1967 foreach ( $templates as $titleObj ) {
1969 $restrictions = $titleObj->getRestrictions( 'edit' );
1970 if ( $restrictions ) {
1971 // Check backwards-compatible messages
1973 if ( $restrictions === [ 'sysop' ] ) {
1974 $msg = wfMessage( 'template-protected' );
1975 } elseif ( $restrictions === [ 'autoconfirmed' ] ) {
1976 $msg = wfMessage( 'template-semiprotected' );
1978 if ( $msg && !$msg->isDisabled() ) {
1979 $protected = $msg->parse();
1981 // Construct the message from restriction-level-*
1982 // e.g. restriction-level-sysop, restriction-level-autoconfirmed
1984 foreach ( $restrictions as $r ) {
1985 $msgs[] = wfMessage( "restriction-level-$r" )->parse();
1987 $protected = wfMessage( 'parentheses' )
1988 ->rawParams( $wgLang->commaList( $msgs ) )->escaped();
1991 if ( $titleObj->quickUserCan( 'edit' ) ) {
1992 $editLink = self
::link(
1994 wfMessage( 'editlink' )->escaped(),
1996 [ 'action' => 'edit' ]
1999 $editLink = self
::link(
2001 wfMessage( 'viewsourcelink' )->escaped(),
2003 [ 'action' => 'edit' ]
2006 $outText .= '<li>' . self
::link( $titleObj )
2007 . wfMessage( 'word-separator' )->escaped()
2008 . wfMessage( 'parentheses' )->rawParams( $editLink )->escaped()
2009 . wfMessage( 'word-separator' )->escaped()
2010 . $protected . '</li>';
2013 if ( $more instanceof Title
) {
2014 $outText .= '<li>' . self
::link( $more, wfMessage( 'moredotdotdot' ) ) . '</li>';
2015 } elseif ( $more ) {
2016 $outText .= "<li>$more</li>";
2019 $outText .= '</ul>';
2025 * Returns HTML for the "hidden categories on this page" list.
2028 * @param array $hiddencats Array of hidden categories from Article::getHiddenCategories
2030 * @return string HTML output
2032 public static function formatHiddenCategories( $hiddencats ) {
2035 if ( count( $hiddencats ) > 0 ) {
2036 # Construct the HTML
2037 $outText = '<div class="mw-hiddenCategoriesExplanation">';
2038 $outText .= wfMessage( 'hiddencategories' )->numParams( count( $hiddencats ) )->parseAsBlock();
2039 $outText .= "</div><ul>\n";
2041 foreach ( $hiddencats as $titleObj ) {
2042 # If it's hidden, it must exist - no need to check with a LinkBatch
2044 . self
::link( $titleObj, null, [], [], 'known' )
2047 $outText .= '</ul>';
2053 * Format a size in bytes for output, using an appropriate
2054 * unit (B, KB, MB or GB) according to the magnitude in question
2057 * @param int $size Size to format
2060 public static function formatSize( $size ) {
2062 return htmlspecialchars( $wgLang->formatSize( $size ) );
2066 * Given the id of an interface element, constructs the appropriate title
2067 * attribute from the system messages. (Note, this is usually the id but
2068 * isn't always, because sometimes the accesskey needs to go on a different
2069 * element than the id, for reverse-compatibility, etc.)
2071 * @since 1.16.3 $msgParams added in 1.27
2072 * @param string $name Id of the element, minus prefixes.
2073 * @param string|null $options Null or the string 'withaccess' to add an access-
2075 * @param array $msgParams Parameters to pass to the message
2077 * @return string Contents of the title attribute (which you must HTML-
2078 * escape), or false for no title attribute
2080 public static function titleAttrib( $name, $options = null, array $msgParams = [] ) {
2081 $message = wfMessage( "tooltip-$name", $msgParams );
2082 if ( !$message->exists() ) {
2085 $tooltip = $message->text();
2086 # Compatibility: formerly some tooltips had [alt-.] hardcoded
2087 $tooltip = preg_replace( "/ ?\[alt-.\]$/", '', $tooltip );
2088 # Message equal to '-' means suppress it.
2089 if ( $tooltip == '-' ) {
2094 if ( $options == 'withaccess' ) {
2095 $accesskey = self
::accesskey( $name );
2096 if ( $accesskey !== false ) {
2097 // Should be build the same as in jquery.accessKeyLabel.js
2098 if ( $tooltip === false ||
$tooltip === '' ) {
2099 $tooltip = wfMessage( 'brackets', $accesskey )->text();
2101 $tooltip .= wfMessage( 'word-separator' )->text();
2102 $tooltip .= wfMessage( 'brackets', $accesskey )->text();
2110 public static $accesskeycache;
2113 * Given the id of an interface element, constructs the appropriate
2114 * accesskey attribute from the system messages. (Note, this is usually
2115 * the id but isn't always, because sometimes the accesskey needs to go on
2116 * a different element than the id, for reverse-compatibility, etc.)
2119 * @param string $name Id of the element, minus prefixes.
2120 * @return string Contents of the accesskey attribute (which you must HTML-
2121 * escape), or false for no accesskey attribute
2123 public static function accesskey( $name ) {
2124 if ( isset( self
::$accesskeycache[$name] ) ) {
2125 return self
::$accesskeycache[$name];
2128 $message = wfMessage( "accesskey-$name" );
2130 if ( !$message->exists() ) {
2133 $accesskey = $message->plain();
2134 if ( $accesskey === '' ||
$accesskey === '-' ) {
2135 # @todo FIXME: Per standard MW behavior, a value of '-' means to suppress the
2136 # attribute, but this is broken for accesskey: that might be a useful
2142 self
::$accesskeycache[$name] = $accesskey;
2143 return self
::$accesskeycache[$name];
2147 * Get a revision-deletion link, or disabled link, or nothing, depending
2148 * on user permissions & the settings on the revision.
2150 * Will use forward-compatible revision ID in the Special:RevDelete link
2151 * if possible, otherwise the timestamp-based ID which may break after
2155 * @param Revision $rev
2156 * @param Title $title
2157 * @return string HTML fragment
2159 public static function getRevDeleteLink( User
$user, Revision
$rev, Title
$title ) {
2160 $canHide = $user->isAllowed( 'deleterevision' );
2161 if ( !$canHide && !( $rev->getVisibility() && $user->isAllowed( 'deletedhistory' ) ) ) {
2165 if ( !$rev->userCan( Revision
::DELETED_RESTRICTED
, $user ) ) {
2166 return Linker
::revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
2168 if ( $rev->getId() ) {
2169 // RevDelete links using revision ID are stable across
2170 // page deletion and undeletion; use when possible.
2172 'type' => 'revision',
2173 'target' => $title->getPrefixedDBkey(),
2174 'ids' => $rev->getId()
2177 // Older deleted entries didn't save a revision ID.
2178 // We have to refer to these by timestamp, ick!
2180 'type' => 'archive',
2181 'target' => $title->getPrefixedDBkey(),
2182 'ids' => $rev->getTimestamp()
2185 return Linker
::revDeleteLink( $query,
2186 $rev->isDeleted( Revision
::DELETED_RESTRICTED
), $canHide );
2191 * Creates a (show/hide) link for deleting revisions/log entries
2193 * @param array $query Query parameters to be passed to link()
2194 * @param bool $restricted Set to true to use a "<strong>" instead of a "<span>"
2195 * @param bool $delete Set to true to use (show/hide) rather than (show)
2197 * @return string HTML "<a>" link to Special:Revisiondelete, wrapped in a
2198 * span to allow for customization of appearance with CSS
2200 public static function revDeleteLink( $query = [], $restricted = false, $delete = true ) {
2201 $sp = SpecialPage
::getTitleFor( 'Revisiondelete' );
2202 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2203 $html = wfMessage( $msgKey )->escaped();
2204 $tag = $restricted ?
'strong' : 'span';
2205 $link = self
::link( $sp, $html, [], $query, [ 'known', 'noclasses' ] );
2208 [ 'class' => 'mw-revdelundel-link' ],
2209 wfMessage( 'parentheses' )->rawParams( $link )->escaped()
2214 * Creates a dead (show/hide) link for deleting revisions/log entries
2217 * @param bool $delete Set to true to use (show/hide) rather than (show)
2219 * @return string HTML text wrapped in a span to allow for customization
2220 * of appearance with CSS
2222 public static function revDeleteLinkDisabled( $delete = true ) {
2223 $msgKey = $delete ?
'rev-delundel' : 'rev-showdeleted';
2224 $html = wfMessage( $msgKey )->escaped();
2225 $htmlParentheses = wfMessage( 'parentheses' )->rawParams( $html )->escaped();
2226 return Xml
::tags( 'span', [ 'class' => 'mw-revdelundel-link' ], $htmlParentheses );
2229 /* Deprecated methods */
2232 * Returns the attributes for the tooltip and access key.
2234 * @since 1.16.3. $msgParams introduced in 1.27
2235 * @param string $name
2236 * @param array $msgParams Params for constructing the message
2240 public static function tooltipAndAccesskeyAttribs( $name, array $msgParams = [] ) {
2241 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2242 # no attribute" instead of "output '' as value for attribute", this
2243 # would be three lines.
2245 'title' => self
::titleAttrib( $name, 'withaccess', $msgParams ),
2246 'accesskey' => self
::accesskey( $name )
2248 if ( $attribs['title'] === false ) {
2249 unset( $attribs['title'] );
2251 if ( $attribs['accesskey'] === false ) {
2252 unset( $attribs['accesskey'] );
2258 * Returns raw bits of HTML, use titleAttrib()
2260 * @param string $name
2261 * @param array|null $options
2262 * @return null|string
2264 public static function tooltip( $name, $options = null ) {
2265 # @todo FIXME: If Sanitizer::expandAttributes() treated "false" as "output
2266 # no attribute" instead of "output '' as value for attribute", this
2267 # would be two lines.
2268 $tooltip = self
::titleAttrib( $name, $options );
2269 if ( $tooltip === false ) {
2272 return Xml
::expandAttributes( [