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
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 2016-09-19
50 private static $voidElements = [
68 // Boolean attributes, which may have the value omitted entirely. Manually
69 // collected from the HTML5 spec as of 2011-08-12.
70 private static $boolAttribs = [
102 * Modifies a set of attributes meant for button elements
103 * and apply a set of default attributes when $wgUseMediaWikiUIEverywhere enabled.
104 * @param array $attrs HTML attributes in an associative array
105 * @param string[] $modifiers classes to add to the button
106 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
107 * @return array $attrs A modified attribute array
109 public static function buttonAttributes( array $attrs, array $modifiers = [] ) {
110 global $wgUseMediaWikiUIEverywhere;
111 if ( $wgUseMediaWikiUIEverywhere ) {
112 if ( isset( $attrs['class'] ) ) {
113 if ( is_array( $attrs['class'] ) ) {
114 $attrs['class'][] = 'mw-ui-button';
115 $attrs['class'] = array_merge( $attrs['class'], $modifiers );
116 // ensure compatibility with Xml
117 $attrs['class'] = implode( ' ', $attrs['class'] );
119 $attrs['class'] .= ' mw-ui-button ' . implode( ' ', $modifiers );
122 // ensure compatibility with Xml
123 $attrs['class'] = 'mw-ui-button ' . implode( ' ', $modifiers );
130 * Modifies a set of attributes meant for text input elements
131 * and apply a set of default attributes.
132 * Removes size attribute when $wgUseMediaWikiUIEverywhere enabled.
133 * @param array $attrs An attribute array.
134 * @return array $attrs A modified attribute array
136 public static function getTextInputAttributes( array $attrs ) {
137 global $wgUseMediaWikiUIEverywhere;
138 if ( $wgUseMediaWikiUIEverywhere ) {
139 if ( isset( $attrs['class'] ) ) {
140 if ( is_array( $attrs['class'] ) ) {
141 $attrs['class'][] = 'mw-ui-input';
143 $attrs['class'] .= ' mw-ui-input';
146 $attrs['class'] = 'mw-ui-input';
153 * Returns an HTML link element in a string styled as a button
154 * (when $wgUseMediaWikiUIEverywhere is enabled).
156 * @param string $contents The raw HTML contents of the element: *not*
158 * @param array $attrs Associative array of attributes, e.g., [
159 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
160 * further documentation.
161 * @param string[] $modifiers classes to add to the button
162 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
163 * @return string Raw HTML
165 public static function linkButton( $contents, array $attrs, array $modifiers = [] ) {
166 return self
::element( 'a',
167 self
::buttonAttributes( $attrs, $modifiers ),
173 * Returns an HTML link element in a string styled as a button
174 * (when $wgUseMediaWikiUIEverywhere is enabled).
176 * @param string $contents The raw HTML contents of the element: *not*
178 * @param array $attrs Associative array of attributes, e.g., [
179 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
180 * further documentation.
181 * @param string[] $modifiers classes to add to the button
182 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
183 * @return string Raw HTML
185 public static function submitButton( $contents, array $attrs, array $modifiers = [] ) {
186 $attrs['type'] = 'submit';
187 $attrs['value'] = $contents;
188 return self
::element( 'input', self
::buttonAttributes( $attrs, $modifiers ) );
192 * Returns an HTML element in a string. The major advantage here over
193 * manually typing out the HTML is that it will escape all attribute
196 * This is quite similar to Xml::tags(), but it implements some useful
197 * HTML-specific logic. For instance, there is no $allowShortTag
198 * parameter: the closing tag is magically omitted if $element has an empty
201 * @param string $element The element's name, e.g., 'a'
202 * @param array $attribs Associative array of attributes, e.g., [
203 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
204 * further documentation.
205 * @param string $contents The raw HTML contents of the element: *not*
207 * @return string Raw HTML
209 public static function rawElement( $element, $attribs = [], $contents = '' ) {
210 $start = self
::openElement( $element, $attribs );
211 if ( in_array( $element, self
::$voidElements ) ) {
213 return substr( $start, 0, -1 ) . '/>';
215 return "$start$contents" . self
::closeElement( $element );
220 * Identical to rawElement(), but HTML-escapes $contents (like
223 * @param string $element
224 * @param array $attribs
225 * @param string $contents
229 public static function element( $element, $attribs = [], $contents = '' ) {
230 return self
::rawElement( $element, $attribs, strtr( $contents, [
231 // There's no point in escaping quotes, >, etc. in the contents of
239 * Identical to rawElement(), but has no third parameter and omits the end
240 * tag (and the self-closing '/' in XML mode for empty elements).
242 * @param string $element
243 * @param array $attribs
247 public static function openElement( $element, $attribs = [] ) {
248 $attribs = (array)$attribs;
249 // This is not required in HTML5, but let's do it anyway, for
250 // consistency and better compression.
251 $element = strtolower( $element );
253 // Remove invalid input types
254 if ( $element == 'input' ) {
282 if ( isset( $attribs['type'] ) && !in_array( $attribs['type'], $validTypes ) ) {
283 unset( $attribs['type'] );
287 // According to standard the default type for <button> elements is "submit".
288 // Depending on compatibility mode IE might use "button", instead.
289 // We enforce the standard "submit".
290 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
291 $attribs['type'] = 'submit';
294 return "<$element" . self
::expandAttributes(
295 self
::dropDefaults( $element, $attribs ) ) . '>';
299 * Returns "</$element>"
302 * @param string $element Name of the element, e.g., 'a'
303 * @return string A closing tag
305 public static function closeElement( $element ) {
306 $element = strtolower( $element );
308 return "</$element>";
312 * Given an element name and an associative array of element attributes,
313 * return an array that is functionally identical to the input array, but
314 * possibly smaller. In particular, attributes might be stripped if they
315 * are given their default values.
317 * This method is not guaranteed to remove all redundant attributes, only
318 * some common ones and some others selected arbitrarily at random. It
319 * only guarantees that the output array should be functionally identical
320 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
322 * @param string $element Name of the element, e.g., 'a'
323 * @param array $attribs Associative array of attributes, e.g., [
324 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
325 * further documentation.
326 * @return array An array of attributes functionally identical to $attribs
328 private static function dropDefaults( $element, array $attribs ) {
329 // Whenever altering this array, please provide a covering test case
330 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
331 static $attribDefaults = [
332 'area' => [ 'shape' => 'rect' ],
334 'formaction' => 'GET',
335 'formenctype' => 'application/x-www-form-urlencoded',
343 'autocomplete' => 'on',
344 'enctype' => 'application/x-www-form-urlencoded',
347 'formaction' => 'GET',
350 'keygen' => [ 'keytype' => 'rsa' ],
351 'link' => [ 'media' => 'all' ],
352 'menu' => [ 'type' => 'list' ],
353 'script' => [ 'type' => 'text/javascript' ],
356 'type' => 'text/css',
358 'textarea' => [ 'wrap' => 'soft' ],
361 $element = strtolower( $element );
363 foreach ( $attribs as $attrib => $value ) {
364 $lcattrib = strtolower( $attrib );
365 if ( is_array( $value ) ) {
366 $value = implode( ' ', $value );
368 $value = strval( $value );
371 // Simple checks using $attribDefaults
372 if ( isset( $attribDefaults[$element][$lcattrib] )
373 && $attribDefaults[$element][$lcattrib] == $value
375 unset( $attribs[$attrib] );
378 if ( $lcattrib == 'class' && $value == '' ) {
379 unset( $attribs[$attrib] );
383 // More subtle checks
384 if ( $element === 'link'
385 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
387 unset( $attribs['type'] );
389 if ( $element === 'input' ) {
390 $type = isset( $attribs['type'] ) ?
$attribs['type'] : null;
391 $value = isset( $attribs['value'] ) ?
$attribs['value'] : null;
392 if ( $type === 'checkbox' ||
$type === 'radio' ) {
393 // The default value for checkboxes and radio buttons is 'on'
394 // not ''. By stripping value="" we break radio boxes that
395 // actually wants empty values.
396 if ( $value === 'on' ) {
397 unset( $attribs['value'] );
399 } elseif ( $type === 'submit' ) {
400 // The default value for submit appears to be "Submit" but
401 // let's not bother stripping out localized text that matches
404 // The default value for nearly every other field type is ''
405 // The 'range' and 'color' types use different defaults but
406 // stripping a value="" does not hurt them.
407 if ( $value === '' ) {
408 unset( $attribs['value'] );
412 if ( $element === 'select' && isset( $attribs['size'] ) ) {
413 if ( in_array( 'multiple', $attribs )
414 ||
( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
417 if ( strval( $attribs['size'] ) == '4' ) {
418 unset( $attribs['size'] );
422 if ( strval( $attribs['size'] ) == '1' ) {
423 unset( $attribs['size'] );
432 * Given an associative array of element attributes, generate a string
433 * to stick after the element name in HTML output. Like [ 'href' =>
434 * 'https://www.mediawiki.org/' ] becomes something like
435 * ' href="https://www.mediawiki.org"'. Again, this is like
436 * Xml::expandAttributes(), but it implements some HTML-specific logic.
438 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
439 * values are allowed as well, which will automagically be normalized
440 * and converted to a space-separated string. In addition to a numerical
441 * array, the attribute value may also be an associative array. See the
442 * example below for how that works.
444 * @par Numerical array
446 * Html::element( 'em', [
447 * 'class' => [ 'foo', 'bar' ]
449 * // gives '<em class="foo bar"></em>'
452 * @par Associative array
454 * Html::element( 'em', [
455 * 'class' => [ 'foo', 'bar', 'foo' => false, 'quux' => true ]
457 * // gives '<em class="bar quux"></em>'
460 * @param array $attribs Associative array of attributes, e.g., [
461 * 'href' => 'https://www.mediawiki.org/' ]. Values will be HTML-escaped.
462 * A value of false means to omit the attribute. For boolean attributes,
463 * you can omit the key, e.g., [ 'checked' ] instead of
464 * [ 'checked' => 'checked' ] or such.
466 * @throws MWException If an attribute that doesn't allow lists is set to an array
467 * @return string HTML fragment that goes between element name and '>'
468 * (starting with a space if at least one attribute is output)
470 public static function expandAttributes( array $attribs ) {
472 foreach ( $attribs as $key => $value ) {
473 // Support intuitive [ 'checked' => true/false ] form
474 if ( $value === false ||
is_null( $value ) ) {
478 // For boolean attributes, support [ 'foo' ] instead of
479 // requiring [ 'foo' => 'meaningless' ].
480 if ( is_int( $key ) && in_array( strtolower( $value ), self
::$boolAttribs ) ) {
484 // Not technically required in HTML5 but we'd like consistency
485 // and better compression anyway.
486 $key = strtolower( $key );
488 // https://www.w3.org/TR/html401/index/attributes.html ("space-separated")
489 // https://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
490 $spaceSeparatedListAttributes = [
491 'class', // html4, html5
492 'accesskey', // as of html5, multiple space-separated values allowed
493 // html4-spec doesn't document rel= as space-separated
494 // but has been used like that and is now documented as such
495 // in the html5-spec.
499 // Specific features for attributes that allow a list of space-separated values
500 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
501 // Apply some normalization and remove duplicates
503 // Convert into correct array. Array can contain space-separated
504 // values. Implode/explode to get those into the main array as well.
505 if ( is_array( $value ) ) {
506 // If input wasn't an array, we can skip this step
508 foreach ( $value as $k => $v ) {
509 if ( is_string( $v ) ) {
510 // String values should be normal `array( 'foo' )`
512 if ( !isset( $value[$v] ) ) {
513 // As a special case don't set 'foo' if a
514 // separate 'foo' => true/false exists in the array
515 // keys should be authoritative
519 // If the value is truthy but not a string this is likely
520 // an [ 'foo' => true ], falsy values don't add strings
524 $value = implode( ' ', $newValue );
526 $value = explode( ' ', $value );
528 // Normalize spacing by fixing up cases where people used
529 // more than 1 space and/or a trailing/leading space
530 $value = array_diff( $value, [ '', ' ' ] );
532 // Remove duplicates and create the string
533 $value = implode( ' ', array_unique( $value ) );
534 } elseif ( is_array( $value ) ) {
535 throw new MWException( "HTML attribute $key can not contain a list of values" );
540 if ( in_array( $key, self
::$boolAttribs ) ) {
541 $ret .= " $key=\"\"";
543 // Apparently we need to entity-encode \n, \r, \t, although the
544 // spec doesn't mention that. Since we're doing strtr() anyway,
545 // we may as well not call htmlspecialchars().
546 // @todo FIXME: Verify that we actually need to
547 // escape \n\r\t here, and explain why, exactly.
548 // We could call Sanitizer::encodeAttribute() for this, but we
549 // don't because we're stubborn and like our marginal savings on
550 // byte size from not having to encode unnecessary quotes.
551 // The only difference between this transform and the one by
552 // Sanitizer::encodeAttribute() is ' is not encoded.
557 // '<' allegedly allowed per spec
558 // but breaks some tools if not escaped.
564 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
571 * Output a "<script>" tag with the given contents.
573 * @todo do some useful escaping as well, like if $contents contains
574 * literal "</script>" or (for XML) literal "]]>".
576 * @param string $contents JavaScript
577 * @return string Raw HTML
579 public static function inlineScript( $contents ) {
582 if ( preg_match( '/[<&]/', $contents ) ) {
583 $contents = "/*<![CDATA[*/$contents/*]]>*/";
586 return self
::rawElement( 'script', $attrs, $contents );
590 * Output a "<script>" tag linking to the given URL, e.g.,
591 * "<script src=foo.js></script>".
594 * @return string Raw HTML
596 public static function linkedScript( $url ) {
597 $attrs = [ 'src' => $url ];
599 return self
::element( 'script', $attrs );
603 * Output a "<style>" tag with the given contents for the given media type
604 * (if any). TODO: do some useful escaping as well, like if $contents
605 * contains literal "</style>" (admittedly unlikely).
607 * @param string $contents CSS
608 * @param string $media A media type string, like 'screen'
609 * @return string Raw HTML
611 public static function inlineStyle( $contents, $media = 'all' ) {
612 // Don't escape '>' since that is used
613 // as direct child selector.
614 // Remember, in css, there is no "x" for hexadecimal escapes, and
615 // the space immediately after an escape sequence is swallowed.
616 $contents = strtr( $contents, [
618 // CDATA end tag for good measure, but the main security
619 // is from escaping the '<'.
620 ']]>' => '\5D\5D\3E '
623 if ( preg_match( '/[<&]/', $contents ) ) {
624 $contents = "/*<![CDATA[*/$contents/*]]>*/";
627 return self
::rawElement( 'style', [
633 * Output a "<link rel=stylesheet>" linking to the given URL for the given
634 * media type (if any).
637 * @param string $media A media type string, like 'screen'
638 * @return string Raw HTML
640 public static function linkedStyle( $url, $media = 'all' ) {
641 return self
::element( 'link', [
642 'rel' => 'stylesheet',
649 * Convenience function to produce an "<input>" element. This supports the
650 * new HTML5 input types and attributes.
652 * @param string $name Name attribute
653 * @param string $value Value attribute
654 * @param string $type Type attribute
655 * @param array $attribs Associative array of miscellaneous extra
656 * attributes, passed to Html::element()
657 * @return string Raw HTML
659 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
660 $attribs['type'] = $type;
661 $attribs['value'] = $value;
662 $attribs['name'] = $name;
663 if ( in_array( $type, [ 'text', 'search', 'email', 'password', 'number' ] ) ) {
664 $attribs = self
::getTextInputAttributes( $attribs );
666 if ( in_array( $type, [ 'button', 'reset', 'submit' ] ) ) {
667 $attribs = self
::buttonAttributes( $attribs );
669 return self
::element( 'input', $attribs );
673 * Convenience function to produce a checkbox (input element with type=checkbox)
675 * @param string $name Name attribute
676 * @param bool $checked Whether the checkbox is checked or not
677 * @param array $attribs Array of additional attributes
678 * @return string Raw HTML
680 public static function check( $name, $checked = false, array $attribs = [] ) {
681 if ( isset( $attribs['value'] ) ) {
682 $value = $attribs['value'];
683 unset( $attribs['value'] );
689 $attribs[] = 'checked';
692 return self
::input( $name, $value, 'checkbox', $attribs );
696 * Convenience function to produce a radio button (input element with type=radio)
698 * @param string $name Name attribute
699 * @param bool $checked Whether the radio button is checked or not
700 * @param array $attribs Array of additional attributes
701 * @return string Raw HTML
703 public static function radio( $name, $checked = false, array $attribs = [] ) {
704 if ( isset( $attribs['value'] ) ) {
705 $value = $attribs['value'];
706 unset( $attribs['value'] );
712 $attribs[] = 'checked';
715 return self
::input( $name, $value, 'radio', $attribs );
719 * Convenience function for generating a label for inputs.
721 * @param string $label Contents of the label
722 * @param string $id ID of the element being labeled
723 * @param array $attribs Additional attributes
724 * @return string Raw HTML
726 public static function label( $label, $id, array $attribs = [] ) {
730 return self
::element( 'label', $attribs, $label );
734 * Convenience function to produce an input element with type=hidden
736 * @param string $name Name attribute
737 * @param string $value Value attribute
738 * @param array $attribs Associative array of miscellaneous extra
739 * attributes, passed to Html::element()
740 * @return string Raw HTML
742 public static function hidden( $name, $value, array $attribs = [] ) {
743 return self
::input( $name, $value, 'hidden', $attribs );
747 * Convenience function to produce a <textarea> element.
749 * This supports leaving out the cols= and rows= which Xml requires and are
750 * required by HTML4/XHTML but not required by HTML5.
752 * @param string $name Name attribute
753 * @param string $value Value attribute
754 * @param array $attribs Associative array of miscellaneous extra
755 * attributes, passed to Html::element()
756 * @return string Raw HTML
758 public static function textarea( $name, $value = '', array $attribs = [] ) {
759 $attribs['name'] = $name;
761 if ( substr( $value, 0, 1 ) == "\n" ) {
762 // Workaround for bug 12130: browsers eat the initial newline
763 // assuming that it's just for show, but they do keep the later
764 // newlines, which we may want to preserve during editing.
765 // Prepending a single newline
766 $spacedValue = "\n" . $value;
768 $spacedValue = $value;
770 return self
::element( 'textarea', self
::getTextInputAttributes( $attribs ), $spacedValue );
774 * Helper for Html::namespaceSelector().
775 * @param array $params See Html::namespaceSelector()
778 public static function namespaceSelectorOptions( array $params = [] ) {
783 if ( !isset( $params['exclude'] ) ||
!is_array( $params['exclude'] ) ) {
784 $params['exclude'] = [];
787 if ( isset( $params['all'] ) ) {
788 // add an option that would let the user select all namespaces.
789 // Value is provided by user, the name shown is localized for the user.
790 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
792 // Add all namespaces as options (in the content language)
793 $options +
= $wgContLang->getFormattedNamespaces();
796 // Filter out namespaces below 0 and massage labels
797 foreach ( $options as $nsId => $nsName ) {
798 if ( $nsId < NS_MAIN ||
in_array( $nsId, $params['exclude'] ) ) {
801 if ( $nsId === NS_MAIN
) {
802 // For other namespaces use the namespace prefix as label, but for
803 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
804 $nsName = wfMessage( 'blanknamespace' )->text();
805 } elseif ( is_int( $nsId ) ) {
806 $nsName = $wgContLang->convertNamespace( $nsId );
808 $optionsOut[$nsId] = $nsName;
815 * Build a drop-down box for selecting a namespace
817 * @param array $params Params to set.
818 * - selected: [optional] Id of namespace which should be pre-selected
819 * - all: [optional] Value of item for "all namespaces". If null or unset,
820 * no "<option>" is generated to select all namespaces.
821 * - label: text for label to add before the field.
822 * - exclude: [optional] Array of namespace ids to exclude.
823 * - disable: [optional] Array of namespace ids for which the option should
824 * be disabled in the selector.
825 * @param array $selectAttribs HTML attributes for the generated select element.
826 * - id: [optional], default: 'namespace'.
827 * - name: [optional], default: 'namespace'.
828 * @return string HTML code to select a namespace.
830 public static function namespaceSelector( array $params = [],
831 array $selectAttribs = []
833 ksort( $selectAttribs );
835 // Is a namespace selected?
836 if ( isset( $params['selected'] ) ) {
837 // If string only contains digits, convert to clean int. Selected could also
838 // be "all" or "" etc. which needs to be left untouched.
839 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
840 // and returns false for already clean ints. Use regex instead..
841 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
842 $params['selected'] = intval( $params['selected'] );
844 // else: leaves it untouched for later processing
846 $params['selected'] = '';
849 if ( !isset( $params['disable'] ) ||
!is_array( $params['disable'] ) ) {
850 $params['disable'] = [];
853 // Associative array between option-values and option-labels
854 $options = self
::namespaceSelectorOptions( $params );
856 // Convert $options to HTML
858 foreach ( $options as $nsId => $nsName ) {
859 $optionsHtml[] = self
::element(
861 'disabled' => in_array( $nsId, $params['disable'] ),
863 'selected' => $nsId === $params['selected'],
868 if ( !array_key_exists( 'id', $selectAttribs ) ) {
869 $selectAttribs['id'] = 'namespace';
872 if ( !array_key_exists( 'name', $selectAttribs ) ) {
873 $selectAttribs['name'] = 'namespace';
877 if ( isset( $params['label'] ) ) {
878 $ret .= self
::element(
880 'for' => isset( $selectAttribs['id'] ) ?
$selectAttribs['id'] : null,
885 // Wrap options in a <select>
886 $ret .= self
::openElement( 'select', $selectAttribs )
888 . implode( "\n", $optionsHtml )
890 . self
::closeElement( 'select' );
896 * Constructs the opening html-tag with necessary doctypes depending on
899 * @param array $attribs Associative array of miscellaneous extra
900 * attributes, passed to Html::element() of html tag.
901 * @return string Raw HTML
903 public static function htmlHeader( array $attribs = [] ) {
906 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
908 $isXHTML = self
::isXmlMimeType( $wgMimeType );
910 if ( $isXHTML ) { // XHTML5
911 // XML MIME-typed markup should have an xml header.
912 // However a DOCTYPE is not needed.
913 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
915 // Add the standard xmlns
916 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
918 // And support custom namespaces
919 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
920 $attribs["xmlns:$tag"] = $ns;
924 $ret .= "<!DOCTYPE html>\n";
927 if ( $wgHtml5Version ) {
928 $attribs['version'] = $wgHtml5Version;
931 $ret .= self
::openElement( 'html', $attribs );
937 * Determines if the given MIME type is xml.
939 * @param string $mimetype MIME type
942 public static function isXmlMimeType( $mimetype ) {
943 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
946 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
947 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
951 * Get HTML for an info box with an icon.
953 * @param string $text Wikitext, get this with wfMessage()->plain()
954 * @param string $icon Path to icon file (used as 'src' attribute)
955 * @param string $alt Alternate text for the icon
956 * @param string $class Additional class name to add to the wrapper div
960 static function infoBox( $text, $icon, $alt, $class = '' ) {
961 $s = self
::openElement( 'div', [ 'class' => "mw-infobox $class" ] );
963 $s .= self
::openElement( 'div', [ 'class' => 'mw-infobox-left' ] ) .
964 self
::element( 'img',
970 self
::closeElement( 'div' );
972 $s .= self
::openElement( 'div', [ 'class' => 'mw-infobox-right' ] ) .
974 self
::closeElement( 'div' );
975 $s .= self
::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
977 $s .= self
::closeElement( 'div' );
979 $s .= self
::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
985 * Generate a srcset attribute value.
987 * Generates a srcset attribute value from an array mapping pixel densities
988 * to URLs. A trailing 'x' in pixel density values is optional.
990 * @note srcset width and height values are not supported.
992 * @see https://html.spec.whatwg.org/#attr-img-srcset
997 * '1x' => 'standard.jpeg',
998 * '1.5x' => 'large.jpeg',
999 * '3x' => 'extra-large.jpeg',
1001 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1004 * @param string[] $urls
1007 static function srcSet( array $urls ) {
1009 foreach ( $urls as $density => $url ) {
1010 // Cast density to float to strip 'x', then back to string to serve
1012 $density = (string)(float)$density;
1013 $candidates[$density] = $url;
1016 // Remove duplicates that are the same as a smaller value
1017 ksort( $candidates, SORT_NUMERIC
);
1018 $candidates = array_unique( $candidates );
1020 // Append density info to the url
1021 foreach ( $candidates as $density => $url ) {
1022 $candidates[$density] = $url . ' ' . $density . 'x';
1025 return implode( ", ", $candidates );