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
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
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
42 * This class is meant to be confined to utility functions that are called from
43 * trusted code paths. It does not do enforcement of policy like not allowing
49 // List of void elements from HTML5, section 8.1.2 as of 2011-08-12
50 private static $voidElements = [
69 // Boolean attributes, which may have the value omitted entirely. Manually
70 // collected from the HTML5 spec as of 2011-08-12.
71 private static $boolAttribs = [
103 * Modifies a set of attributes meant for button elements
104 * and apply a set of default attributes when $wgUseMediaWikiUIEverywhere enabled.
105 * @param array $attrs HTML attributes in an associative array
106 * @param string[] $modifiers classes to add to the button
107 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
108 * @return array $attrs A modified attribute array
110 public static function buttonAttributes( array $attrs, array $modifiers = [] ) {
111 global $wgUseMediaWikiUIEverywhere;
112 if ( $wgUseMediaWikiUIEverywhere ) {
113 if ( isset( $attrs['class'] ) ) {
114 if ( is_array( $attrs['class'] ) ) {
115 $attrs['class'][] = 'mw-ui-button';
116 $attrs['class'] = array_merge( $attrs['class'], $modifiers );
117 // ensure compatibility with Xml
118 $attrs['class'] = implode( ' ', $attrs['class'] );
120 $attrs['class'] .= ' mw-ui-button ' . implode( ' ', $modifiers );
123 // ensure compatibility with Xml
124 $attrs['class'] = 'mw-ui-button ' . implode( ' ', $modifiers );
131 * Modifies a set of attributes meant for text input elements
132 * and apply a set of default attributes.
133 * Removes size attribute when $wgUseMediaWikiUIEverywhere enabled.
134 * @param array $attrs An attribute array.
135 * @return array $attrs A modified attribute array
137 public static function getTextInputAttributes( array $attrs ) {
138 global $wgUseMediaWikiUIEverywhere;
139 if ( $wgUseMediaWikiUIEverywhere ) {
140 if ( isset( $attrs['class'] ) ) {
141 if ( is_array( $attrs['class'] ) ) {
142 $attrs['class'][] = 'mw-ui-input';
144 $attrs['class'] .= ' mw-ui-input';
147 $attrs['class'] = 'mw-ui-input';
154 * Returns an HTML link element in a string styled as a button
155 * (when $wgUseMediaWikiUIEverywhere is enabled).
157 * @param string $contents The raw HTML contents of the element: *not*
159 * @param array $attrs Associative array of attributes, e.g., array(
160 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
161 * further documentation.
162 * @param string[] $modifiers classes to add to the button
163 * @see http://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
164 * @return string Raw HTML
166 public static function linkButton( $contents, array $attrs, array $modifiers = [] ) {
167 return self
::element( 'a',
168 self
::buttonAttributes( $attrs, $modifiers ),
174 * Returns an HTML link element in a string styled as a button
175 * (when $wgUseMediaWikiUIEverywhere is enabled).
177 * @param string $contents The raw HTML contents of the element: *not*
179 * @param array $attrs Associative array of attributes, e.g., array(
180 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
181 * further documentation.
182 * @param string[] $modifiers classes to add to the button
183 * @see http://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
184 * @return string Raw HTML
186 public static function submitButton( $contents, array $attrs, array $modifiers = [] ) {
187 $attrs['type'] = 'submit';
188 $attrs['value'] = $contents;
189 return self
::element( 'input', self
::buttonAttributes( $attrs, $modifiers ) );
193 * Returns an HTML element in a string. The major advantage here over
194 * manually typing out the HTML is that it will escape all attribute
197 * This is quite similar to Xml::tags(), but it implements some useful
198 * HTML-specific logic. For instance, there is no $allowShortTag
199 * parameter: the closing tag is magically omitted if $element has an empty
202 * @param string $element The element's name, e.g., 'a'
203 * @param array $attribs Associative array of attributes, e.g., array(
204 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
205 * further documentation.
206 * @param string $contents The raw HTML contents of the element: *not*
208 * @return string Raw HTML
210 public static function rawElement( $element, $attribs = [], $contents = '' ) {
211 $start = self
::openElement( $element, $attribs );
212 if ( in_array( $element, self
::$voidElements ) ) {
214 return substr( $start, 0, -1 ) . '/>';
216 return "$start$contents" . self
::closeElement( $element );
221 * Identical to rawElement(), but HTML-escapes $contents (like
224 * @param string $element
225 * @param array $attribs
226 * @param string $contents
230 public static function element( $element, $attribs = [], $contents = '' ) {
231 return self
::rawElement( $element, $attribs, strtr( $contents, [
232 // There's no point in escaping quotes, >, etc. in the contents of
240 * Identical to rawElement(), but has no third parameter and omits the end
241 * tag (and the self-closing '/' in XML mode for empty elements).
243 * @param string $element
244 * @param array $attribs
248 public static function openElement( $element, $attribs = [] ) {
249 $attribs = (array)$attribs;
250 // This is not required in HTML5, but let's do it anyway, for
251 // consistency and better compression.
252 $element = strtolower( $element );
254 // Remove invalid input types
255 if ( $element == 'input' ) {
283 if ( isset( $attribs['type'] ) && !in_array( $attribs['type'], $validTypes ) ) {
284 unset( $attribs['type'] );
288 // According to standard the default type for <button> elements is "submit".
289 // Depending on compatibility mode IE might use "button", instead.
290 // We enforce the standard "submit".
291 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
292 $attribs['type'] = 'submit';
295 return "<$element" . self
::expandAttributes(
296 self
::dropDefaults( $element, $attribs ) ) . '>';
300 * Returns "</$element>"
303 * @param string $element Name of the element, e.g., 'a'
304 * @return string A closing tag
306 public static function closeElement( $element ) {
307 $element = strtolower( $element );
309 return "</$element>";
313 * Given an element name and an associative array of element attributes,
314 * return an array that is functionally identical to the input array, but
315 * possibly smaller. In particular, attributes might be stripped if they
316 * are given their default values.
318 * This method is not guaranteed to remove all redundant attributes, only
319 * some common ones and some others selected arbitrarily at random. It
320 * only guarantees that the output array should be functionally identical
321 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
323 * @param string $element Name of the element, e.g., 'a'
324 * @param array $attribs Associative array of attributes, e.g., array(
325 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
326 * further documentation.
327 * @return array An array of attributes functionally identical to $attribs
329 private static function dropDefaults( $element, array $attribs ) {
330 // Whenever altering this array, please provide a covering test case
331 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
332 static $attribDefaults = [
333 'area' => [ 'shape' => 'rect' ],
335 'formaction' => 'GET',
336 'formenctype' => 'application/x-www-form-urlencoded',
342 'command' => [ 'type' => 'command' ],
345 'autocomplete' => 'on',
346 'enctype' => 'application/x-www-form-urlencoded',
349 'formaction' => 'GET',
352 'keygen' => [ 'keytype' => 'rsa' ],
353 'link' => [ 'media' => 'all' ],
354 'menu' => [ 'type' => 'list' ],
355 'script' => [ 'type' => 'text/javascript' ],
358 'type' => 'text/css',
360 'textarea' => [ 'wrap' => 'soft' ],
363 $element = strtolower( $element );
365 foreach ( $attribs as $attrib => $value ) {
366 $lcattrib = strtolower( $attrib );
367 if ( is_array( $value ) ) {
368 $value = implode( ' ', $value );
370 $value = strval( $value );
373 // Simple checks using $attribDefaults
374 if ( isset( $attribDefaults[$element][$lcattrib] )
375 && $attribDefaults[$element][$lcattrib] == $value
377 unset( $attribs[$attrib] );
380 if ( $lcattrib == 'class' && $value == '' ) {
381 unset( $attribs[$attrib] );
385 // More subtle checks
386 if ( $element === 'link'
387 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
389 unset( $attribs['type'] );
391 if ( $element === 'input' ) {
392 $type = isset( $attribs['type'] ) ?
$attribs['type'] : null;
393 $value = isset( $attribs['value'] ) ?
$attribs['value'] : null;
394 if ( $type === 'checkbox' ||
$type === 'radio' ) {
395 // The default value for checkboxes and radio buttons is 'on'
396 // not ''. By stripping value="" we break radio boxes that
397 // actually wants empty values.
398 if ( $value === 'on' ) {
399 unset( $attribs['value'] );
401 } elseif ( $type === 'submit' ) {
402 // The default value for submit appears to be "Submit" but
403 // let's not bother stripping out localized text that matches
406 // The default value for nearly every other field type is ''
407 // The 'range' and 'color' types use different defaults but
408 // stripping a value="" does not hurt them.
409 if ( $value === '' ) {
410 unset( $attribs['value'] );
414 if ( $element === 'select' && isset( $attribs['size'] ) ) {
415 if ( in_array( 'multiple', $attribs )
416 ||
( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
419 if ( strval( $attribs['size'] ) == '4' ) {
420 unset( $attribs['size'] );
424 if ( strval( $attribs['size'] ) == '1' ) {
425 unset( $attribs['size'] );
434 * Given an associative array of element attributes, generate a string
435 * to stick after the element name in HTML output. Like array( 'href' =>
436 * 'http://www.mediawiki.org/' ) becomes something like
437 * ' href="http://www.mediawiki.org"'. Again, this is like
438 * Xml::expandAttributes(), but it implements some HTML-specific logic.
440 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
441 * values are allowed as well, which will automagically be normalized
442 * and converted to a space-separated string. In addition to a numerical
443 * array, the attribute value may also be an associative array. See the
444 * example below for how that works.
446 * @par Numerical array
448 * Html::element( 'em', array(
449 * 'class' => array( 'foo', 'bar' )
451 * // gives '<em class="foo bar"></em>'
454 * @par Associative array
456 * Html::element( 'em', array(
457 * 'class' => array( 'foo', 'bar', 'foo' => false, 'quux' => true )
459 * // gives '<em class="bar quux"></em>'
462 * @param array $attribs Associative array of attributes, e.g., array(
463 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
464 * A value of false means to omit the attribute. For boolean attributes,
465 * you can omit the key, e.g., array( 'checked' ) instead of
466 * array( 'checked' => 'checked' ) or such.
468 * @throws MWException If an attribute that doesn't allow lists is set to an array
469 * @return string HTML fragment that goes between element name and '>'
470 * (starting with a space if at least one attribute is output)
472 public static function expandAttributes( array $attribs ) {
474 foreach ( $attribs as $key => $value ) {
475 // Support intuitive array( 'checked' => true/false ) form
476 if ( $value === false ||
is_null( $value ) ) {
480 // For boolean attributes, support array( 'foo' ) instead of
481 // requiring array( 'foo' => 'meaningless' ).
482 if ( is_int( $key ) && in_array( strtolower( $value ), self
::$boolAttribs ) ) {
486 // Not technically required in HTML5 but we'd like consistency
487 // and better compression anyway.
488 $key = strtolower( $key );
490 // Bug 23769: Blacklist all form validation attributes for now. Current
491 // (June 2010) WebKit has no UI, so the form just refuses to submit
492 // without telling the user why, which is much worse than failing
493 // server-side validation. Opera is the only other implementation at
494 // this time, and has ugly UI, so just kill the feature entirely until
495 // we have at least one good implementation.
497 // As the default value of "1" for "step" rejects decimal
498 // numbers to be entered in 'type="number"' fields, allow
499 // the special case 'step="any"'.
501 if ( in_array( $key, [ 'max', 'min', 'pattern', 'required' ] )
502 ||
$key === 'step' && $value !== 'any' ) {
506 // http://www.w3.org/TR/html401/index/attributes.html ("space-separated")
507 // http://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
508 $spaceSeparatedListAttributes = [
509 'class', // html4, html5
510 'accesskey', // as of html5, multiple space-separated values allowed
511 // html4-spec doesn't document rel= as space-separated
512 // but has been used like that and is now documented as such
513 // in the html5-spec.
517 // Specific features for attributes that allow a list of space-separated values
518 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
519 // Apply some normalization and remove duplicates
521 // Convert into correct array. Array can contain space-separated
522 // values. Implode/explode to get those into the main array as well.
523 if ( is_array( $value ) ) {
524 // If input wasn't an array, we can skip this step
526 foreach ( $value as $k => $v ) {
527 if ( is_string( $v ) ) {
528 // String values should be normal `array( 'foo' )`
530 if ( !isset( $value[$v] ) ) {
531 // As a special case don't set 'foo' if a
532 // separate 'foo' => true/false exists in the array
533 // keys should be authoritative
537 // If the value is truthy but not a string this is likely
538 // an array( 'foo' => true ), falsy values don't add strings
542 $value = implode( ' ', $newValue );
544 $value = explode( ' ', $value );
546 // Normalize spacing by fixing up cases where people used
547 // more than 1 space and/or a trailing/leading space
548 $value = array_diff( $value, [ '', ' ' ] );
550 // Remove duplicates and create the string
551 $value = implode( ' ', array_unique( $value ) );
552 } elseif ( is_array( $value ) ) {
553 throw new MWException( "HTML attribute $key can not contain a list of values" );
558 if ( in_array( $key, self
::$boolAttribs ) ) {
559 $ret .= " $key=\"\"";
561 // Apparently we need to entity-encode \n, \r, \t, although the
562 // spec doesn't mention that. Since we're doing strtr() anyway,
563 // we may as well not call htmlspecialchars().
564 // @todo FIXME: Verify that we actually need to
565 // escape \n\r\t here, and explain why, exactly.
566 // We could call Sanitizer::encodeAttribute() for this, but we
567 // don't because we're stubborn and like our marginal savings on
568 // byte size from not having to encode unnecessary quotes.
569 // The only difference between this transform and the one by
570 // Sanitizer::encodeAttribute() is ' is not encoded.
575 // '<' allegedly allowed per spec
576 // but breaks some tools if not escaped.
582 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
589 * Output a "<script>" tag with the given contents.
591 * @todo do some useful escaping as well, like if $contents contains
592 * literal "</script>" or (for XML) literal "]]>".
594 * @param string $contents JavaScript
595 * @return string Raw HTML
597 public static function inlineScript( $contents ) {
600 if ( preg_match( '/[<&]/', $contents ) ) {
601 $contents = "/*<![CDATA[*/$contents/*]]>*/";
604 return self
::rawElement( 'script', $attrs, $contents );
608 * Output a "<script>" tag linking to the given URL, e.g.,
609 * "<script src=foo.js></script>".
612 * @return string Raw HTML
614 public static function linkedScript( $url ) {
615 $attrs = [ 'src' => $url ];
617 return self
::element( 'script', $attrs );
621 * Output a "<style>" tag with the given contents for the given media type
622 * (if any). TODO: do some useful escaping as well, like if $contents
623 * contains literal "</style>" (admittedly unlikely).
625 * @param string $contents CSS
626 * @param string $media A media type string, like 'screen'
627 * @return string Raw HTML
629 public static function inlineStyle( $contents, $media = 'all' ) {
630 if ( preg_match( '/[<&]/', $contents ) ) {
631 $contents = "/*<![CDATA[*/$contents/*]]>*/";
634 return self
::rawElement( 'style', [
640 * Output a "<link rel=stylesheet>" linking to the given URL for the given
641 * media type (if any).
644 * @param string $media A media type string, like 'screen'
645 * @return string Raw HTML
647 public static function linkedStyle( $url, $media = 'all' ) {
648 return self
::element( 'link', [
649 'rel' => 'stylesheet',
656 * Convenience function to produce an "<input>" element. This supports the
657 * new HTML5 input types and attributes.
659 * @param string $name Name attribute
660 * @param string $value Value attribute
661 * @param string $type Type attribute
662 * @param array $attribs Associative array of miscellaneous extra
663 * attributes, passed to Html::element()
664 * @return string Raw HTML
666 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
667 $attribs['type'] = $type;
668 $attribs['value'] = $value;
669 $attribs['name'] = $name;
670 if ( in_array( $type, [ 'text', 'search', 'email', 'password', 'number' ] ) ) {
671 $attribs = self
::getTextInputAttributes( $attribs );
673 if ( in_array( $type, [ 'button', 'reset', 'submit' ] ) ) {
674 $attribs = self
::buttonAttributes( $attribs );
676 return self
::element( 'input', $attribs );
680 * Convenience function to produce a checkbox (input element with type=checkbox)
682 * @param string $name Name attribute
683 * @param bool $checked Whether the checkbox is checked or not
684 * @param array $attribs Array of additional attributes
685 * @return string Raw HTML
687 public static function check( $name, $checked = false, array $attribs = [] ) {
688 if ( isset( $attribs['value'] ) ) {
689 $value = $attribs['value'];
690 unset( $attribs['value'] );
696 $attribs[] = 'checked';
699 return self
::input( $name, $value, 'checkbox', $attribs );
703 * Convenience function to produce a radio button (input element with type=radio)
705 * @param string $name Name attribute
706 * @param bool $checked Whether the radio button is checked or not
707 * @param array $attribs Array of additional attributes
708 * @return string Raw HTML
710 public static function radio( $name, $checked = false, array $attribs = [] ) {
711 if ( isset( $attribs['value'] ) ) {
712 $value = $attribs['value'];
713 unset( $attribs['value'] );
719 $attribs[] = 'checked';
722 return self
::input( $name, $value, 'radio', $attribs );
726 * Convenience function for generating a label for inputs.
728 * @param string $label Contents of the label
729 * @param string $id ID of the element being labeled
730 * @param array $attribs Additional attributes
731 * @return string Raw HTML
733 public static function label( $label, $id, array $attribs = [] ) {
737 return self
::element( 'label', $attribs, $label );
741 * Convenience function to produce an input element with type=hidden
743 * @param string $name Name attribute
744 * @param string $value Value attribute
745 * @param array $attribs Associative array of miscellaneous extra
746 * attributes, passed to Html::element()
747 * @return string Raw HTML
749 public static function hidden( $name, $value, array $attribs = [] ) {
750 return self
::input( $name, $value, 'hidden', $attribs );
754 * Convenience function to produce a <textarea> element.
756 * This supports leaving out the cols= and rows= which Xml requires and are
757 * required by HTML4/XHTML but not required by HTML5.
759 * @param string $name Name attribute
760 * @param string $value Value attribute
761 * @param array $attribs Associative array of miscellaneous extra
762 * attributes, passed to Html::element()
763 * @return string Raw HTML
765 public static function textarea( $name, $value = '', array $attribs = [] ) {
766 $attribs['name'] = $name;
768 if ( substr( $value, 0, 1 ) == "\n" ) {
769 // Workaround for bug 12130: browsers eat the initial newline
770 // assuming that it's just for show, but they do keep the later
771 // newlines, which we may want to preserve during editing.
772 // Prepending a single newline
773 $spacedValue = "\n" . $value;
775 $spacedValue = $value;
777 return self
::element( 'textarea', self
::getTextInputAttributes( $attribs ), $spacedValue );
781 * Helper for Html::namespaceSelector().
782 * @param array $params See Html::namespaceSelector()
785 public static function namespaceSelectorOptions( array $params = [] ) {
790 if ( !isset( $params['exclude'] ) ||
!is_array( $params['exclude'] ) ) {
791 $params['exclude'] = [];
794 if ( isset( $params['all'] ) ) {
795 // add an option that would let the user select all namespaces.
796 // Value is provided by user, the name shown is localized for the user.
797 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
799 // Add all namespaces as options (in the content language)
800 $options +
= $wgContLang->getFormattedNamespaces();
803 // Filter out namespaces below 0 and massage labels
804 foreach ( $options as $nsId => $nsName ) {
805 if ( $nsId < NS_MAIN ||
in_array( $nsId, $params['exclude'] ) ) {
808 if ( $nsId === NS_MAIN
) {
809 // For other namespaces use the namespace prefix as label, but for
810 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
811 $nsName = wfMessage( 'blanknamespace' )->text();
812 } elseif ( is_int( $nsId ) ) {
813 $nsName = $wgContLang->convertNamespace( $nsId );
815 $optionsOut[$nsId] = $nsName;
822 * Build a drop-down box for selecting a namespace
824 * @param array $params Params to set.
825 * - selected: [optional] Id of namespace which should be pre-selected
826 * - all: [optional] Value of item for "all namespaces". If null or unset,
827 * no "<option>" is generated to select all namespaces.
828 * - label: text for label to add before the field.
829 * - exclude: [optional] Array of namespace ids to exclude.
830 * - disable: [optional] Array of namespace ids for which the option should
831 * be disabled in the selector.
832 * @param array $selectAttribs HTML attributes for the generated select element.
833 * - id: [optional], default: 'namespace'.
834 * - name: [optional], default: 'namespace'.
835 * @return string HTML code to select a namespace.
837 public static function namespaceSelector( array $params = [],
838 array $selectAttribs = []
840 ksort( $selectAttribs );
842 // Is a namespace selected?
843 if ( isset( $params['selected'] ) ) {
844 // If string only contains digits, convert to clean int. Selected could also
845 // be "all" or "" etc. which needs to be left untouched.
846 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
847 // and returns false for already clean ints. Use regex instead..
848 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
849 $params['selected'] = intval( $params['selected'] );
851 // else: leaves it untouched for later processing
853 $params['selected'] = '';
856 if ( !isset( $params['disable'] ) ||
!is_array( $params['disable'] ) ) {
857 $params['disable'] = [];
860 // Associative array between option-values and option-labels
861 $options = self
::namespaceSelectorOptions( $params );
863 // Convert $options to HTML
865 foreach ( $options as $nsId => $nsName ) {
866 $optionsHtml[] = self
::element(
868 'disabled' => in_array( $nsId, $params['disable'] ),
870 'selected' => $nsId === $params['selected'],
875 if ( !array_key_exists( 'id', $selectAttribs ) ) {
876 $selectAttribs['id'] = 'namespace';
879 if ( !array_key_exists( 'name', $selectAttribs ) ) {
880 $selectAttribs['name'] = 'namespace';
884 if ( isset( $params['label'] ) ) {
885 $ret .= self
::element(
887 'for' => isset( $selectAttribs['id'] ) ?
$selectAttribs['id'] : null,
892 // Wrap options in a <select>
893 $ret .= self
::openElement( 'select', $selectAttribs )
895 . implode( "\n", $optionsHtml )
897 . self
::closeElement( 'select' );
903 * Constructs the opening html-tag with necessary doctypes depending on
906 * @param array $attribs Associative array of miscellaneous extra
907 * attributes, passed to Html::element() of html tag.
908 * @return string Raw HTML
910 public static function htmlHeader( array $attribs = [] ) {
913 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
915 $isXHTML = self
::isXmlMimeType( $wgMimeType );
917 if ( $isXHTML ) { // XHTML5
918 // XML MIME-typed markup should have an xml header.
919 // However a DOCTYPE is not needed.
920 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
922 // Add the standard xmlns
923 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
925 // And support custom namespaces
926 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
927 $attribs["xmlns:$tag"] = $ns;
931 $ret .= "<!DOCTYPE html>\n";
934 if ( $wgHtml5Version ) {
935 $attribs['version'] = $wgHtml5Version;
938 $html = self
::openElement( 'html', $attribs );
950 * Determines if the given MIME type is xml.
952 * @param string $mimetype MIME type
955 public static function isXmlMimeType( $mimetype ) {
956 # http://www.whatwg.org/html/infrastructure.html#xml-mime-type
959 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
960 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
964 * Get HTML for an info box with an icon.
966 * @param string $text Wikitext, get this with wfMessage()->plain()
967 * @param string $icon Path to icon file (used as 'src' attribute)
968 * @param string $alt Alternate text for the icon
969 * @param string $class Additional class name to add to the wrapper div
973 static function infoBox( $text, $icon, $alt, $class = '' ) {
974 $s = self
::openElement( 'div', [ 'class' => "mw-infobox $class" ] );
976 $s .= self
::openElement( 'div', [ 'class' => 'mw-infobox-left' ] ) .
977 self
::element( 'img',
983 self
::closeElement( 'div' );
985 $s .= self
::openElement( 'div', [ 'class' => 'mw-infobox-right' ] ) .
987 self
::closeElement( 'div' );
988 $s .= self
::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
990 $s .= self
::closeElement( 'div' );
992 $s .= self
::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
998 * Generate a srcset attribute value.
1000 * Generates a srcset attribute value from an array mapping pixel densities
1001 * to URLs. A trailing 'x' in pixel density values is optional.
1003 * @note srcset width and height values are not supported.
1005 * @see http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
1009 * Html::srcSet( array(
1010 * '1x' => 'standard.jpeg',
1011 * '1.5x' => 'large.jpeg',
1012 * '3x' => 'extra-large.jpeg',
1014 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1017 * @param string[] $urls
1020 static function srcSet( array $urls ) {
1022 foreach ( $urls as $density => $url ) {
1023 // Cast density to float to strip 'x'.
1024 $candidates[] = $url . ' ' . (float)$density . 'x';
1026 return implode( ", ", $candidates );