SpecialRedirect: Don't pass null to explode
[mediawiki.git] / includes / Html.php
blob397550731a4e9e98c51412fe39929fd1dd2cbbcd
1 <?php
2 /**
3 * Collection of methods to generate HTML content
5 * Copyright © 2009 Aryeh Gregor
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @file
26 use MediaWiki\MainConfigNames;
27 use MediaWiki\MediaWikiServices;
29 /**
30 * This class is a collection of static functions that serve two purposes:
32 * 1) Implement any algorithms specified by HTML5, or other HTML
33 * specifications, in a convenient and self-contained way.
35 * 2) Allow HTML elements to be conveniently and safely generated, like the
36 * current Xml class but a) less confused (Xml supports HTML-specific things,
37 * but only sometimes!) and b) not necessarily confined to XML-compatible
38 * output.
40 * There are two important configuration options this class uses:
42 * $wgMimeType: If this is set to an xml MIME type then output should be
43 * valid XHTML5.
45 * This class is meant to be confined to utility functions that are called from
46 * trusted code paths. It does not do enforcement of policy like not allowing
47 * <a> elements.
49 * @since 1.16
51 class Html {
52 /** @var bool[] List of void elements from HTML5, section 8.1.2 as of 2016-09-19 */
53 private static $voidElements = [
54 'area' => true,
55 'base' => true,
56 'br' => true,
57 'col' => true,
58 'embed' => true,
59 'hr' => true,
60 'img' => true,
61 'input' => true,
62 'keygen' => true,
63 'link' => true,
64 'meta' => true,
65 'param' => true,
66 'source' => true,
67 'track' => true,
68 'wbr' => true,
71 /**
72 * Boolean attributes, which may have the value omitted entirely. Manually
73 * collected from the HTML5 spec as of 2011-08-12.
74 * @var bool[]
76 private static $boolAttribs = [
77 'async' => true,
78 'autofocus' => true,
79 'autoplay' => true,
80 'checked' => true,
81 'controls' => true,
82 'default' => true,
83 'defer' => true,
84 'disabled' => true,
85 'formnovalidate' => true,
86 'hidden' => true,
87 'ismap' => true,
88 'itemscope' => true,
89 'loop' => true,
90 'multiple' => true,
91 'muted' => true,
92 'novalidate' => true,
93 'open' => true,
94 'pubdate' => true,
95 'readonly' => true,
96 'required' => true,
97 'reversed' => true,
98 'scoped' => true,
99 'seamless' => true,
100 'selected' => true,
101 'truespeed' => true,
102 'typemustmatch' => true,
106 * Modifies a set of attributes meant for button elements
107 * and apply a set of default attributes when $wgUseMediaWikiUIEverywhere enabled.
108 * @param array $attrs HTML attributes in an associative array
109 * @param string[] $modifiers classes to add to the button
110 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
111 * @return array Modified attributes array
113 public static function buttonAttributes( array $attrs, array $modifiers = [] ) {
114 $useMediaWikiUIEverywhere = MediaWikiServices::getInstance()
115 ->getMainConfig()->get( MainConfigNames::UseMediaWikiUIEverywhere );
116 if ( $useMediaWikiUIEverywhere ) {
117 if ( isset( $attrs['class'] ) ) {
118 if ( is_array( $attrs['class'] ) ) {
119 $attrs['class'][] = 'mw-ui-button';
120 $attrs['class'] = array_merge( $attrs['class'], $modifiers );
121 // ensure compatibility with Xml
122 $attrs['class'] = implode( ' ', $attrs['class'] );
123 } else {
124 $attrs['class'] .= ' mw-ui-button ' . implode( ' ', $modifiers );
126 } else {
127 // ensure compatibility with Xml
128 $attrs['class'] = 'mw-ui-button ' . implode( ' ', $modifiers );
131 return $attrs;
135 * Modifies a set of attributes meant for text input elements
136 * and apply a set of default attributes.
137 * Removes size attribute when $wgUseMediaWikiUIEverywhere enabled.
138 * @param array $attrs An attribute array.
139 * @return array Modified attributes array
141 public static function getTextInputAttributes( array $attrs ) {
142 $useMediaWikiUIEverywhere = MediaWikiServices::getInstance()
143 ->getMainConfig()->get( MainConfigNames::UseMediaWikiUIEverywhere );
144 if ( $useMediaWikiUIEverywhere ) {
145 if ( isset( $attrs['class'] ) ) {
146 if ( is_array( $attrs['class'] ) ) {
147 $attrs['class'][] = 'mw-ui-input';
148 } else {
149 $attrs['class'] .= ' mw-ui-input';
151 } else {
152 $attrs['class'] = 'mw-ui-input';
155 return $attrs;
159 * Returns an HTML link element in a string styled as a button
160 * (when $wgUseMediaWikiUIEverywhere is enabled).
162 * @param string $text The text of the element. Will be escaped (not raw HTML)
163 * @param array $attrs Associative array of attributes, e.g., [
164 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
165 * further documentation.
166 * @param string[] $modifiers classes to add to the button
167 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
168 * @return string Raw HTML
170 public static function linkButton( $text, array $attrs, array $modifiers = [] ) {
171 return self::element( 'a',
172 self::buttonAttributes( $attrs, $modifiers ),
173 $text
178 * Returns an HTML link element in a string styled as a button
179 * (when $wgUseMediaWikiUIEverywhere is enabled).
181 * @param string $contents The raw HTML contents of the element: *not*
182 * escaped!
183 * @param array $attrs Associative array of attributes, e.g., [
184 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
185 * further documentation.
186 * @param string[] $modifiers classes to add to the button
187 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
188 * @return string Raw HTML
190 public static function submitButton( $contents, array $attrs, array $modifiers = [] ) {
191 $attrs['type'] = 'submit';
192 $attrs['value'] = $contents;
193 return self::element( 'input', self::buttonAttributes( $attrs, $modifiers ) );
197 * Returns an HTML element in a string. The major advantage here over
198 * manually typing out the HTML is that it will escape all attribute
199 * values.
201 * This is quite similar to Xml::tags(), but it implements some useful
202 * HTML-specific logic. For instance, there is no $allowShortTag
203 * parameter: the closing tag is magically omitted if $element has an empty
204 * content model.
206 * @param string $element The element's name, e.g., 'a'
207 * @param array $attribs Associative array of attributes, e.g., [
208 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
209 * further documentation.
210 * @param string $contents The raw HTML contents of the element: *not*
211 * escaped!
212 * @return string Raw HTML
214 public static function rawElement( $element, $attribs = [], $contents = '' ) {
215 $start = self::openElement( $element, $attribs );
216 if ( isset( self::$voidElements[$element] ) ) {
217 // Silly XML.
218 return substr( $start, 0, -1 ) . '/>';
219 } else {
220 return $start . $contents . self::closeElement( $element );
225 * Identical to rawElement(), but HTML-escapes $contents (like
226 * Xml::element()).
228 * @param string $element Name of the element, e.g., 'a'
229 * @param array $attribs Associative array of attributes, e.g., [
230 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
231 * further documentation.
232 * @param string $contents
234 * @return string
236 public static function element( $element, $attribs = [], $contents = '' ) {
237 return self::rawElement( $element, $attribs, strtr( $contents, [
238 // There's no point in escaping quotes, >, etc. in the contents of
239 // elements.
240 '&' => '&amp;',
241 '<' => '&lt;'
242 ] ) );
246 * Identical to rawElement(), but has no third parameter and omits the end
247 * tag (and the self-closing '/' in XML mode for empty elements).
249 * @param string $element Name of the element, e.g., 'a'
250 * @param array $attribs Associative array of attributes, e.g., [
251 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
252 * further documentation.
254 * @return string
256 public static function openElement( $element, $attribs = [] ) {
257 $attribs = (array)$attribs;
258 // This is not required in HTML5, but let's do it anyway, for
259 // consistency and better compression.
260 $element = strtolower( $element );
262 // Some people were abusing this by passing things like
263 // 'h1 id="foo" to $element, which we don't want.
264 if ( strpos( $element, ' ' ) !== false ) {
265 wfWarn( __METHOD__ . " given element name with space '$element'" );
268 // Remove invalid input types
269 if ( $element == 'input' ) {
270 $validTypes = [
271 'hidden' => true,
272 'text' => true,
273 'password' => true,
274 'checkbox' => true,
275 'radio' => true,
276 'file' => true,
277 'submit' => true,
278 'image' => true,
279 'reset' => true,
280 'button' => true,
282 // HTML input types
283 'datetime' => true,
284 'datetime-local' => true,
285 'date' => true,
286 'month' => true,
287 'time' => true,
288 'week' => true,
289 'number' => true,
290 'range' => true,
291 'email' => true,
292 'url' => true,
293 'search' => true,
294 'tel' => true,
295 'color' => true,
297 if ( isset( $attribs['type'] ) && !isset( $validTypes[$attribs['type']] ) ) {
298 unset( $attribs['type'] );
302 // According to standard the default type for <button> elements is "submit".
303 // Depending on compatibility mode IE might use "button", instead.
304 // We enforce the standard "submit".
305 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
306 $attribs['type'] = 'submit';
309 return "<$element" . self::expandAttributes(
310 self::dropDefaults( $element, $attribs ) ) . '>';
314 * Returns "</$element>"
316 * @since 1.17
317 * @param string $element Name of the element, e.g., 'a'
318 * @return string A closing tag
320 public static function closeElement( $element ) {
321 $element = strtolower( $element );
323 return "</$element>";
327 * Given an element name and an associative array of element attributes,
328 * return an array that is functionally identical to the input array, but
329 * possibly smaller. In particular, attributes might be stripped if they
330 * are given their default values.
332 * This method is not guaranteed to remove all redundant attributes, only
333 * some common ones and some others selected arbitrarily at random. It
334 * only guarantees that the output array should be functionally identical
335 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
337 * @param string $element Name of the element, e.g., 'a'
338 * @param array $attribs Associative array of attributes, e.g., [
339 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
340 * further documentation.
341 * @return array An array of attributes functionally identical to $attribs
343 private static function dropDefaults( $element, array $attribs ) {
344 // Whenever altering this array, please provide a covering test case
345 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
346 static $attribDefaults = [
347 'area' => [ 'shape' => 'rect' ],
348 'button' => [
349 'formaction' => 'GET',
350 'formenctype' => 'application/x-www-form-urlencoded',
352 'canvas' => [
353 'height' => '150',
354 'width' => '300',
356 'form' => [
357 'action' => 'GET',
358 'autocomplete' => 'on',
359 'enctype' => 'application/x-www-form-urlencoded',
361 'input' => [
362 'formaction' => 'GET',
363 'type' => 'text',
365 'keygen' => [ 'keytype' => 'rsa' ],
366 'link' => [ 'media' => 'all' ],
367 'menu' => [ 'type' => 'list' ],
368 'script' => [ 'type' => 'text/javascript' ],
369 'style' => [
370 'media' => 'all',
371 'type' => 'text/css',
373 'textarea' => [ 'wrap' => 'soft' ],
376 foreach ( $attribs as $attrib => $value ) {
377 if ( $attrib === 'class' ) {
378 if ( $value === '' || $value === [] || $value === [ '' ] ) {
379 unset( $attribs[$attrib] );
381 } elseif ( isset( $attribDefaults[$element][$attrib] ) ) {
382 if ( is_array( $value ) ) {
383 $value = implode( ' ', $value );
384 } else {
385 $value = strval( $value );
387 if ( $attribDefaults[$element][$attrib] == $value ) {
388 unset( $attribs[$attrib] );
393 // More subtle checks
394 if ( $element === 'link'
395 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
397 unset( $attribs['type'] );
399 if ( $element === 'input' ) {
400 $type = $attribs['type'] ?? null;
401 $value = $attribs['value'] ?? null;
402 if ( $type === 'checkbox' || $type === 'radio' ) {
403 // The default value for checkboxes and radio buttons is 'on'
404 // not ''. By stripping value="" we break radio boxes that
405 // actually wants empty values.
406 if ( $value === 'on' ) {
407 unset( $attribs['value'] );
409 } elseif ( $type === 'submit' ) {
410 // The default value for submit appears to be "Submit" but
411 // let's not bother stripping out localized text that matches
412 // that.
413 } else {
414 // The default value for nearly every other field type is ''
415 // The 'range' and 'color' types use different defaults but
416 // stripping a value="" does not hurt them.
417 if ( $value === '' ) {
418 unset( $attribs['value'] );
422 if ( $element === 'select' && isset( $attribs['size'] ) ) {
423 if ( in_array( 'multiple', $attribs )
424 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
426 // A multi-select
427 if ( strval( $attribs['size'] ) == '4' ) {
428 unset( $attribs['size'] );
430 } else {
431 // Single select
432 if ( strval( $attribs['size'] ) == '1' ) {
433 unset( $attribs['size'] );
438 return $attribs;
442 * Given an associative array of element attributes, generate a string
443 * to stick after the element name in HTML output. Like [ 'href' =>
444 * 'https://www.mediawiki.org/' ] becomes something like
445 * ' href="https://www.mediawiki.org"'. Again, this is like
446 * Xml::expandAttributes(), but it implements some HTML-specific logic.
448 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
449 * values are allowed as well, which will automagically be normalized
450 * and converted to a space-separated string. In addition to a numerical
451 * array, the attribute value may also be an associative array. See the
452 * example below for how that works.
454 * @par Numerical array
455 * @code
456 * Html::element( 'em', [
457 * 'class' => [ 'foo', 'bar' ]
458 * ] );
459 * // gives '<em class="foo bar"></em>'
460 * @endcode
462 * @par Associative array
463 * @code
464 * Html::element( 'em', [
465 * 'class' => [ 'foo', 'bar', 'foo' => false, 'quux' => true ]
466 * ] );
467 * // gives '<em class="bar quux"></em>'
468 * @endcode
470 * @param array $attribs Associative array of attributes, e.g., [
471 * 'href' => 'https://www.mediawiki.org/' ]. Values will be HTML-escaped.
472 * A value of false or null means to omit the attribute. For boolean attributes,
473 * you can omit the key, e.g., [ 'checked' ] instead of
474 * [ 'checked' => 'checked' ] or such.
476 * @throws MWException If an attribute that doesn't allow lists is set to an array
477 * @return string HTML fragment that goes between element name and '>'
478 * (starting with a space if at least one attribute is output)
480 public static function expandAttributes( array $attribs ) {
481 $ret = '';
482 foreach ( $attribs as $key => $value ) {
483 // Support intuitive [ 'checked' => true/false ] form
484 if ( $value === false || $value === null ) {
485 continue;
488 // For boolean attributes, support [ 'foo' ] instead of
489 // requiring [ 'foo' => 'meaningless' ].
490 if ( is_int( $key ) && isset( self::$boolAttribs[strtolower( $value )] ) ) {
491 $key = $value;
494 // Not technically required in HTML5 but we'd like consistency
495 // and better compression anyway.
496 $key = strtolower( $key );
498 // https://www.w3.org/TR/html401/index/attributes.html ("space-separated")
499 // https://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
500 $spaceSeparatedListAttributes = [
501 'class' => true, // html4, html5
502 'accesskey' => true, // as of html5, multiple space-separated values allowed
503 // html4-spec doesn't document rel= as space-separated
504 // but has been used like that and is now documented as such
505 // in the html5-spec.
506 'rel' => true,
509 // Specific features for attributes that allow a list of space-separated values
510 if ( isset( $spaceSeparatedListAttributes[$key] ) ) {
511 // Apply some normalization and remove duplicates
513 // Convert into correct array. Array can contain space-separated
514 // values. Implode/explode to get those into the main array as well.
515 if ( is_array( $value ) ) {
516 // If input wasn't an array, we can skip this step
517 $arrayValue = [];
518 foreach ( $value as $k => $v ) {
519 if ( is_string( $v ) ) {
520 // String values should be normal `[ 'foo' ]`
521 // Just append them
522 if ( !isset( $value[$v] ) ) {
523 // As a special case don't set 'foo' if a
524 // separate 'foo' => true/false exists in the array
525 // keys should be authoritative
526 foreach ( explode( ' ', $v ) as $part ) {
527 // Normalize spacing by fixing up cases where people used
528 // more than 1 space and/or a trailing/leading space
529 if ( $part !== '' && $part !== ' ' ) {
530 $arrayValue[] = $part;
534 } elseif ( $v ) {
535 // If the value is truthy but not a string this is likely
536 // an [ 'foo' => true ], falsy values don't add strings
537 $arrayValue[] = $k;
540 } else {
541 $arrayValue = explode( ' ', $value );
542 // Normalize spacing by fixing up cases where people used
543 // more than 1 space and/or a trailing/leading space
544 $arrayValue = array_diff( $arrayValue, [ '', ' ' ] );
547 // Remove duplicates and create the string
548 $value = implode( ' ', array_unique( $arrayValue ) );
550 // Optimization: Skip below boolAttribs check and jump straight
551 // to its `else` block. The current $spaceSeparatedListAttributes
552 // block is mutually exclusive with $boolAttribs.
553 // phpcs:ignore Generic.PHP.DiscourageGoto
554 goto not_bool; // NOSONAR
555 } elseif ( is_array( $value ) ) {
556 throw new MWException( "HTML attribute $key can not contain a list of values" );
559 if ( isset( self::$boolAttribs[$key] ) ) {
560 $ret .= " $key=\"\"";
561 } else {
562 // phpcs:ignore Generic.PHP.DiscourageGoto
563 not_bool:
564 // Inlined from Sanitizer::encodeAttribute() for improved performance
565 $encValue = htmlspecialchars( $value, ENT_QUOTES );
566 // Whitespace is normalized during attribute decoding,
567 // so if we've been passed non-spaces we must encode them
568 // ahead of time or they won't be preserved.
569 $encValue = strtr( $encValue, [
570 "\n" => '&#10;',
571 "\r" => '&#13;',
572 "\t" => '&#9;',
573 ] );
574 $ret .= " $key=\"$encValue\"";
577 return $ret;
581 * Output an HTML script tag with the given contents.
583 * It is unsupported for the contents to contain the sequence `<script` or `</script`
584 * (case-insensitive). This ensures the script can be terminated easily and consistently.
585 * It is the responsibility of the caller to avoid such character sequence by escaping
586 * or avoiding it. If found at run-time, the contents are replaced with a comment, and
587 * a warning is logged server-side.
589 * @param string $contents JavaScript
590 * @param string|null $nonce Nonce for CSP header, from OutputPage->getCSP()->getNonce()
591 * @return string Raw HTML
593 public static function inlineScript( $contents, $nonce = null ) {
594 $attrs = [];
595 if ( $nonce !== null ) {
596 $attrs['nonce'] = $nonce;
597 } elseif ( ContentSecurityPolicy::isNonceRequired( MediaWikiServices::getInstance()->getMainConfig() ) ) {
598 wfWarn( "no nonce set on script. CSP will break it" );
601 if ( preg_match( '/<\/?script/i', $contents ) ) {
602 wfLogWarning( __METHOD__ . ': Illegal character sequence found in inline script.' );
603 $contents = '/* ERROR: Invalid script */';
606 return self::rawElement( 'script', $attrs, $contents );
610 * Output a "<script>" tag linking to the given URL, e.g.,
611 * "<script src=foo.js></script>".
613 * @param string $url
614 * @param string|null $nonce Nonce for CSP header, from OutputPage->getCSP()->getNonce()
615 * @return string Raw HTML
617 public static function linkedScript( $url, $nonce = null ) {
618 $attrs = [ 'src' => $url ];
619 if ( $nonce !== null ) {
620 $attrs['nonce'] = $nonce;
621 } elseif ( ContentSecurityPolicy::isNonceRequired( MediaWikiServices::getInstance()->getMainConfig() ) ) {
622 wfWarn( "no nonce set on script. CSP will break it" );
625 return self::element( 'script', $attrs );
629 * Output a "<style>" tag with the given contents for the given media type
630 * (if any). TODO: do some useful escaping as well, like if $contents
631 * contains literal "</style>" (admittedly unlikely).
633 * @param string $contents CSS
634 * @param string $media A media type string, like 'screen'
635 * @param array $attribs (since 1.31) Associative array of attributes, e.g., [
636 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
637 * further documentation.
638 * @return string Raw HTML
640 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
641 // Don't escape '>' since that is used
642 // as direct child selector.
643 // Remember, in css, there is no "x" for hexadecimal escapes, and
644 // the space immediately after an escape sequence is swallowed.
645 $contents = strtr( $contents, [
646 '<' => '\3C ',
647 // CDATA end tag for good measure, but the main security
648 // is from escaping the '<'.
649 ']]>' => '\5D\5D\3E '
650 ] );
652 if ( preg_match( '/[<&]/', $contents ) ) {
653 $contents = "/*<![CDATA[*/$contents/*]]>*/";
656 return self::rawElement( 'style', [
657 'media' => $media,
658 ] + $attribs, $contents );
662 * Output a "<link rel=stylesheet>" linking to the given URL for the given
663 * media type (if any).
665 * @param string $url
666 * @param string $media A media type string, like 'screen'
667 * @return string Raw HTML
669 public static function linkedStyle( $url, $media = 'all' ) {
670 return self::element( 'link', [
671 'rel' => 'stylesheet',
672 'href' => $url,
673 'media' => $media,
674 ] );
678 * Convenience function to produce an "<input>" element. This supports the
679 * new HTML5 input types and attributes.
681 * @param string $name Name attribute
682 * @param string $value Value attribute
683 * @param string $type Type attribute
684 * @param array $attribs Associative array of miscellaneous extra
685 * attributes, passed to Html::element()
686 * @return string Raw HTML
688 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
689 $attribs['type'] = $type;
690 $attribs['value'] = $value;
691 $attribs['name'] = $name;
692 $textInputAttributes = [
693 'text' => true,
694 'search' => true,
695 'email' => true,
696 'password' => true,
697 'number' => true
699 if ( isset( $textInputAttributes[$type] ) ) {
700 $attribs = self::getTextInputAttributes( $attribs );
702 $buttonAttributes = [
703 'button' => true,
704 'reset' => true,
705 'submit' => true
707 if ( isset( $buttonAttributes[$type] ) ) {
708 $attribs = self::buttonAttributes( $attribs );
710 return self::element( 'input', $attribs );
714 * Convenience function to produce a checkbox (input element with type=checkbox)
716 * @param string $name Name attribute
717 * @param bool $checked Whether the checkbox is checked or not
718 * @param array $attribs Array of additional attributes
719 * @return string Raw HTML
721 public static function check( $name, $checked = false, array $attribs = [] ) {
722 if ( isset( $attribs['value'] ) ) {
723 $value = $attribs['value'];
724 unset( $attribs['value'] );
725 } else {
726 $value = 1;
729 if ( $checked ) {
730 $attribs[] = 'checked';
733 return self::input( $name, $value, 'checkbox', $attribs );
737 * Return the HTML for a message box.
738 * @since 1.31
739 * @param string $html of contents of box
740 * @param string|array $className corresponding to box
741 * @param string $heading (optional)
742 * @return string of HTML representing a box.
744 private static function messageBox( $html, $className, $heading = '' ) {
745 if ( $heading !== '' ) {
746 $html = self::element( 'h2', [], $heading ) . $html;
748 if ( is_array( $className ) ) {
749 $className[] = 'mw-message-box';
750 } else {
751 $className .= ' mw-message-box';
753 return self::rawElement( 'div', [ 'class' => $className ], $html );
757 * Return the HTML for a notice message box.
758 * @since 1.38
759 * @param string $html of contents of notice
760 * @param string|array $className corresponding to notice
761 * @return string of HTML representing the notice
763 public static function noticeBox( $html, $className ) {
764 return self::messageBox( $html, [ 'mw-message-box-notice', $className ] );
768 * Return a warning box.
769 * @since 1.31
770 * @since 1.34 $className optional parameter added
771 * @param string $html of contents of box
772 * @param string $className (optional) corresponding to box
773 * @return string of HTML representing a warning box.
775 public static function warningBox( $html, $className = '' ) {
776 return self::messageBox( $html, [ 'mw-message-box-warning', $className ] );
780 * Return an error box.
781 * @since 1.31
782 * @since 1.34 $className optional parameter added
783 * @param string $html of contents of error box
784 * @param string $heading (optional)
785 * @param string $className (optional) corresponding to box
786 * @return string of HTML representing an error box.
788 public static function errorBox( $html, $heading = '', $className = '' ) {
789 return self::messageBox( $html, [ 'mw-message-box-error', $className ], $heading );
793 * Return a success box.
794 * @since 1.31
795 * @since 1.34 $className optional parameter added
796 * @param string $html of contents of box
797 * @param string $className (optional) corresponding to box
798 * @return string of HTML representing a success box.
800 public static function successBox( $html, $className = '' ) {
801 return self::messageBox( $html, [ 'mw-message-box-success', $className ] );
805 * Convenience function to produce a radio button (input element with type=radio)
807 * @param string $name Name attribute
808 * @param bool $checked Whether the radio button is checked or not
809 * @param array $attribs Array of additional attributes
810 * @return string Raw HTML
812 public static function radio( $name, $checked = false, array $attribs = [] ) {
813 if ( isset( $attribs['value'] ) ) {
814 $value = $attribs['value'];
815 unset( $attribs['value'] );
816 } else {
817 $value = 1;
820 if ( $checked ) {
821 $attribs[] = 'checked';
824 return self::input( $name, $value, 'radio', $attribs );
828 * Convenience function for generating a label for inputs.
830 * @param string $label Contents of the label
831 * @param string $id ID of the element being labeled
832 * @param array $attribs Additional attributes
833 * @return string Raw HTML
835 public static function label( $label, $id, array $attribs = [] ) {
836 $attribs += [
837 'for' => $id
839 return self::element( 'label', $attribs, $label );
843 * Convenience function to produce an input element with type=hidden
845 * @param string $name Name attribute
846 * @param mixed $value Value attribute
847 * @param array $attribs Associative array of miscellaneous extra
848 * attributes, passed to Html::element()
849 * @return string Raw HTML
851 public static function hidden( $name, $value, array $attribs = [] ) {
852 return self::input( $name, $value, 'hidden', $attribs );
856 * Convenience function to produce a <textarea> element.
858 * This supports leaving out the cols= and rows= which Xml requires and are
859 * required by HTML4/XHTML but not required by HTML5.
861 * @param string $name Name attribute
862 * @param string $value Value attribute
863 * @param array $attribs Associative array of miscellaneous extra
864 * attributes, passed to Html::element()
865 * @return string Raw HTML
867 public static function textarea( $name, $value = '', array $attribs = [] ) {
868 $attribs['name'] = $name;
870 if ( substr( $value, 0, 1 ) == "\n" ) {
871 // Workaround for T14130: browsers eat the initial newline
872 // assuming that it's just for show, but they do keep the later
873 // newlines, which we may want to preserve during editing.
874 // Prepending a single newline
875 $spacedValue = "\n" . $value;
876 } else {
877 $spacedValue = $value;
879 return self::element( 'textarea', self::getTextInputAttributes( $attribs ), $spacedValue );
883 * Helper for Html::namespaceSelector().
884 * @param array $params See Html::namespaceSelector()
885 * @return array
887 public static function namespaceSelectorOptions( array $params = [] ) {
888 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
889 $params['exclude'] = [];
892 if ( $params['in-user-lang'] ?? false ) {
893 global $wgLang;
894 $lang = $wgLang;
895 } else {
896 $lang = MediaWikiServices::getInstance()->getContentLanguage();
899 $optionsOut = [];
900 if ( isset( $params['all'] ) ) {
901 // add an option that would let the user select all namespaces.
902 // Value is provided by user, the name shown is localized for the user.
903 $optionsOut[$params['all']] = wfMessage( 'namespacesall' )->text();
905 // Add all namespaces as options
906 $options = $lang->getFormattedNamespaces();
907 // Filter out namespaces below 0 and massage labels
908 foreach ( $options as $nsId => $nsName ) {
909 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
910 continue;
912 if ( $nsId === NS_MAIN ) {
913 // For other namespaces use the namespace prefix as label, but for
914 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
915 $nsName = wfMessage( 'blanknamespace' )->text();
916 } elseif ( is_int( $nsId ) ) {
917 $converter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
918 ->getLanguageConverter( $lang );
919 $nsName = $converter->convertNamespace( $nsId );
921 $optionsOut[$nsId] = $nsName;
924 return $optionsOut;
928 * Build a drop-down box for selecting a namespace
930 * @param array $params Params to set.
931 * - selected: [optional] Id of namespace which should be pre-selected
932 * - all: [optional] Value of item for "all namespaces". If null or unset,
933 * no "<option>" is generated to select all namespaces.
934 * - label: text for label to add before the field.
935 * - exclude: [optional] Array of namespace ids to exclude.
936 * - disable: [optional] Array of namespace ids for which the option should
937 * be disabled in the selector.
938 * @param array $selectAttribs HTML attributes for the generated select element.
939 * - id: [optional], default: 'namespace'.
940 * - name: [optional], default: 'namespace'.
941 * @return string HTML code to select a namespace.
943 public static function namespaceSelector( array $params = [],
944 array $selectAttribs = []
946 ksort( $selectAttribs );
948 // Is a namespace selected?
949 if ( isset( $params['selected'] ) ) {
950 // If string only contains digits, convert to clean int. Selected could also
951 // be "all" or "" etc. which needs to be left untouched.
952 if ( !is_int( $params['selected'] ) && ctype_digit( (string)$params['selected'] ) ) {
953 $params['selected'] = (int)$params['selected'];
955 // else: leaves it untouched for later processing
956 } else {
957 $params['selected'] = '';
960 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
961 $params['disable'] = [];
964 // Associative array between option-values and option-labels
965 $options = self::namespaceSelectorOptions( $params );
967 // Convert $options to HTML
968 $optionsHtml = [];
969 foreach ( $options as $nsId => $nsName ) {
970 $optionsHtml[] = self::element(
971 'option', [
972 'disabled' => in_array( $nsId, $params['disable'] ),
973 'value' => $nsId,
974 'selected' => $nsId === $params['selected'],
975 ], $nsName
979 if ( !array_key_exists( 'id', $selectAttribs ) ) {
980 $selectAttribs['id'] = 'namespace';
983 if ( !array_key_exists( 'name', $selectAttribs ) ) {
984 $selectAttribs['name'] = 'namespace';
987 $ret = '';
988 if ( isset( $params['label'] ) ) {
989 $ret .= self::element(
990 'label', [
991 'for' => $selectAttribs['id'] ?? null,
992 ], $params['label']
993 ) . "\u{00A0}";
996 // Wrap options in a <select>
997 $ret .= self::openElement( 'select', $selectAttribs )
998 . "\n"
999 . implode( "\n", $optionsHtml )
1000 . "\n"
1001 . self::closeElement( 'select' );
1003 return $ret;
1007 * Constructs the opening html-tag with necessary doctypes depending on
1008 * global variables.
1010 * @param array $attribs Associative array of miscellaneous extra
1011 * attributes, passed to Html::element() of html tag.
1012 * @return string Raw HTML
1014 public static function htmlHeader( array $attribs = [] ) {
1015 $ret = '';
1016 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1017 $html5Version = $mainConfig->get( MainConfigNames::Html5Version );
1018 $mimeType = $mainConfig->get( MainConfigNames::MimeType );
1019 $xhtmlNamespaces = $mainConfig->get( MainConfigNames::XhtmlNamespaces );
1021 $isXHTML = self::isXmlMimeType( $mimeType );
1023 if ( $isXHTML ) { // XHTML5
1024 // XML MIME-typed markup should have an xml header.
1025 // However a DOCTYPE is not needed.
1026 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
1028 // Add the standard xmlns
1029 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
1031 // And support custom namespaces
1032 foreach ( $xhtmlNamespaces as $tag => $ns ) {
1033 $attribs["xmlns:$tag"] = $ns;
1035 } else { // HTML5
1036 $ret .= "<!DOCTYPE html>\n";
1039 if ( $html5Version ) {
1040 $attribs['version'] = $html5Version;
1043 $ret .= self::openElement( 'html', $attribs );
1045 return $ret;
1049 * Determines if the given MIME type is xml.
1051 * @param string $mimetype
1052 * @return bool
1054 public static function isXmlMimeType( $mimetype ) {
1055 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
1056 # * text/xml
1057 # * application/xml
1058 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1059 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1063 * Generate a srcset attribute value.
1065 * Generates a srcset attribute value from an array mapping pixel densities
1066 * to URLs. A trailing 'x' in pixel density values is optional.
1068 * @note srcset width and height values are not supported.
1070 * @see https://html.spec.whatwg.org/#attr-img-srcset
1072 * @par Example:
1073 * @code
1074 * Html::srcSet( [
1075 * '1x' => 'standard.jpeg',
1076 * '1.5x' => 'large.jpeg',
1077 * '3x' => 'extra-large.jpeg',
1078 * ] );
1079 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1080 * @endcode
1082 * @param string[] $urls
1083 * @return string
1085 public static function srcSet( array $urls ) {
1086 $candidates = [];
1087 foreach ( $urls as $density => $url ) {
1088 // Cast density to float to strip 'x', then back to string to serve
1089 // as array index.
1090 $density = (string)(float)$density;
1091 $candidates[$density] = $url;
1094 // Remove duplicates that are the same as a smaller value
1095 ksort( $candidates, SORT_NUMERIC );
1096 $candidates = array_unique( $candidates );
1098 // Append density info to the url
1099 foreach ( $candidates as $density => $url ) {
1100 $candidates[$density] = $url . ' ' . $density . 'x';
1103 return implode( ", ", $candidates );