When serializing Message, don't try to unstub StubUserLang
[mediawiki.git] / includes / Html.php
blob5f91dacaba104b26716c1bc9fa8d45f1770df884
1 <?php
2 /**
3 * Collection of methods to generate HTML content
5 * Copyright © 2009 Aryeh Gregor
6 * http://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 /**
27 * This class is a collection of static functions that serve two purposes:
29 * 1) Implement any algorithms specified by HTML5, or other HTML
30 * specifications, in a convenient and self-contained way.
32 * 2) Allow HTML elements to be conveniently and safely generated, like the
33 * current Xml class but a) less confused (Xml supports HTML-specific things,
34 * but only sometimes!) and b) not necessarily confined to XML-compatible
35 * output.
37 * There are two important configuration options this class uses:
39 * $wgMimeType: If this is set to an xml MIME type then output should be
40 * valid XHTML5.
41 * $wgWellFormedXml: If this is set to true, then all output should be
42 * well-formed XML (quotes on attributes, self-closing tags, etc.).
44 * This class is meant to be confined to utility functions that are called from
45 * trusted code paths. It does not do enforcement of policy like not allowing
46 * <a> elements.
48 * @since 1.16
50 class Html {
51 // List of void elements from HTML5, section 8.1.2 as of 2011-08-12
52 private static $voidElements = array(
53 'area',
54 'base',
55 'br',
56 'col',
57 'command',
58 'embed',
59 'hr',
60 'img',
61 'input',
62 'keygen',
63 'link',
64 'meta',
65 'param',
66 'source',
67 'track',
68 'wbr',
71 // Boolean attributes, which may have the value omitted entirely. Manually
72 // collected from the HTML5 spec as of 2011-08-12.
73 private static $boolAttribs = array(
74 'async',
75 'autofocus',
76 'autoplay',
77 'checked',
78 'controls',
79 'default',
80 'defer',
81 'disabled',
82 'formnovalidate',
83 'hidden',
84 'ismap',
85 'itemscope',
86 'loop',
87 'multiple',
88 'muted',
89 'novalidate',
90 'open',
91 'pubdate',
92 'readonly',
93 'required',
94 'reversed',
95 'scoped',
96 'seamless',
97 'selected',
98 'truespeed',
99 'typemustmatch',
100 // HTML5 Microdata
101 'itemscope',
105 * Modifies a set of attributes meant for button elements
106 * and apply a set of default attributes when $wgUseMediaWikiUIEverywhere enabled.
107 * @param array $attrs HTML attributes in an associative array
108 * @param string[] $modifiers classes to add to the button
109 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
110 * @return array $attrs A modified attribute array
112 public static function buttonAttributes( array $attrs, array $modifiers = array() ) {
113 global $wgUseMediaWikiUIEverywhere;
114 if ( $wgUseMediaWikiUIEverywhere ) {
115 if ( isset( $attrs['class'] ) ) {
116 if ( is_array( $attrs['class'] ) ) {
117 $attrs['class'][] = 'mw-ui-button';
118 $attrs['class'] = array_merge( $attrs['class'], $modifiers );
119 // ensure compatibility with Xml
120 $attrs['class'] = implode( ' ', $attrs['class'] );
121 } else {
122 $attrs['class'] .= ' mw-ui-button ' . implode( ' ', $modifiers );
124 } else {
125 // ensure compatibility with Xml
126 $attrs['class'] = 'mw-ui-button ' . implode( ' ', $modifiers );
129 return $attrs;
133 * Modifies a set of attributes meant for text input elements
134 * and apply a set of default attributes.
135 * Removes size attribute when $wgUseMediaWikiUIEverywhere enabled.
136 * @param array $attrs An attribute array.
137 * @return array $attrs A modified attribute array
139 public static function getTextInputAttributes( array $attrs ) {
140 global $wgUseMediaWikiUIEverywhere;
141 if ( $wgUseMediaWikiUIEverywhere ) {
142 if ( isset( $attrs['class'] ) ) {
143 if ( is_array( $attrs['class'] ) ) {
144 $attrs['class'][] = 'mw-ui-input';
145 } else {
146 $attrs['class'] .= ' mw-ui-input';
148 } else {
149 $attrs['class'] = 'mw-ui-input';
152 return $attrs;
156 * Returns an HTML link element in a string styled as a button
157 * (when $wgUseMediaWikiUIEverywhere is enabled).
159 * @param string $contents The raw HTML contents of the element: *not*
160 * escaped!
161 * @param array $attrs Associative array of attributes, e.g., array(
162 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
163 * further documentation.
164 * @param string[] $modifiers classes to add to the button
165 * @see http://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
166 * @return string Raw HTML
168 public static function linkButton( $contents, array $attrs, array $modifiers = array() ) {
169 return self::element( 'a',
170 self::buttonAttributes( $attrs, $modifiers ),
171 $contents
176 * Returns an HTML link element in a string styled as a button
177 * (when $wgUseMediaWikiUIEverywhere is enabled).
179 * @param string $contents The raw HTML contents of the element: *not*
180 * escaped!
181 * @param array $attrs Associative array of attributes, e.g., array(
182 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
183 * further documentation.
184 * @param string[] $modifiers classes to add to the button
185 * @see http://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
186 * @return string Raw HTML
188 public static function submitButton( $contents, array $attrs, array $modifiers = array() ) {
189 $attrs['type'] = 'submit';
190 $attrs['value'] = $contents;
191 return self::element( 'input', self::buttonAttributes( $attrs, $modifiers ) );
195 * Returns an HTML element in a string. The major advantage here over
196 * manually typing out the HTML is that it will escape all attribute
197 * values.
199 * This is quite similar to Xml::tags(), but it implements some useful
200 * HTML-specific logic. For instance, there is no $allowShortTag
201 * parameter: the closing tag is magically omitted if $element has an empty
202 * content model. If $wgWellFormedXml is false, then a few bytes will be
203 * shaved off the HTML output as well.
205 * @param string $element The element's name, e.g., 'a'
206 * @param array $attribs Associative array of attributes, e.g., array(
207 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
208 * further documentation.
209 * @param string $contents The raw HTML contents of the element: *not*
210 * escaped!
211 * @return string Raw HTML
213 public static function rawElement( $element, $attribs = array(), $contents = '' ) {
214 global $wgWellFormedXml;
215 $start = self::openElement( $element, $attribs );
216 if ( in_array( $element, self::$voidElements ) ) {
217 if ( $wgWellFormedXml ) {
218 // Silly XML.
219 return substr( $start, 0, -1 ) . ' />';
221 return $start;
222 } else {
223 return "$start$contents" . self::closeElement( $element );
228 * Identical to rawElement(), but HTML-escapes $contents (like
229 * Xml::element()).
231 * @param string $element
232 * @param array $attribs
233 * @param string $contents
235 * @return string
237 public static function element( $element, $attribs = array(), $contents = '' ) {
238 return self::rawElement( $element, $attribs, strtr( $contents, array(
239 // There's no point in escaping quotes, >, etc. in the contents of
240 // elements.
241 '&' => '&amp;',
242 '<' => '&lt;'
243 ) ) );
247 * Identical to rawElement(), but has no third parameter and omits the end
248 * tag (and the self-closing '/' in XML mode for empty elements).
250 * @param string $element
251 * @param array $attribs
253 * @return string
255 public static function openElement( $element, $attribs = array() ) {
256 $attribs = (array)$attribs;
257 // This is not required in HTML5, but let's do it anyway, for
258 // consistency and better compression.
259 $element = strtolower( $element );
261 // Remove invalid input types
262 if ( $element == 'input' ) {
263 $validTypes = array(
264 'hidden',
265 'text',
266 'password',
267 'checkbox',
268 'radio',
269 'file',
270 'submit',
271 'image',
272 'reset',
273 'button',
275 // HTML input types
276 'datetime',
277 'datetime-local',
278 'date',
279 'month',
280 'time',
281 'week',
282 'number',
283 'range',
284 'email',
285 'url',
286 'search',
287 'tel',
288 'color',
290 if ( isset( $attribs['type'] ) && !in_array( $attribs['type'], $validTypes ) ) {
291 unset( $attribs['type'] );
295 // According to standard the default type for <button> elements is "submit".
296 // Depending on compatibility mode IE might use "button", instead.
297 // We enforce the standard "submit".
298 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
299 $attribs['type'] = 'submit';
302 return "<$element" . self::expandAttributes(
303 self::dropDefaults( $element, $attribs ) ) . '>';
307 * Returns "</$element>"
309 * @since 1.17
310 * @param string $element Name of the element, e.g., 'a'
311 * @return string A closing tag
313 public static function closeElement( $element ) {
314 $element = strtolower( $element );
316 return "</$element>";
320 * Given an element name and an associative array of element attributes,
321 * return an array that is functionally identical to the input array, but
322 * possibly smaller. In particular, attributes might be stripped if they
323 * are given their default values.
325 * This method is not guaranteed to remove all redundant attributes, only
326 * some common ones and some others selected arbitrarily at random. It
327 * only guarantees that the output array should be functionally identical
328 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
330 * @param string $element Name of the element, e.g., 'a'
331 * @param array $attribs Associative array of attributes, e.g., array(
332 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
333 * further documentation.
334 * @return array An array of attributes functionally identical to $attribs
336 private static function dropDefaults( $element, array $attribs ) {
337 // Whenever altering this array, please provide a covering test case
338 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
339 static $attribDefaults = array(
340 'area' => array( 'shape' => 'rect' ),
341 'button' => array(
342 'formaction' => 'GET',
343 'formenctype' => 'application/x-www-form-urlencoded',
345 'canvas' => array(
346 'height' => '150',
347 'width' => '300',
349 'command' => array( 'type' => 'command' ),
350 'form' => array(
351 'action' => 'GET',
352 'autocomplete' => 'on',
353 'enctype' => 'application/x-www-form-urlencoded',
355 'input' => array(
356 'formaction' => 'GET',
357 'type' => 'text',
359 'keygen' => array( 'keytype' => 'rsa' ),
360 'link' => array( 'media' => 'all' ),
361 'menu' => array( 'type' => 'list' ),
362 'script' => array( 'type' => 'text/javascript' ),
363 'style' => array(
364 'media' => 'all',
365 'type' => 'text/css',
367 'textarea' => array( 'wrap' => 'soft' ),
370 $element = strtolower( $element );
372 foreach ( $attribs as $attrib => $value ) {
373 $lcattrib = strtolower( $attrib );
374 if ( is_array( $value ) ) {
375 $value = implode( ' ', $value );
376 } else {
377 $value = strval( $value );
380 // Simple checks using $attribDefaults
381 if ( isset( $attribDefaults[$element][$lcattrib] )
382 && $attribDefaults[$element][$lcattrib] == $value
384 unset( $attribs[$attrib] );
387 if ( $lcattrib == 'class' && $value == '' ) {
388 unset( $attribs[$attrib] );
392 // More subtle checks
393 if ( $element === 'link'
394 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
396 unset( $attribs['type'] );
398 if ( $element === 'input' ) {
399 $type = isset( $attribs['type'] ) ? $attribs['type'] : null;
400 $value = isset( $attribs['value'] ) ? $attribs['value'] : null;
401 if ( $type === 'checkbox' || $type === 'radio' ) {
402 // The default value for checkboxes and radio buttons is 'on'
403 // not ''. By stripping value="" we break radio boxes that
404 // actually wants empty values.
405 if ( $value === 'on' ) {
406 unset( $attribs['value'] );
408 } elseif ( $type === 'submit' ) {
409 // The default value for submit appears to be "Submit" but
410 // let's not bother stripping out localized text that matches
411 // that.
412 } else {
413 // The default value for nearly every other field type is ''
414 // The 'range' and 'color' types use different defaults but
415 // stripping a value="" does not hurt them.
416 if ( $value === '' ) {
417 unset( $attribs['value'] );
421 if ( $element === 'select' && isset( $attribs['size'] ) ) {
422 if ( in_array( 'multiple', $attribs )
423 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
425 // A multi-select
426 if ( strval( $attribs['size'] ) == '4' ) {
427 unset( $attribs['size'] );
429 } else {
430 // Single select
431 if ( strval( $attribs['size'] ) == '1' ) {
432 unset( $attribs['size'] );
437 return $attribs;
441 * Given an associative array of element attributes, generate a string
442 * to stick after the element name in HTML output. Like array( 'href' =>
443 * 'http://www.mediawiki.org/' ) becomes something like
444 * ' href="http://www.mediawiki.org"'. Again, this is like
445 * Xml::expandAttributes(), but it implements some HTML-specific logic.
446 * For instance, it will omit quotation marks if $wgWellFormedXml is false,
447 * and will treat boolean attributes specially.
449 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
450 * values are allowed as well, which will automagically be normalized
451 * and converted to a space-separated string. In addition to a numerical
452 * array, the attribute value may also be an associative array. See the
453 * example below for how that works.
455 * @par Numerical array
456 * @code
457 * Html::element( 'em', array(
458 * 'class' => array( 'foo', 'bar' )
459 * ) );
460 * // gives '<em class="foo bar"></em>'
461 * @endcode
463 * @par Associative array
464 * @code
465 * Html::element( 'em', array(
466 * 'class' => array( 'foo', 'bar', 'foo' => false, 'quux' => true )
467 * ) );
468 * // gives '<em class="bar quux"></em>'
469 * @endcode
471 * @param array $attribs Associative array of attributes, e.g., array(
472 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
473 * A value of false means to omit the attribute. For boolean attributes,
474 * you can omit the key, e.g., array( 'checked' ) instead of
475 * array( 'checked' => 'checked' ) or such.
477 * @throws MWException If an attribute that doesn't allow lists is set to an array
478 * @return string HTML fragment that goes between element name and '>'
479 * (starting with a space if at least one attribute is output)
481 public static function expandAttributes( array $attribs ) {
482 global $wgWellFormedXml;
484 $ret = '';
485 foreach ( $attribs as $key => $value ) {
486 // Support intuitive array( 'checked' => true/false ) form
487 if ( $value === false || is_null( $value ) ) {
488 continue;
491 // For boolean attributes, support array( 'foo' ) instead of
492 // requiring array( 'foo' => 'meaningless' ).
493 if ( is_int( $key ) && in_array( strtolower( $value ), self::$boolAttribs ) ) {
494 $key = $value;
497 // Not technically required in HTML5 but we'd like consistency
498 // and better compression anyway.
499 $key = strtolower( $key );
501 // Bug 23769: Blacklist all form validation attributes for now. Current
502 // (June 2010) WebKit has no UI, so the form just refuses to submit
503 // without telling the user why, which is much worse than failing
504 // server-side validation. Opera is the only other implementation at
505 // this time, and has ugly UI, so just kill the feature entirely until
506 // we have at least one good implementation.
508 // As the default value of "1" for "step" rejects decimal
509 // numbers to be entered in 'type="number"' fields, allow
510 // the special case 'step="any"'.
512 if ( in_array( $key, array( 'max', 'min', 'pattern', 'required' ) )
513 || $key === 'step' && $value !== 'any' ) {
514 continue;
517 // http://www.w3.org/TR/html401/index/attributes.html ("space-separated")
518 // http://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
519 $spaceSeparatedListAttributes = array(
520 'class', // html4, html5
521 'accesskey', // as of html5, multiple space-separated values allowed
522 // html4-spec doesn't document rel= as space-separated
523 // but has been used like that and is now documented as such
524 // in the html5-spec.
525 'rel',
528 // Specific features for attributes that allow a list of space-separated values
529 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
530 // Apply some normalization and remove duplicates
532 // Convert into correct array. Array can contain space-separated
533 // values. Implode/explode to get those into the main array as well.
534 if ( is_array( $value ) ) {
535 // If input wasn't an array, we can skip this step
536 $newValue = array();
537 foreach ( $value as $k => $v ) {
538 if ( is_string( $v ) ) {
539 // String values should be normal `array( 'foo' )`
540 // Just append them
541 if ( !isset( $value[$v] ) ) {
542 // As a special case don't set 'foo' if a
543 // separate 'foo' => true/false exists in the array
544 // keys should be authoritative
545 $newValue[] = $v;
547 } elseif ( $v ) {
548 // If the value is truthy but not a string this is likely
549 // an array( 'foo' => true ), falsy values don't add strings
550 $newValue[] = $k;
553 $value = implode( ' ', $newValue );
555 $value = explode( ' ', $value );
557 // Normalize spacing by fixing up cases where people used
558 // more than 1 space and/or a trailing/leading space
559 $value = array_diff( $value, array( '', ' ' ) );
561 // Remove duplicates and create the string
562 $value = implode( ' ', array_unique( $value ) );
563 } elseif ( is_array( $value ) ) {
564 throw new MWException( "HTML attribute $key can not contain a list of values" );
567 // See the "Attributes" section in the HTML syntax part of HTML5,
568 // 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
569 // marks omitted, but not all. (Although a literal " is not
570 // permitted, we don't check for that, since it will be escaped
571 // anyway.)
573 // See also research done on further characters that need to be
574 // escaped: http://code.google.com/p/html5lib/issues/detail?id=93
575 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
576 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
577 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
578 if ( $wgWellFormedXml || $value === '' || preg_match( "![$badChars]!u", $value ) ) {
579 $quote = '"';
580 } else {
581 $quote = '';
584 if ( in_array( $key, self::$boolAttribs ) ) {
585 // In HTML5, we can leave the value empty. If we don't need
586 // well-formed XML, we can omit the = entirely.
587 if ( !$wgWellFormedXml ) {
588 $ret .= " $key";
589 } else {
590 $ret .= " $key=\"\"";
592 } else {
593 // Apparently we need to entity-encode \n, \r, \t, although the
594 // spec doesn't mention that. Since we're doing strtr() anyway,
595 // we may as well not call htmlspecialchars().
596 // @todo FIXME: Verify that we actually need to
597 // escape \n\r\t here, and explain why, exactly.
598 // We could call Sanitizer::encodeAttribute() for this, but we
599 // don't because we're stubborn and like our marginal savings on
600 // byte size from not having to encode unnecessary quotes.
601 // The only difference between this transform and the one by
602 // Sanitizer::encodeAttribute() is '<' is only encoded here if
603 // $wgWellFormedXml is set, and ' is not encoded.
604 $map = array(
605 '&' => '&amp;',
606 '"' => '&quot;',
607 '>' => '&gt;',
608 "\n" => '&#10;',
609 "\r" => '&#13;',
610 "\t" => '&#9;'
612 if ( $wgWellFormedXml ) {
613 // This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
614 // But reportedly it breaks some XML tools?
615 // @todo FIXME: Is this really true?
616 $map['<'] = '&lt;';
618 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
621 return $ret;
625 * Output a "<script>" tag with the given contents.
627 * @todo do some useful escaping as well, like if $contents contains
628 * literal "</script>" or (for XML) literal "]]>".
630 * @param string $contents JavaScript
631 * @return string Raw HTML
633 public static function inlineScript( $contents ) {
634 global $wgWellFormedXml;
636 $attrs = array();
638 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
639 $contents = "/*<![CDATA[*/$contents/*]]>*/";
642 return self::rawElement( 'script', $attrs, $contents );
646 * Output a "<script>" tag linking to the given URL, e.g.,
647 * "<script src=foo.js></script>".
649 * @param string $url
650 * @return string Raw HTML
652 public static function linkedScript( $url ) {
653 $attrs = array( 'src' => $url );
655 return self::element( 'script', $attrs );
659 * Output a "<style>" tag with the given contents for the given media type
660 * (if any). TODO: do some useful escaping as well, like if $contents
661 * contains literal "</style>" (admittedly unlikely).
663 * @param string $contents CSS
664 * @param string $media A media type string, like 'screen'
665 * @return string Raw HTML
667 public static function inlineStyle( $contents, $media = 'all' ) {
668 global $wgWellFormedXml;
670 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
671 $contents = "/*<![CDATA[*/$contents/*]]>*/";
674 return self::rawElement( 'style', array(
675 'media' => $media,
676 ), $contents );
680 * Output a "<link rel=stylesheet>" linking to the given URL for the given
681 * media type (if any).
683 * @param string $url
684 * @param string $media A media type string, like 'screen'
685 * @return string Raw HTML
687 public static function linkedStyle( $url, $media = 'all' ) {
688 return self::element( 'link', array(
689 'rel' => 'stylesheet',
690 'href' => $url,
691 'media' => $media,
692 ) );
696 * Convenience function to produce an "<input>" element. This supports the
697 * new HTML5 input types and attributes.
699 * @param string $name Name attribute
700 * @param string $value Value attribute
701 * @param string $type Type attribute
702 * @param array $attribs Associative array of miscellaneous extra
703 * attributes, passed to Html::element()
704 * @return string Raw HTML
706 public static function input( $name, $value = '', $type = 'text', array $attribs = array() ) {
707 $attribs['type'] = $type;
708 $attribs['value'] = $value;
709 $attribs['name'] = $name;
710 if ( in_array( $type, array( 'text', 'search', 'email', 'password', 'number' ) ) ) {
711 $attribs = self::getTextInputAttributes( $attribs );
713 if ( in_array( $type, array( 'button', 'reset', 'submit' ) ) ) {
714 $attribs = self::buttonAttributes( $attribs );
716 return self::element( 'input', $attribs );
720 * Convenience function to produce a checkbox (input element with type=checkbox)
722 * @param string $name Name attribute
723 * @param bool $checked Whether the checkbox is checked or not
724 * @param array $attribs Array of additional attributes
725 * @return string Raw HTML
727 public static function check( $name, $checked = false, array $attribs = array() ) {
728 if ( isset( $attribs['value'] ) ) {
729 $value = $attribs['value'];
730 unset( $attribs['value'] );
731 } else {
732 $value = 1;
735 if ( $checked ) {
736 $attribs[] = 'checked';
739 return self::input( $name, $value, 'checkbox', $attribs );
743 * Convenience function to produce a radio button (input element with type=radio)
745 * @param string $name Name attribute
746 * @param bool $checked Whether the radio button is checked or not
747 * @param array $attribs Array of additional attributes
748 * @return string Raw HTML
750 public static function radio( $name, $checked = false, array $attribs = array() ) {
751 if ( isset( $attribs['value'] ) ) {
752 $value = $attribs['value'];
753 unset( $attribs['value'] );
754 } else {
755 $value = 1;
758 if ( $checked ) {
759 $attribs[] = 'checked';
762 return self::input( $name, $value, 'radio', $attribs );
766 * Convenience function for generating a label for inputs.
768 * @param string $label Contents of the label
769 * @param string $id ID of the element being labeled
770 * @param array $attribs Additional attributes
771 * @return string Raw HTML
773 public static function label( $label, $id, array $attribs = array() ) {
774 $attribs += array(
775 'for' => $id
777 return self::element( 'label', $attribs, $label );
781 * Convenience function to produce an input element with type=hidden
783 * @param string $name Name attribute
784 * @param string $value Value attribute
785 * @param array $attribs Associative array of miscellaneous extra
786 * attributes, passed to Html::element()
787 * @return string Raw HTML
789 public static function hidden( $name, $value, array $attribs = array() ) {
790 return self::input( $name, $value, 'hidden', $attribs );
794 * Convenience function to produce a <textarea> element.
796 * This supports leaving out the cols= and rows= which Xml requires and are
797 * required by HTML4/XHTML but not required by HTML5.
799 * @param string $name Name attribute
800 * @param string $value Value attribute
801 * @param array $attribs Associative array of miscellaneous extra
802 * attributes, passed to Html::element()
803 * @return string Raw HTML
805 public static function textarea( $name, $value = '', array $attribs = array() ) {
806 $attribs['name'] = $name;
808 if ( substr( $value, 0, 1 ) == "\n" ) {
809 // Workaround for bug 12130: browsers eat the initial newline
810 // assuming that it's just for show, but they do keep the later
811 // newlines, which we may want to preserve during editing.
812 // Prepending a single newline
813 $spacedValue = "\n" . $value;
814 } else {
815 $spacedValue = $value;
817 return self::element( 'textarea', self::getTextInputAttributes( $attribs ), $spacedValue );
821 * Helper for Html::namespaceSelector().
822 * @param array $params See Html::namespaceSelector()
823 * @return array
825 public static function namespaceSelectorOptions( array $params = array() ) {
826 global $wgContLang;
828 $options = array();
830 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
831 $params['exclude'] = array();
834 if ( isset( $params['all'] ) ) {
835 // add an option that would let the user select all namespaces.
836 // Value is provided by user, the name shown is localized for the user.
837 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
839 // Add all namespaces as options (in the content language)
840 $options += $wgContLang->getFormattedNamespaces();
842 $optionsOut = array();
843 // Filter out namespaces below 0 and massage labels
844 foreach ( $options as $nsId => $nsName ) {
845 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
846 continue;
848 if ( $nsId === NS_MAIN ) {
849 // For other namespaces use the namespace prefix as label, but for
850 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
851 $nsName = wfMessage( 'blanknamespace' )->text();
852 } elseif ( is_int( $nsId ) ) {
853 $nsName = $wgContLang->convertNamespace( $nsId );
855 $optionsOut[$nsId] = $nsName;
858 return $optionsOut;
862 * Build a drop-down box for selecting a namespace
864 * @param array $params Params to set.
865 * - selected: [optional] Id of namespace which should be pre-selected
866 * - all: [optional] Value of item for "all namespaces". If null or unset,
867 * no "<option>" is generated to select all namespaces.
868 * - label: text for label to add before the field.
869 * - exclude: [optional] Array of namespace ids to exclude.
870 * - disable: [optional] Array of namespace ids for which the option should
871 * be disabled in the selector.
872 * @param array $selectAttribs HTML attributes for the generated select element.
873 * - id: [optional], default: 'namespace'.
874 * - name: [optional], default: 'namespace'.
875 * @return string HTML code to select a namespace.
877 public static function namespaceSelector( array $params = array(),
878 array $selectAttribs = array()
880 ksort( $selectAttribs );
882 // Is a namespace selected?
883 if ( isset( $params['selected'] ) ) {
884 // If string only contains digits, convert to clean int. Selected could also
885 // be "all" or "" etc. which needs to be left untouched.
886 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
887 // and returns false for already clean ints. Use regex instead..
888 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
889 $params['selected'] = intval( $params['selected'] );
891 // else: leaves it untouched for later processing
892 } else {
893 $params['selected'] = '';
896 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
897 $params['disable'] = array();
900 // Associative array between option-values and option-labels
901 $options = self::namespaceSelectorOptions( $params );
903 // Convert $options to HTML
904 $optionsHtml = array();
905 foreach ( $options as $nsId => $nsName ) {
906 $optionsHtml[] = self::element(
907 'option', array(
908 'disabled' => in_array( $nsId, $params['disable'] ),
909 'value' => $nsId,
910 'selected' => $nsId === $params['selected'],
911 ), $nsName
915 if ( !array_key_exists( 'id', $selectAttribs ) ) {
916 $selectAttribs['id'] = 'namespace';
919 if ( !array_key_exists( 'name', $selectAttribs ) ) {
920 $selectAttribs['name'] = 'namespace';
923 $ret = '';
924 if ( isset( $params['label'] ) ) {
925 $ret .= self::element(
926 'label', array(
927 'for' => isset( $selectAttribs['id'] ) ? $selectAttribs['id'] : null,
928 ), $params['label']
929 ) . '&#160;';
932 // Wrap options in a <select>
933 $ret .= self::openElement( 'select', $selectAttribs )
934 . "\n"
935 . implode( "\n", $optionsHtml )
936 . "\n"
937 . self::closeElement( 'select' );
939 return $ret;
943 * Constructs the opening html-tag with necessary doctypes depending on
944 * global variables.
946 * @param array $attribs Associative array of miscellaneous extra
947 * attributes, passed to Html::element() of html tag.
948 * @return string Raw HTML
950 public static function htmlHeader( array $attribs = array() ) {
951 $ret = '';
953 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
955 $isXHTML = self::isXmlMimeType( $wgMimeType );
957 if ( $isXHTML ) { // XHTML5
958 // XML MIME-typed markup should have an xml header.
959 // However a DOCTYPE is not needed.
960 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
962 // Add the standard xmlns
963 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
965 // And support custom namespaces
966 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
967 $attribs["xmlns:$tag"] = $ns;
969 } else { // HTML5
970 // DOCTYPE
971 $ret .= "<!DOCTYPE html>\n";
974 if ( $wgHtml5Version ) {
975 $attribs['version'] = $wgHtml5Version;
978 $html = self::openElement( 'html', $attribs );
980 if ( $html ) {
981 $html .= "\n";
984 $ret .= $html;
986 return $ret;
990 * Determines if the given MIME type is xml.
992 * @param string $mimetype MIME type
993 * @return bool
995 public static function isXmlMimeType( $mimetype ) {
996 # http://www.whatwg.org/html/infrastructure.html#xml-mime-type
997 # * text/xml
998 # * application/xml
999 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1000 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1004 * Get HTML for an info box with an icon.
1006 * @param string $text Wikitext, get this with wfMessage()->plain()
1007 * @param string $icon Path to icon file (used as 'src' attribute)
1008 * @param string $alt Alternate text for the icon
1009 * @param string $class Additional class name to add to the wrapper div
1011 * @return string
1013 static function infoBox( $text, $icon, $alt, $class = '' ) {
1014 $s = self::openElement( 'div', array( 'class' => "mw-infobox $class" ) );
1016 $s .= self::openElement( 'div', array( 'class' => 'mw-infobox-left' ) ) .
1017 self::element( 'img',
1018 array(
1019 'src' => $icon,
1020 'alt' => $alt,
1023 self::closeElement( 'div' );
1025 $s .= self::openElement( 'div', array( 'class' => 'mw-infobox-right' ) ) .
1026 $text .
1027 self::closeElement( 'div' );
1028 $s .= self::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
1030 $s .= self::closeElement( 'div' );
1032 $s .= self::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
1034 return $s;
1038 * Generate a srcset attribute value.
1040 * Generates a srcset attribute value from an array mapping pixel densities
1041 * to URLs. A trailing 'x' in pixel density values is optional.
1043 * @note srcset width and height values are not supported.
1045 * @see http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
1047 * @par Example:
1048 * @code
1049 * Html::srcSet( array(
1050 * '1x' => 'standard.jpeg',
1051 * '1.5x' => 'large.jpeg',
1052 * '3x' => 'extra-large.jpeg',
1053 * ) );
1054 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1055 * @endcode
1057 * @param string[] $urls
1058 * @return string
1060 static function srcSet( array $urls ) {
1061 $candidates = array();
1062 foreach ( $urls as $density => $url ) {
1063 // Cast density to float to strip 'x'.
1064 $candidates[] = $url . ' ' . (float)$density . 'x';
1066 return implode( ", ", $candidates );