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
25 use MediaWiki\MediaWikiServices
;
28 * This class is a collection of static functions that serve two purposes:
30 * 1) Implement any algorithms specified by HTML5, or other HTML
31 * specifications, in a convenient and self-contained way.
33 * 2) Allow HTML elements to be conveniently and safely generated, like the
34 * current Xml class but a) less confused (Xml supports HTML-specific things,
35 * but only sometimes!) and b) not necessarily confined to XML-compatible
38 * There are two important configuration options this class uses:
40 * $wgMimeType: If this is set to an xml MIME type then output should be
43 * This class is meant to be confined to utility functions that are called from
44 * trusted code paths. It does not do enforcement of policy like not allowing
50 // List of void elements from HTML5, section 8.1.2 as of 2016-09-19
51 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., [
160 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
161 * further documentation.
162 * @param string[] $modifiers classes to add to the button
163 * @see https://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., [
180 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
181 * further documentation.
182 * @param string[] $modifiers classes to add to the button
183 * @see https://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., [
204 * 'href' => 'https://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 Name of the element, e.g., 'a'
225 * @param array $attribs Associative array of attributes, e.g., [
226 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
227 * further documentation.
228 * @param string $contents
232 public static function element( $element, $attribs = [], $contents = '' ) {
233 return self
::rawElement( $element, $attribs, strtr( $contents, [
234 // There's no point in escaping quotes, >, etc. in the contents of
242 * Identical to rawElement(), but has no third parameter and omits the end
243 * tag (and the self-closing '/' in XML mode for empty elements).
245 * @param string $element Name of the element, e.g., 'a'
246 * @param array $attribs Associative array of attributes, e.g., [
247 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
248 * further documentation.
252 public static function openElement( $element, $attribs = [] ) {
253 $attribs = (array)$attribs;
254 // This is not required in HTML5, but let's do it anyway, for
255 // consistency and better compression.
256 $element = strtolower( $element );
258 // Remove invalid input types
259 if ( $element == 'input' ) {
287 if ( isset( $attribs['type'] ) && !in_array( $attribs['type'], $validTypes ) ) {
288 unset( $attribs['type'] );
292 // According to standard the default type for <button> elements is "submit".
293 // Depending on compatibility mode IE might use "button", instead.
294 // We enforce the standard "submit".
295 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
296 $attribs['type'] = 'submit';
299 return "<$element" . self
::expandAttributes(
300 self
::dropDefaults( $element, $attribs ) ) . '>';
304 * Returns "</$element>"
307 * @param string $element Name of the element, e.g., 'a'
308 * @return string A closing tag
310 public static function closeElement( $element ) {
311 $element = strtolower( $element );
313 return "</$element>";
317 * Given an element name and an associative array of element attributes,
318 * return an array that is functionally identical to the input array, but
319 * possibly smaller. In particular, attributes might be stripped if they
320 * are given their default values.
322 * This method is not guaranteed to remove all redundant attributes, only
323 * some common ones and some others selected arbitrarily at random. It
324 * only guarantees that the output array should be functionally identical
325 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
327 * @param string $element Name of the element, e.g., 'a'
328 * @param array $attribs Associative array of attributes, e.g., [
329 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
330 * further documentation.
331 * @return array An array of attributes functionally identical to $attribs
333 private static function dropDefaults( $element, array $attribs ) {
334 // Whenever altering this array, please provide a covering test case
335 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
336 static $attribDefaults = [
337 'area' => [ 'shape' => 'rect' ],
339 'formaction' => 'GET',
340 'formenctype' => 'application/x-www-form-urlencoded',
348 'autocomplete' => 'on',
349 'enctype' => 'application/x-www-form-urlencoded',
352 'formaction' => 'GET',
355 'keygen' => [ 'keytype' => 'rsa' ],
356 'link' => [ 'media' => 'all' ],
357 'menu' => [ 'type' => 'list' ],
358 'script' => [ 'type' => 'text/javascript' ],
361 'type' => 'text/css',
363 'textarea' => [ 'wrap' => 'soft' ],
366 $element = strtolower( $element );
368 foreach ( $attribs as $attrib => $value ) {
369 $lcattrib = strtolower( $attrib );
370 if ( is_array( $value ) ) {
371 $value = implode( ' ', $value );
373 $value = strval( $value );
376 // Simple checks using $attribDefaults
377 if ( isset( $attribDefaults[$element][$lcattrib] )
378 && $attribDefaults[$element][$lcattrib] == $value
380 unset( $attribs[$attrib] );
383 if ( $lcattrib == 'class' && $value == '' ) {
384 unset( $attribs[$attrib] );
388 // More subtle checks
389 if ( $element === 'link'
390 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
392 unset( $attribs['type'] );
394 if ( $element === 'input' ) {
395 $type = $attribs['type'] ??
null;
396 $value = $attribs['value'] ??
null;
397 if ( $type === 'checkbox' ||
$type === 'radio' ) {
398 // The default value for checkboxes and radio buttons is 'on'
399 // not ''. By stripping value="" we break radio boxes that
400 // actually wants empty values.
401 if ( $value === 'on' ) {
402 unset( $attribs['value'] );
404 } elseif ( $type === 'submit' ) {
405 // The default value for submit appears to be "Submit" but
406 // let's not bother stripping out localized text that matches
409 // The default value for nearly every other field type is ''
410 // The 'range' and 'color' types use different defaults but
411 // stripping a value="" does not hurt them.
412 if ( $value === '' ) {
413 unset( $attribs['value'] );
417 if ( $element === 'select' && isset( $attribs['size'] ) ) {
418 if ( in_array( 'multiple', $attribs )
419 ||
( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
422 if ( strval( $attribs['size'] ) == '4' ) {
423 unset( $attribs['size'] );
427 if ( strval( $attribs['size'] ) == '1' ) {
428 unset( $attribs['size'] );
437 * Given an associative array of element attributes, generate a string
438 * to stick after the element name in HTML output. Like [ 'href' =>
439 * 'https://www.mediawiki.org/' ] becomes something like
440 * ' href="https://www.mediawiki.org"'. Again, this is like
441 * Xml::expandAttributes(), but it implements some HTML-specific logic.
443 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
444 * values are allowed as well, which will automagically be normalized
445 * and converted to a space-separated string. In addition to a numerical
446 * array, the attribute value may also be an associative array. See the
447 * example below for how that works.
449 * @par Numerical array
451 * Html::element( 'em', [
452 * 'class' => [ 'foo', 'bar' ]
454 * // gives '<em class="foo bar"></em>'
457 * @par Associative array
459 * Html::element( 'em', [
460 * 'class' => [ 'foo', 'bar', 'foo' => false, 'quux' => true ]
462 * // gives '<em class="bar quux"></em>'
465 * @param array $attribs Associative array of attributes, e.g., [
466 * 'href' => 'https://www.mediawiki.org/' ]. Values will be HTML-escaped.
467 * A value of false or null means to omit the attribute. For boolean attributes,
468 * you can omit the key, e.g., [ 'checked' ] instead of
469 * [ 'checked' => 'checked' ] or such.
471 * @throws MWException If an attribute that doesn't allow lists is set to an array
472 * @return string HTML fragment that goes between element name and '>'
473 * (starting with a space if at least one attribute is output)
475 public static function expandAttributes( array $attribs ) {
477 foreach ( $attribs as $key => $value ) {
478 // Support intuitive [ 'checked' => true/false ] form
479 if ( $value === false ||
is_null( $value ) ) {
483 // For boolean attributes, support [ 'foo' ] instead of
484 // requiring [ 'foo' => 'meaningless' ].
485 if ( is_int( $key ) && in_array( strtolower( $value ), self
::$boolAttribs ) ) {
489 // Not technically required in HTML5 but we'd like consistency
490 // and better compression anyway.
491 $key = strtolower( $key );
493 // https://www.w3.org/TR/html401/index/attributes.html ("space-separated")
494 // https://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
495 $spaceSeparatedListAttributes = [
496 'class', // html4, html5
497 'accesskey', // as of html5, multiple space-separated values allowed
498 // html4-spec doesn't document rel= as space-separated
499 // but has been used like that and is now documented as such
500 // in the html5-spec.
504 // Specific features for attributes that allow a list of space-separated values
505 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
506 // Apply some normalization and remove duplicates
508 // Convert into correct array. Array can contain space-separated
509 // values. Implode/explode to get those into the main array as well.
510 if ( is_array( $value ) ) {
511 // If input wasn't an array, we can skip this step
513 foreach ( $value as $k => $v ) {
514 if ( is_string( $v ) ) {
515 // String values should be normal `array( 'foo' )`
517 if ( !isset( $value[$v] ) ) {
518 // As a special case don't set 'foo' if a
519 // separate 'foo' => true/false exists in the array
520 // keys should be authoritative
524 // If the value is truthy but not a string this is likely
525 // an [ 'foo' => true ], falsy values don't add strings
529 $value = implode( ' ', $newValue );
531 $value = explode( ' ', $value );
533 // Normalize spacing by fixing up cases where people used
534 // more than 1 space and/or a trailing/leading space
535 $value = array_diff( $value, [ '', ' ' ] );
537 // Remove duplicates and create the string
538 $value = implode( ' ', array_unique( $value ) );
539 } elseif ( is_array( $value ) ) {
540 throw new MWException( "HTML attribute $key can not contain a list of values" );
545 if ( in_array( $key, self
::$boolAttribs ) ) {
546 $ret .= " $key=\"\"";
548 $ret .= " $key=$quote" . Sanitizer
::encodeAttribute( $value ) . $quote;
555 * Output a "<script>" tag with the given contents.
557 * @todo do some useful escaping as well, like if $contents contains
558 * literal "</script>" or (for XML) literal "]]>".
560 * @param string $contents JavaScript
561 * @param string|null $nonce Nonce for CSP header, from OutputPage::getCSPNonce()
562 * @return string Raw HTML
564 public static function inlineScript( $contents, $nonce = null ) {
566 if ( $nonce !== null ) {
567 $attrs['nonce'] = $nonce;
569 if ( ContentSecurityPolicy
::isNonceRequired( RequestContext
::getMain()->getConfig() ) ) {
570 wfWarn( "no nonce set on script. CSP will break it" );
574 if ( preg_match( '/[<&]/', $contents ) ) {
575 $contents = "/*<![CDATA[*/$contents/*]]>*/";
578 return self
::rawElement( 'script', $attrs, $contents );
582 * Output a "<script>" tag linking to the given URL, e.g.,
583 * "<script src=foo.js></script>".
586 * @param string|null $nonce Nonce for CSP header, from OutputPage::getCSPNonce()
587 * @return string Raw HTML
589 public static function linkedScript( $url, $nonce = null ) {
590 $attrs = [ 'src' => $url ];
591 if ( $nonce !== null ) {
592 $attrs['nonce'] = $nonce;
594 if ( ContentSecurityPolicy
::isNonceRequired( RequestContext
::getMain()->getConfig() ) ) {
595 wfWarn( "no nonce set on script. CSP will break it" );
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 * @param array $attribs (since 1.31) Associative array of attributes, e.g., [
610 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
611 * further documentation.
612 * @return string Raw HTML
614 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
615 // Don't escape '>' since that is used
616 // as direct child selector.
617 // Remember, in css, there is no "x" for hexadecimal escapes, and
618 // the space immediately after an escape sequence is swallowed.
619 $contents = strtr( $contents, [
621 // CDATA end tag for good measure, but the main security
622 // is from escaping the '<'.
623 ']]>' => '\5D\5D\3E '
626 if ( preg_match( '/[<&]/', $contents ) ) {
627 $contents = "/*<![CDATA[*/$contents/*]]>*/";
630 return self
::rawElement( 'style', [
632 ] +
$attribs, $contents );
636 * Output a "<link rel=stylesheet>" linking to the given URL for the given
637 * media type (if any).
640 * @param string $media A media type string, like 'screen'
641 * @return string Raw HTML
643 public static function linkedStyle( $url, $media = 'all' ) {
644 return self
::element( 'link', [
645 'rel' => 'stylesheet',
652 * Convenience function to produce an "<input>" element. This supports the
653 * new HTML5 input types and attributes.
655 * @param string $name Name attribute
656 * @param string $value Value attribute
657 * @param string $type Type attribute
658 * @param array $attribs Associative array of miscellaneous extra
659 * attributes, passed to Html::element()
660 * @return string Raw HTML
662 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
663 $attribs['type'] = $type;
664 $attribs['value'] = $value;
665 $attribs['name'] = $name;
666 if ( in_array( $type, [ 'text', 'search', 'email', 'password', 'number' ] ) ) {
667 $attribs = self
::getTextInputAttributes( $attribs );
669 if ( in_array( $type, [ 'button', 'reset', 'submit' ] ) ) {
670 $attribs = self
::buttonAttributes( $attribs );
672 return self
::element( 'input', $attribs );
676 * Convenience function to produce a checkbox (input element with type=checkbox)
678 * @param string $name Name attribute
679 * @param bool $checked Whether the checkbox is checked or not
680 * @param array $attribs Array of additional attributes
681 * @return string Raw HTML
683 public static function check( $name, $checked = false, array $attribs = [] ) {
684 if ( isset( $attribs['value'] ) ) {
685 $value = $attribs['value'];
686 unset( $attribs['value'] );
692 $attribs[] = 'checked';
695 return self
::input( $name, $value, 'checkbox', $attribs );
699 * Return the HTML for a message box.
701 * @param string $html of contents of box
702 * @param string $className corresponding to box
703 * @param string $heading (optional)
704 * @return string of HTML representing a box.
706 private static function messageBox( $html, $className, $heading = '' ) {
708 $html = self
::element( 'h2', [], $heading ) . $html;
710 return self
::rawElement( 'div', [ 'class' => $className ], $html );
714 * Return a warning box.
716 * @param string $html of contents of box
717 * @return string of HTML representing a warning box.
719 public static function warningBox( $html ) {
720 return self
::messageBox( $html, 'warningbox' );
724 * Return an error box.
726 * @param string $html of contents of error box
727 * @param string $heading (optional)
728 * @return string of HTML representing an error box.
730 public static function errorBox( $html, $heading = '' ) {
731 return self
::messageBox( $html, 'errorbox', $heading );
735 * Return a success box.
737 * @param string $html of contents of box
738 * @return string of HTML representing a success box.
740 public static function successBox( $html ) {
741 return self
::messageBox( $html, 'successbox' );
745 * Convenience function to produce a radio button (input element with type=radio)
747 * @param string $name Name attribute
748 * @param bool $checked Whether the radio button is checked or not
749 * @param array $attribs Array of additional attributes
750 * @return string Raw HTML
752 public static function radio( $name, $checked = false, array $attribs = [] ) {
753 if ( isset( $attribs['value'] ) ) {
754 $value = $attribs['value'];
755 unset( $attribs['value'] );
761 $attribs[] = 'checked';
764 return self
::input( $name, $value, 'radio', $attribs );
768 * Convenience function for generating a label for inputs.
770 * @param string $label Contents of the label
771 * @param string $id ID of the element being labeled
772 * @param array $attribs Additional attributes
773 * @return string Raw HTML
775 public static function label( $label, $id, array $attribs = [] ) {
779 return self
::element( 'label', $attribs, $label );
783 * Convenience function to produce an input element with type=hidden
785 * @param string $name Name attribute
786 * @param string $value Value attribute
787 * @param array $attribs Associative array of miscellaneous extra
788 * attributes, passed to Html::element()
789 * @return string Raw HTML
791 public static function hidden( $name, $value, array $attribs = [] ) {
792 return self
::input( $name, $value, 'hidden', $attribs );
796 * Convenience function to produce a <textarea> element.
798 * This supports leaving out the cols= and rows= which Xml requires and are
799 * required by HTML4/XHTML but not required by HTML5.
801 * @param string $name Name attribute
802 * @param string $value Value attribute
803 * @param array $attribs Associative array of miscellaneous extra
804 * attributes, passed to Html::element()
805 * @return string Raw HTML
807 public static function textarea( $name, $value = '', array $attribs = [] ) {
808 $attribs['name'] = $name;
810 if ( substr( $value, 0, 1 ) == "\n" ) {
811 // Workaround for T14130: browsers eat the initial newline
812 // assuming that it's just for show, but they do keep the later
813 // newlines, which we may want to preserve during editing.
814 // Prepending a single newline
815 $spacedValue = "\n" . $value;
817 $spacedValue = $value;
819 return self
::element( 'textarea', self
::getTextInputAttributes( $attribs ), $spacedValue );
823 * Helper for Html::namespaceSelector().
824 * @param array $params See Html::namespaceSelector()
827 public static function namespaceSelectorOptions( array $params = [] ) {
830 if ( !isset( $params['exclude'] ) ||
!is_array( $params['exclude'] ) ) {
831 $params['exclude'] = [];
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)
841 MediaWikiServices
::getInstance()->getContentLanguage()->getFormattedNamespaces();
844 // Filter out namespaces below 0 and massage labels
845 foreach ( $options as $nsId => $nsName ) {
846 if ( $nsId < NS_MAIN ||
in_array( $nsId, $params['exclude'] ) ) {
849 if ( $nsId === NS_MAIN
) {
850 // For other namespaces use the namespace prefix as label, but for
851 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
852 $nsName = wfMessage( 'blanknamespace' )->text();
853 } elseif ( is_int( $nsId ) ) {
854 $nsName = MediaWikiServices
::getInstance()->getContentLanguage()->
855 convertNamespace( $nsId );
857 $optionsOut[$nsId] = $nsName;
864 * Build a drop-down box for selecting a namespace
866 * @param array $params Params to set.
867 * - selected: [optional] Id of namespace which should be pre-selected
868 * - all: [optional] Value of item for "all namespaces". If null or unset,
869 * no "<option>" is generated to select all namespaces.
870 * - label: text for label to add before the field.
871 * - exclude: [optional] Array of namespace ids to exclude.
872 * - disable: [optional] Array of namespace ids for which the option should
873 * be disabled in the selector.
874 * @param array $selectAttribs HTML attributes for the generated select element.
875 * - id: [optional], default: 'namespace'.
876 * - name: [optional], default: 'namespace'.
877 * @return string HTML code to select a namespace.
879 public static function namespaceSelector( array $params = [],
880 array $selectAttribs = []
882 ksort( $selectAttribs );
884 // Is a namespace selected?
885 if ( isset( $params['selected'] ) ) {
886 // If string only contains digits, convert to clean int. Selected could also
887 // be "all" or "" etc. which needs to be left untouched.
888 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
889 // and returns false for already clean ints. Use regex instead..
890 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
891 $params['selected'] = intval( $params['selected'] );
893 // else: leaves it untouched for later processing
895 $params['selected'] = '';
898 if ( !isset( $params['disable'] ) ||
!is_array( $params['disable'] ) ) {
899 $params['disable'] = [];
902 // Associative array between option-values and option-labels
903 $options = self
::namespaceSelectorOptions( $params );
905 // Convert $options to HTML
907 foreach ( $options as $nsId => $nsName ) {
908 $optionsHtml[] = self
::element(
910 'disabled' => in_array( $nsId, $params['disable'] ),
912 'selected' => $nsId === $params['selected'],
917 if ( !array_key_exists( 'id', $selectAttribs ) ) {
918 $selectAttribs['id'] = 'namespace';
921 if ( !array_key_exists( 'name', $selectAttribs ) ) {
922 $selectAttribs['name'] = 'namespace';
926 if ( isset( $params['label'] ) ) {
927 $ret .= self
::element(
929 'for' => $selectAttribs['id'] ??
null,
934 // Wrap options in a <select>
935 $ret .= self
::openElement( 'select', $selectAttribs )
937 . implode( "\n", $optionsHtml )
939 . self
::closeElement( 'select' );
945 * Constructs the opening html-tag with necessary doctypes depending on
948 * @param array $attribs Associative array of miscellaneous extra
949 * attributes, passed to Html::element() of html tag.
950 * @return string Raw HTML
952 public static function htmlHeader( array $attribs = [] ) {
955 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
957 $isXHTML = self
::isXmlMimeType( $wgMimeType );
959 if ( $isXHTML ) { // XHTML5
960 // XML MIME-typed markup should have an xml header.
961 // However a DOCTYPE is not needed.
962 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
964 // Add the standard xmlns
965 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
967 // And support custom namespaces
968 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
969 $attribs["xmlns:$tag"] = $ns;
973 $ret .= "<!DOCTYPE html>\n";
976 if ( $wgHtml5Version ) {
977 $attribs['version'] = $wgHtml5Version;
980 $ret .= self
::openElement( 'html', $attribs );
986 * Determines if the given MIME type is xml.
988 * @param string $mimetype MIME type
991 public static function isXmlMimeType( $mimetype ) {
992 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
995 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
996 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1000 * Get HTML for an info box with an icon.
1002 * @param string $text Wikitext, get this with wfMessage()->plain()
1003 * @param string $icon Path to icon file (used as 'src' attribute)
1004 * @param string $alt Alternate text for the icon
1005 * @param string $class Additional class name to add to the wrapper div
1009 static function infoBox( $text, $icon, $alt, $class = '' ) {
1010 $s = self
::openElement( 'div', [ 'class' => "mw-infobox $class" ] );
1012 $s .= self
::openElement( 'div', [ 'class' => 'mw-infobox-left' ] ) .
1013 self
::element( 'img',
1019 self
::closeElement( 'div' );
1021 $s .= self
::openElement( 'div', [ 'class' => 'mw-infobox-right' ] ) .
1023 self
::closeElement( 'div' );
1024 $s .= self
::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
1026 $s .= self
::closeElement( 'div' );
1028 $s .= self
::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
1034 * Generate a srcset attribute value.
1036 * Generates a srcset attribute value from an array mapping pixel densities
1037 * to URLs. A trailing 'x' in pixel density values is optional.
1039 * @note srcset width and height values are not supported.
1041 * @see https://html.spec.whatwg.org/#attr-img-srcset
1046 * '1x' => 'standard.jpeg',
1047 * '1.5x' => 'large.jpeg',
1048 * '3x' => 'extra-large.jpeg',
1050 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1053 * @param string[] $urls
1056 static function srcSet( array $urls ) {
1058 foreach ( $urls as $density => $url ) {
1059 // Cast density to float to strip 'x', then back to string to serve
1061 $density = (string)(float)$density;
1062 $candidates[$density] = $url;
1065 // Remove duplicates that are the same as a smaller value
1066 ksort( $candidates, SORT_NUMERIC
);
1067 $candidates = array_unique( $candidates );
1069 // Append density info to the url
1070 foreach ( $candidates as $density => $url ) {
1071 $candidates[$density] = $url . ' ' . $density . 'x';
1074 return implode( ", ", $candidates );