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 an HTML script tag with the given contents.
557 * It is unsupported for the contents to contain the sequence `<script` or `</script`
558 * (case-insensitive). This ensures the script can be terminated easily and consistently.
559 * It is the responsibility of the caller to avoid such character sequence by escaping
560 * or avoiding it. If found at run-time, the contents are replaced with a comment, and
561 * a warning is logged server-side.
563 * @param string $contents JavaScript
564 * @param string|null $nonce Nonce for CSP header, from OutputPage::getCSPNonce()
565 * @return string Raw HTML
567 public static function inlineScript( $contents, $nonce = null ) {
569 if ( $nonce !== null ) {
570 $attrs['nonce'] = $nonce;
572 if ( ContentSecurityPolicy
::isNonceRequired( RequestContext
::getMain()->getConfig() ) ) {
573 wfWarn( "no nonce set on script. CSP will break it" );
577 if ( preg_match( '/<\/?script/i', $contents ) ) {
578 wfLogWarning( __METHOD__
. ': Illegal character sequence found in inline script.' );
579 $contents = '/* ERROR: Invalid script */';
582 return self
::rawElement( 'script', $attrs, $contents );
586 * Output a "<script>" tag linking to the given URL, e.g.,
587 * "<script src=foo.js></script>".
590 * @param string|null $nonce Nonce for CSP header, from OutputPage::getCSPNonce()
591 * @return string Raw HTML
593 public static function linkedScript( $url, $nonce = null ) {
594 $attrs = [ 'src' => $url ];
595 if ( $nonce !== null ) {
596 $attrs['nonce'] = $nonce;
598 if ( ContentSecurityPolicy
::isNonceRequired( RequestContext
::getMain()->getConfig() ) ) {
599 wfWarn( "no nonce set on script. CSP will break it" );
603 return self
::element( 'script', $attrs );
607 * Output a "<style>" tag with the given contents for the given media type
608 * (if any). TODO: do some useful escaping as well, like if $contents
609 * contains literal "</style>" (admittedly unlikely).
611 * @param string $contents CSS
612 * @param string $media A media type string, like 'screen'
613 * @param array $attribs (since 1.31) Associative array of attributes, e.g., [
614 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
615 * further documentation.
616 * @return string Raw HTML
618 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
619 // Don't escape '>' since that is used
620 // as direct child selector.
621 // Remember, in css, there is no "x" for hexadecimal escapes, and
622 // the space immediately after an escape sequence is swallowed.
623 $contents = strtr( $contents, [
625 // CDATA end tag for good measure, but the main security
626 // is from escaping the '<'.
627 ']]>' => '\5D\5D\3E '
630 if ( preg_match( '/[<&]/', $contents ) ) {
631 $contents = "/*<![CDATA[*/$contents/*]]>*/";
634 return self
::rawElement( 'style', [
636 ] +
$attribs, $contents );
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 * Return the HTML for a message box.
705 * @param string $html of contents of box
706 * @param string $className corresponding to box
707 * @param string $heading (optional)
708 * @return string of HTML representing a box.
710 private static function messageBox( $html, $className, $heading = '' ) {
711 if ( $heading !== '' ) {
712 $html = self
::element( 'h2', [], $heading ) . $html;
714 return self
::rawElement( 'div', [ 'class' => $className ], $html );
718 * Return a warning box.
720 * @param string $html of contents of box
721 * @return string of HTML representing a warning box.
723 public static function warningBox( $html ) {
724 return self
::messageBox( $html, 'warningbox' );
728 * Return an error box.
730 * @param string $html of contents of error box
731 * @param string $heading (optional)
732 * @return string of HTML representing an error box.
734 public static function errorBox( $html, $heading = '' ) {
735 return self
::messageBox( $html, 'errorbox', $heading );
739 * Return a success box.
741 * @param string $html of contents of box
742 * @return string of HTML representing a success box.
744 public static function successBox( $html ) {
745 return self
::messageBox( $html, 'successbox' );
749 * Convenience function to produce a radio button (input element with type=radio)
751 * @param string $name Name attribute
752 * @param bool $checked Whether the radio button is checked or not
753 * @param array $attribs Array of additional attributes
754 * @return string Raw HTML
756 public static function radio( $name, $checked = false, array $attribs = [] ) {
757 if ( isset( $attribs['value'] ) ) {
758 $value = $attribs['value'];
759 unset( $attribs['value'] );
765 $attribs[] = 'checked';
768 return self
::input( $name, $value, 'radio', $attribs );
772 * Convenience function for generating a label for inputs.
774 * @param string $label Contents of the label
775 * @param string $id ID of the element being labeled
776 * @param array $attribs Additional attributes
777 * @return string Raw HTML
779 public static function label( $label, $id, array $attribs = [] ) {
783 return self
::element( 'label', $attribs, $label );
787 * Convenience function to produce an input element with type=hidden
789 * @param string $name Name attribute
790 * @param string $value Value attribute
791 * @param array $attribs Associative array of miscellaneous extra
792 * attributes, passed to Html::element()
793 * @return string Raw HTML
795 public static function hidden( $name, $value, array $attribs = [] ) {
796 return self
::input( $name, $value, 'hidden', $attribs );
800 * Convenience function to produce a <textarea> element.
802 * This supports leaving out the cols= and rows= which Xml requires and are
803 * required by HTML4/XHTML but not required by HTML5.
805 * @param string $name Name attribute
806 * @param string $value Value attribute
807 * @param array $attribs Associative array of miscellaneous extra
808 * attributes, passed to Html::element()
809 * @return string Raw HTML
811 public static function textarea( $name, $value = '', array $attribs = [] ) {
812 $attribs['name'] = $name;
814 if ( substr( $value, 0, 1 ) == "\n" ) {
815 // Workaround for T14130: browsers eat the initial newline
816 // assuming that it's just for show, but they do keep the later
817 // newlines, which we may want to preserve during editing.
818 // Prepending a single newline
819 $spacedValue = "\n" . $value;
821 $spacedValue = $value;
823 return self
::element( 'textarea', self
::getTextInputAttributes( $attribs ), $spacedValue );
827 * Helper for Html::namespaceSelector().
828 * @param array $params See Html::namespaceSelector()
831 public static function namespaceSelectorOptions( array $params = [] ) {
834 if ( !isset( $params['exclude'] ) ||
!is_array( $params['exclude'] ) ) {
835 $params['exclude'] = [];
838 if ( isset( $params['all'] ) ) {
839 // add an option that would let the user select all namespaces.
840 // Value is provided by user, the name shown is localized for the user.
841 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
843 // Add all namespaces as options (in the content language)
845 MediaWikiServices
::getInstance()->getContentLanguage()->getFormattedNamespaces();
848 // Filter out namespaces below 0 and massage labels
849 foreach ( $options as $nsId => $nsName ) {
850 if ( $nsId < NS_MAIN ||
in_array( $nsId, $params['exclude'] ) ) {
853 if ( $nsId === NS_MAIN
) {
854 // For other namespaces use the namespace prefix as label, but for
855 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
856 $nsName = wfMessage( 'blanknamespace' )->text();
857 } elseif ( is_int( $nsId ) ) {
858 $nsName = MediaWikiServices
::getInstance()->getContentLanguage()->
859 convertNamespace( $nsId );
861 $optionsOut[$nsId] = $nsName;
868 * Build a drop-down box for selecting a namespace
870 * @param array $params Params to set.
871 * - selected: [optional] Id of namespace which should be pre-selected
872 * - all: [optional] Value of item for "all namespaces". If null or unset,
873 * no "<option>" is generated to select all namespaces.
874 * - label: text for label to add before the field.
875 * - exclude: [optional] Array of namespace ids to exclude.
876 * - disable: [optional] Array of namespace ids for which the option should
877 * be disabled in the selector.
878 * @param array $selectAttribs HTML attributes for the generated select element.
879 * - id: [optional], default: 'namespace'.
880 * - name: [optional], default: 'namespace'.
881 * @return string HTML code to select a namespace.
883 public static function namespaceSelector( array $params = [],
884 array $selectAttribs = []
886 ksort( $selectAttribs );
888 // Is a namespace selected?
889 if ( isset( $params['selected'] ) ) {
890 // If string only contains digits, convert to clean int. Selected could also
891 // be "all" or "" etc. which needs to be left untouched.
892 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
893 // and returns false for already clean ints. Use regex instead..
894 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
895 $params['selected'] = intval( $params['selected'] );
897 // else: leaves it untouched for later processing
899 $params['selected'] = '';
902 if ( !isset( $params['disable'] ) ||
!is_array( $params['disable'] ) ) {
903 $params['disable'] = [];
906 // Associative array between option-values and option-labels
907 $options = self
::namespaceSelectorOptions( $params );
909 // Convert $options to HTML
911 foreach ( $options as $nsId => $nsName ) {
912 $optionsHtml[] = self
::element(
914 'disabled' => in_array( $nsId, $params['disable'] ),
916 'selected' => $nsId === $params['selected'],
921 if ( !array_key_exists( 'id', $selectAttribs ) ) {
922 $selectAttribs['id'] = 'namespace';
925 if ( !array_key_exists( 'name', $selectAttribs ) ) {
926 $selectAttribs['name'] = 'namespace';
930 if ( isset( $params['label'] ) ) {
931 $ret .= self
::element(
933 'for' => $selectAttribs['id'] ??
null,
938 // Wrap options in a <select>
939 $ret .= self
::openElement( 'select', $selectAttribs )
941 . implode( "\n", $optionsHtml )
943 . self
::closeElement( 'select' );
949 * Constructs the opening html-tag with necessary doctypes depending on
952 * @param array $attribs Associative array of miscellaneous extra
953 * attributes, passed to Html::element() of html tag.
954 * @return string Raw HTML
956 public static function htmlHeader( array $attribs = [] ) {
959 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
961 $isXHTML = self
::isXmlMimeType( $wgMimeType );
963 if ( $isXHTML ) { // XHTML5
964 // XML MIME-typed markup should have an xml header.
965 // However a DOCTYPE is not needed.
966 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
968 // Add the standard xmlns
969 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
971 // And support custom namespaces
972 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
973 $attribs["xmlns:$tag"] = $ns;
977 $ret .= "<!DOCTYPE html>\n";
980 if ( $wgHtml5Version ) {
981 $attribs['version'] = $wgHtml5Version;
984 $ret .= self
::openElement( 'html', $attribs );
990 * Determines if the given MIME type is xml.
992 * @param string $mimetype MIME type
995 public static function isXmlMimeType( $mimetype ) {
996 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
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
1013 static function infoBox( $text, $icon, $alt, $class = '' ) {
1014 $s = self
::openElement( 'div', [ 'class' => "mw-infobox $class" ] );
1016 $s .= self
::openElement( 'div', [ 'class' => 'mw-infobox-left' ] ) .
1017 self
::element( 'img',
1023 self
::closeElement( 'div' );
1025 $s .= self
::openElement( 'div', [ 'class' => 'mw-infobox-right' ] ) .
1027 self
::closeElement( 'div' );
1028 $s .= self
::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
1030 $s .= self
::closeElement( 'div' );
1032 $s .= self
::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
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 https://html.spec.whatwg.org/#attr-img-srcset
1050 * '1x' => 'standard.jpeg',
1051 * '1.5x' => 'large.jpeg',
1052 * '3x' => 'extra-large.jpeg',
1054 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1057 * @param string[] $urls
1060 static function srcSet( array $urls ) {
1062 foreach ( $urls as $density => $url ) {
1063 // Cast density to float to strip 'x', then back to string to serve
1065 $density = (string)(float)$density;
1066 $candidates[$density] = $url;
1069 // Remove duplicates that are the same as a smaller value
1070 ksort( $candidates, SORT_NUMERIC
);
1071 $candidates = array_unique( $candidates );
1073 // Append density info to the url
1074 foreach ( $candidates as $density => $url ) {
1075 $candidates[$density] = $url . ' ' . $density . 'x';
1078 return implode( ", ", $candidates );