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 // Some people were abusing this by passing things like
259 // 'h1 id="foo" to $element, which we don't want.
260 if ( strpos( $element, ' ' ) !== false ) {
261 wfWarn( __METHOD__
. " given element name with space '$element'" );
264 // Remove invalid input types
265 if ( $element == 'input' ) {
293 if ( isset( $attribs['type'] ) && !in_array( $attribs['type'], $validTypes ) ) {
294 unset( $attribs['type'] );
298 // According to standard the default type for <button> elements is "submit".
299 // Depending on compatibility mode IE might use "button", instead.
300 // We enforce the standard "submit".
301 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
302 $attribs['type'] = 'submit';
305 return "<$element" . self
::expandAttributes(
306 self
::dropDefaults( $element, $attribs ) ) . '>';
310 * Returns "</$element>"
313 * @param string $element Name of the element, e.g., 'a'
314 * @return string A closing tag
316 public static function closeElement( $element ) {
317 $element = strtolower( $element );
319 return "</$element>";
323 * Given an element name and an associative array of element attributes,
324 * return an array that is functionally identical to the input array, but
325 * possibly smaller. In particular, attributes might be stripped if they
326 * are given their default values.
328 * This method is not guaranteed to remove all redundant attributes, only
329 * some common ones and some others selected arbitrarily at random. It
330 * only guarantees that the output array should be functionally identical
331 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
333 * @param string $element Name of the element, e.g., 'a'
334 * @param array $attribs Associative array of attributes, e.g., [
335 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
336 * further documentation.
337 * @return array An array of attributes functionally identical to $attribs
339 private static function dropDefaults( $element, array $attribs ) {
340 // Whenever altering this array, please provide a covering test case
341 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
342 static $attribDefaults = [
343 'area' => [ 'shape' => 'rect' ],
345 'formaction' => 'GET',
346 'formenctype' => 'application/x-www-form-urlencoded',
354 'autocomplete' => 'on',
355 'enctype' => 'application/x-www-form-urlencoded',
358 'formaction' => 'GET',
361 'keygen' => [ 'keytype' => 'rsa' ],
362 'link' => [ 'media' => 'all' ],
363 'menu' => [ 'type' => 'list' ],
364 'script' => [ 'type' => 'text/javascript' ],
367 'type' => 'text/css',
369 'textarea' => [ 'wrap' => 'soft' ],
372 $element = strtolower( $element );
374 foreach ( $attribs as $attrib => $value ) {
375 $lcattrib = strtolower( $attrib );
376 if ( is_array( $value ) ) {
377 $value = implode( ' ', $value );
379 $value = strval( $value );
382 // Simple checks using $attribDefaults
383 if ( isset( $attribDefaults[$element][$lcattrib] )
384 && $attribDefaults[$element][$lcattrib] == $value
386 unset( $attribs[$attrib] );
389 if ( $lcattrib == 'class' && $value == '' ) {
390 unset( $attribs[$attrib] );
394 // More subtle checks
395 if ( $element === 'link'
396 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
398 unset( $attribs['type'] );
400 if ( $element === 'input' ) {
401 $type = $attribs['type'] ??
null;
402 $value = $attribs['value'] ??
null;
403 if ( $type === 'checkbox' ||
$type === 'radio' ) {
404 // The default value for checkboxes and radio buttons is 'on'
405 // not ''. By stripping value="" we break radio boxes that
406 // actually wants empty values.
407 if ( $value === 'on' ) {
408 unset( $attribs['value'] );
410 } elseif ( $type === 'submit' ) {
411 // The default value for submit appears to be "Submit" but
412 // let's not bother stripping out localized text that matches
415 // The default value for nearly every other field type is ''
416 // The 'range' and 'color' types use different defaults but
417 // stripping a value="" does not hurt them.
418 if ( $value === '' ) {
419 unset( $attribs['value'] );
423 if ( $element === 'select' && isset( $attribs['size'] ) ) {
424 if ( in_array( 'multiple', $attribs )
425 ||
( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
428 if ( strval( $attribs['size'] ) == '4' ) {
429 unset( $attribs['size'] );
433 if ( strval( $attribs['size'] ) == '1' ) {
434 unset( $attribs['size'] );
443 * Given an associative array of element attributes, generate a string
444 * to stick after the element name in HTML output. Like [ 'href' =>
445 * 'https://www.mediawiki.org/' ] becomes something like
446 * ' href="https://www.mediawiki.org"'. Again, this is like
447 * Xml::expandAttributes(), but it implements some HTML-specific logic.
449 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
450 * values are allowed as well, which will automagically be normalized
451 * and converted to a space-separated string. In addition to a numerical
452 * array, the attribute value may also be an associative array. See the
453 * example below for how that works.
455 * @par Numerical array
457 * Html::element( 'em', [
458 * 'class' => [ 'foo', 'bar' ]
460 * // gives '<em class="foo bar"></em>'
463 * @par Associative array
465 * Html::element( 'em', [
466 * 'class' => [ 'foo', 'bar', 'foo' => false, 'quux' => true ]
468 * // gives '<em class="bar quux"></em>'
471 * @param array $attribs Associative array of attributes, e.g., [
472 * 'href' => 'https://www.mediawiki.org/' ]. Values will be HTML-escaped.
473 * A value of false or null means to omit the attribute. For boolean attributes,
474 * you can omit the key, e.g., [ 'checked' ] instead of
475 * [ 'checked' => 'checked' ] or such.
477 * @throws MWException If an attribute that doesn't allow lists is set to an array
478 * @return string HTML fragment that goes between element name and '>'
479 * (starting with a space if at least one attribute is output)
481 public static function expandAttributes( array $attribs ) {
483 foreach ( $attribs as $key => $value ) {
484 // Support intuitive [ 'checked' => true/false ] form
485 if ( $value === false ||
is_null( $value ) ) {
489 // For boolean attributes, support [ 'foo' ] instead of
490 // requiring [ 'foo' => 'meaningless' ].
491 if ( is_int( $key ) && in_array( strtolower( $value ), self
::$boolAttribs ) ) {
495 // Not technically required in HTML5 but we'd like consistency
496 // and better compression anyway.
497 $key = strtolower( $key );
499 // https://www.w3.org/TR/html401/index/attributes.html ("space-separated")
500 // https://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
501 $spaceSeparatedListAttributes = [
502 'class', // html4, html5
503 'accesskey', // as of html5, multiple space-separated values allowed
504 // html4-spec doesn't document rel= as space-separated
505 // but has been used like that and is now documented as such
506 // in the html5-spec.
510 // Specific features for attributes that allow a list of space-separated values
511 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
512 // Apply some normalization and remove duplicates
514 // Convert into correct array. Array can contain space-separated
515 // values. Implode/explode to get those into the main array as well.
516 if ( is_array( $value ) ) {
517 // If input wasn't an array, we can skip this step
519 foreach ( $value as $k => $v ) {
520 if ( is_string( $v ) ) {
521 // String values should be normal `array( 'foo' )`
523 if ( !isset( $value[$v] ) ) {
524 // As a special case don't set 'foo' if a
525 // separate 'foo' => true/false exists in the array
526 // keys should be authoritative
530 // If the value is truthy but not a string this is likely
531 // an [ 'foo' => true ], falsy values don't add strings
535 $value = implode( ' ', $newValue );
537 $value = explode( ' ', $value );
539 // Normalize spacing by fixing up cases where people used
540 // more than 1 space and/or a trailing/leading space
541 $value = array_diff( $value, [ '', ' ' ] );
543 // Remove duplicates and create the string
544 $value = implode( ' ', array_unique( $value ) );
545 } elseif ( is_array( $value ) ) {
546 throw new MWException( "HTML attribute $key can not contain a list of values" );
551 if ( in_array( $key, self
::$boolAttribs ) ) {
552 $ret .= " $key=\"\"";
554 $ret .= " $key=$quote" . Sanitizer
::encodeAttribute( $value ) . $quote;
561 * Output an HTML script tag with the given contents.
563 * It is unsupported for the contents to contain the sequence `<script` or `</script`
564 * (case-insensitive). This ensures the script can be terminated easily and consistently.
565 * It is the responsibility of the caller to avoid such character sequence by escaping
566 * or avoiding it. If found at run-time, the contents are replaced with a comment, and
567 * a warning is logged server-side.
569 * @param string $contents JavaScript
570 * @param string|null $nonce Nonce for CSP header, from OutputPage::getCSPNonce()
571 * @return string Raw HTML
573 public static function inlineScript( $contents, $nonce = null ) {
575 if ( $nonce !== null ) {
576 $attrs['nonce'] = $nonce;
578 if ( ContentSecurityPolicy
::isNonceRequired( RequestContext
::getMain()->getConfig() ) ) {
579 wfWarn( "no nonce set on script. CSP will break it" );
583 if ( preg_match( '/<\/?script/i', $contents ) ) {
584 wfLogWarning( __METHOD__
. ': Illegal character sequence found in inline script.' );
585 $contents = '/* ERROR: Invalid script */';
588 return self
::rawElement( 'script', $attrs, $contents );
592 * Output a "<script>" tag linking to the given URL, e.g.,
593 * "<script src=foo.js></script>".
596 * @param string|null $nonce Nonce for CSP header, from OutputPage::getCSPNonce()
597 * @return string Raw HTML
599 public static function linkedScript( $url, $nonce = null ) {
600 $attrs = [ 'src' => $url ];
601 if ( $nonce !== null ) {
602 $attrs['nonce'] = $nonce;
604 if ( ContentSecurityPolicy
::isNonceRequired( RequestContext
::getMain()->getConfig() ) ) {
605 wfWarn( "no nonce set on script. CSP will break it" );
609 return self
::element( 'script', $attrs );
613 * Output a "<style>" tag with the given contents for the given media type
614 * (if any). TODO: do some useful escaping as well, like if $contents
615 * contains literal "</style>" (admittedly unlikely).
617 * @param string $contents CSS
618 * @param string $media A media type string, like 'screen'
619 * @param array $attribs (since 1.31) Associative array of attributes, e.g., [
620 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
621 * further documentation.
622 * @return string Raw HTML
624 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
625 // Don't escape '>' since that is used
626 // as direct child selector.
627 // Remember, in css, there is no "x" for hexadecimal escapes, and
628 // the space immediately after an escape sequence is swallowed.
629 $contents = strtr( $contents, [
631 // CDATA end tag for good measure, but the main security
632 // is from escaping the '<'.
633 ']]>' => '\5D\5D\3E '
636 if ( preg_match( '/[<&]/', $contents ) ) {
637 $contents = "/*<![CDATA[*/$contents/*]]>*/";
640 return self
::rawElement( 'style', [
642 ] +
$attribs, $contents );
646 * Output a "<link rel=stylesheet>" linking to the given URL for the given
647 * media type (if any).
650 * @param string $media A media type string, like 'screen'
651 * @return string Raw HTML
653 public static function linkedStyle( $url, $media = 'all' ) {
654 return self
::element( 'link', [
655 'rel' => 'stylesheet',
662 * Convenience function to produce an "<input>" element. This supports the
663 * new HTML5 input types and attributes.
665 * @param string $name Name attribute
666 * @param string $value Value attribute
667 * @param string $type Type attribute
668 * @param array $attribs Associative array of miscellaneous extra
669 * attributes, passed to Html::element()
670 * @return string Raw HTML
672 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
673 $attribs['type'] = $type;
674 $attribs['value'] = $value;
675 $attribs['name'] = $name;
676 if ( in_array( $type, [ 'text', 'search', 'email', 'password', 'number' ] ) ) {
677 $attribs = self
::getTextInputAttributes( $attribs );
679 if ( in_array( $type, [ 'button', 'reset', 'submit' ] ) ) {
680 $attribs = self
::buttonAttributes( $attribs );
682 return self
::element( 'input', $attribs );
686 * Convenience function to produce a checkbox (input element with type=checkbox)
688 * @param string $name Name attribute
689 * @param bool $checked Whether the checkbox is checked or not
690 * @param array $attribs Array of additional attributes
691 * @return string Raw HTML
693 public static function check( $name, $checked = false, array $attribs = [] ) {
694 if ( isset( $attribs['value'] ) ) {
695 $value = $attribs['value'];
696 unset( $attribs['value'] );
702 $attribs[] = 'checked';
705 return self
::input( $name, $value, 'checkbox', $attribs );
709 * Return the HTML for a message box.
711 * @param string $html of contents of box
712 * @param string $className corresponding to box
713 * @param string $heading (optional)
714 * @return string of HTML representing a box.
716 private static function messageBox( $html, $className, $heading = '' ) {
717 if ( $heading !== '' ) {
718 $html = self
::element( 'h2', [], $heading ) . $html;
720 return self
::rawElement( 'div', [ 'class' => $className ], $html );
724 * Return a warning box.
726 * @param string $html of contents of box
727 * @return string of HTML representing a warning box.
729 public static function warningBox( $html ) {
730 return self
::messageBox( $html, 'warningbox' );
734 * Return an error box.
736 * @param string $html of contents of error box
737 * @param string $heading (optional)
738 * @return string of HTML representing an error box.
740 public static function errorBox( $html, $heading = '' ) {
741 return self
::messageBox( $html, 'errorbox', $heading );
745 * Return a success box.
747 * @param string $html of contents of box
748 * @return string of HTML representing a success box.
750 public static function successBox( $html ) {
751 return self
::messageBox( $html, 'successbox' );
755 * Convenience function to produce a radio button (input element with type=radio)
757 * @param string $name Name attribute
758 * @param bool $checked Whether the radio button is checked or not
759 * @param array $attribs Array of additional attributes
760 * @return string Raw HTML
762 public static function radio( $name, $checked = false, array $attribs = [] ) {
763 if ( isset( $attribs['value'] ) ) {
764 $value = $attribs['value'];
765 unset( $attribs['value'] );
771 $attribs[] = 'checked';
774 return self
::input( $name, $value, 'radio', $attribs );
778 * Convenience function for generating a label for inputs.
780 * @param string $label Contents of the label
781 * @param string $id ID of the element being labeled
782 * @param array $attribs Additional attributes
783 * @return string Raw HTML
785 public static function label( $label, $id, array $attribs = [] ) {
789 return self
::element( 'label', $attribs, $label );
793 * Convenience function to produce an input element with type=hidden
795 * @param string $name Name attribute
796 * @param string $value Value attribute
797 * @param array $attribs Associative array of miscellaneous extra
798 * attributes, passed to Html::element()
799 * @return string Raw HTML
801 public static function hidden( $name, $value, array $attribs = [] ) {
802 return self
::input( $name, $value, 'hidden', $attribs );
806 * Convenience function to produce a <textarea> element.
808 * This supports leaving out the cols= and rows= which Xml requires and are
809 * required by HTML4/XHTML but not required by HTML5.
811 * @param string $name Name attribute
812 * @param string $value Value attribute
813 * @param array $attribs Associative array of miscellaneous extra
814 * attributes, passed to Html::element()
815 * @return string Raw HTML
817 public static function textarea( $name, $value = '', array $attribs = [] ) {
818 $attribs['name'] = $name;
820 if ( substr( $value, 0, 1 ) == "\n" ) {
821 // Workaround for T14130: browsers eat the initial newline
822 // assuming that it's just for show, but they do keep the later
823 // newlines, which we may want to preserve during editing.
824 // Prepending a single newline
825 $spacedValue = "\n" . $value;
827 $spacedValue = $value;
829 return self
::element( 'textarea', self
::getTextInputAttributes( $attribs ), $spacedValue );
833 * Helper for Html::namespaceSelector().
834 * @param array $params See Html::namespaceSelector()
837 public static function namespaceSelectorOptions( array $params = [] ) {
840 if ( !isset( $params['exclude'] ) ||
!is_array( $params['exclude'] ) ) {
841 $params['exclude'] = [];
844 if ( isset( $params['all'] ) ) {
845 // add an option that would let the user select all namespaces.
846 // Value is provided by user, the name shown is localized for the user.
847 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
849 if ( $params['in-user-lang'] ??
false ) {
853 $lang = MediaWikiServices
::getInstance()->getContentLanguage();
855 // Add all namespaces as options
856 $options +
= $lang->getFormattedNamespaces();
859 // Filter out namespaces below 0 and massage labels
860 foreach ( $options as $nsId => $nsName ) {
861 if ( $nsId < NS_MAIN ||
in_array( $nsId, $params['exclude'] ) ) {
864 if ( $nsId === NS_MAIN
) {
865 // For other namespaces use the namespace prefix as label, but for
866 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
867 $nsName = wfMessage( 'blanknamespace' )->text();
868 } elseif ( is_int( $nsId ) ) {
869 $nsName = $lang->convertNamespace( $nsId );
871 $optionsOut[$nsId] = $nsName;
878 * Build a drop-down box for selecting a namespace
880 * @param array $params Params to set.
881 * - selected: [optional] Id of namespace which should be pre-selected
882 * - all: [optional] Value of item for "all namespaces". If null or unset,
883 * no "<option>" is generated to select all namespaces.
884 * - label: text for label to add before the field.
885 * - exclude: [optional] Array of namespace ids to exclude.
886 * - disable: [optional] Array of namespace ids for which the option should
887 * be disabled in the selector.
888 * @param array $selectAttribs HTML attributes for the generated select element.
889 * - id: [optional], default: 'namespace'.
890 * - name: [optional], default: 'namespace'.
891 * @return string HTML code to select a namespace.
893 public static function namespaceSelector( array $params = [],
894 array $selectAttribs = []
896 ksort( $selectAttribs );
898 // Is a namespace selected?
899 if ( isset( $params['selected'] ) ) {
900 // If string only contains digits, convert to clean int. Selected could also
901 // be "all" or "" etc. which needs to be left untouched.
902 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
903 // and returns false for already clean ints. Use regex instead..
904 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
905 $params['selected'] = intval( $params['selected'] );
907 // else: leaves it untouched for later processing
909 $params['selected'] = '';
912 if ( !isset( $params['disable'] ) ||
!is_array( $params['disable'] ) ) {
913 $params['disable'] = [];
916 // Associative array between option-values and option-labels
917 $options = self
::namespaceSelectorOptions( $params );
919 // Convert $options to HTML
921 foreach ( $options as $nsId => $nsName ) {
922 $optionsHtml[] = self
::element(
924 'disabled' => in_array( $nsId, $params['disable'] ),
926 'selected' => $nsId === $params['selected'],
931 if ( !array_key_exists( 'id', $selectAttribs ) ) {
932 $selectAttribs['id'] = 'namespace';
935 if ( !array_key_exists( 'name', $selectAttribs ) ) {
936 $selectAttribs['name'] = 'namespace';
940 if ( isset( $params['label'] ) ) {
941 $ret .= self
::element(
943 'for' => $selectAttribs['id'] ??
null,
948 // Wrap options in a <select>
949 $ret .= self
::openElement( 'select', $selectAttribs )
951 . implode( "\n", $optionsHtml )
953 . self
::closeElement( 'select' );
959 * Constructs the opening html-tag with necessary doctypes depending on
962 * @param array $attribs Associative array of miscellaneous extra
963 * attributes, passed to Html::element() of html tag.
964 * @return string Raw HTML
966 public static function htmlHeader( array $attribs = [] ) {
969 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
971 $isXHTML = self
::isXmlMimeType( $wgMimeType );
973 if ( $isXHTML ) { // XHTML5
974 // XML MIME-typed markup should have an xml header.
975 // However a DOCTYPE is not needed.
976 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
978 // Add the standard xmlns
979 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
981 // And support custom namespaces
982 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
983 $attribs["xmlns:$tag"] = $ns;
987 $ret .= "<!DOCTYPE html>\n";
990 if ( $wgHtml5Version ) {
991 $attribs['version'] = $wgHtml5Version;
994 $ret .= self
::openElement( 'html', $attribs );
1000 * Determines if the given MIME type is xml.
1002 * @param string $mimetype MIME type
1005 public static function isXmlMimeType( $mimetype ) {
1006 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
1009 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1010 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1014 * Get HTML for an info box with an icon.
1016 * @param string $text Wikitext, get this with wfMessage()->plain()
1017 * @param string $icon Path to icon file (used as 'src' attribute)
1018 * @param string $alt Alternate text for the icon
1019 * @param string $class Additional class name to add to the wrapper div
1023 static function infoBox( $text, $icon, $alt, $class = '' ) {
1024 $s = self
::openElement( 'div', [ 'class' => "mw-infobox $class" ] );
1026 $s .= self
::openElement( 'div', [ 'class' => 'mw-infobox-left' ] ) .
1027 self
::element( 'img',
1033 self
::closeElement( 'div' );
1035 $s .= self
::openElement( 'div', [ 'class' => 'mw-infobox-right' ] ) .
1037 self
::closeElement( 'div' );
1038 $s .= self
::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
1040 $s .= self
::closeElement( 'div' );
1042 $s .= self
::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
1048 * Generate a srcset attribute value.
1050 * Generates a srcset attribute value from an array mapping pixel densities
1051 * to URLs. A trailing 'x' in pixel density values is optional.
1053 * @note srcset width and height values are not supported.
1055 * @see https://html.spec.whatwg.org/#attr-img-srcset
1060 * '1x' => 'standard.jpeg',
1061 * '1.5x' => 'large.jpeg',
1062 * '3x' => 'extra-large.jpeg',
1064 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1067 * @param string[] $urls
1070 static function srcSet( array $urls ) {
1072 foreach ( $urls as $density => $url ) {
1073 // Cast density to float to strip 'x', then back to string to serve
1075 $density = (string)(float)$density;
1076 $candidates[$density] = $url;
1079 // Remove duplicates that are the same as a smaller value
1080 ksort( $candidates, SORT_NUMERIC
);
1081 $candidates = array_unique( $candidates );
1083 // Append density info to the url
1084 foreach ( $candidates as $density => $url ) {
1085 $candidates[$density] = $url . ' ' . $density . 'x';
1088 return implode( ", ", $candidates );