MediaWiki master
Html.php
Go to the documentation of this file.
1<?php
26namespace MediaWiki\Html;
27
32use UnexpectedValueException;
33
56class Html {
58 private static $voidElements = [
59 'area' => true,
60 'base' => true,
61 'br' => true,
62 'col' => true,
63 'embed' => true,
64 'hr' => true,
65 'img' => true,
66 'input' => true,
67 'keygen' => true,
68 'link' => true,
69 'meta' => true,
70 'param' => true,
71 'source' => true,
72 'track' => true,
73 'wbr' => true,
74 ];
75
81 private static $boolAttribs = [
82 'async' => true,
83 'autofocus' => true,
84 'autoplay' => true,
85 'checked' => true,
86 'controls' => true,
87 'default' => true,
88 'defer' => true,
89 'disabled' => true,
90 'formnovalidate' => true,
91 'hidden' => true,
92 'ismap' => true,
93 'itemscope' => true,
94 'loop' => true,
95 'multiple' => true,
96 'muted' => true,
97 'novalidate' => true,
98 'open' => true,
99 'pubdate' => true,
100 'readonly' => true,
101 'required' => true,
102 'reversed' => true,
103 'scoped' => true,
104 'seamless' => true,
105 'selected' => true,
106 'truespeed' => true,
107 'typemustmatch' => true,
108 ];
109
118 public static function buttonAttributes( array $attrs, array $modifiers = [] ) {
119 wfDeprecated( __METHOD__, '1.42' );
120 return $attrs;
121 }
122
130 public static function getTextInputAttributes( array $attrs ) {
131 wfDeprecated( __METHOD__, '1.42' );
132 return $attrs;
133 }
134
145 public static function linkButton( $text, array $attrs, array $modifiers = [] ) {
146 return self::element(
147 'a',
148 $attrs,
149 $text
150 );
151 }
152
163 public static function submitButton( $contents, array $attrs = [], array $modifiers = [] ) {
164 $attrs['type'] = 'submit';
165 $attrs['value'] = $contents;
166 return self::element( 'input', $attrs );
167 }
168
191 public static function rawElement( $element, $attribs = [], $contents = '' ) {
192 $start = self::openElement( $element, $attribs );
193 if ( isset( self::$voidElements[$element] ) ) {
194 return $start;
195 } else {
196 return $start . $contents . self::closeElement( $element );
197 }
198 }
199
216 public static function element( $element, $attribs = [], $contents = '' ) {
217 return self::rawElement(
218 $element,
219 $attribs,
220 strtr( $contents ?? '', [
221 // There's no point in escaping quotes, >, etc. in the contents of
222 // elements.
223 '&' => '&amp;',
224 '<' => '&lt;',
225 ] )
226 );
227 }
228
240 public static function openElement( $element, $attribs = [] ) {
241 $attribs = (array)$attribs;
242 // This is not required in HTML5, but let's do it anyway, for
243 // consistency and better compression.
244 $element = strtolower( $element );
245
246 // Some people were abusing this by passing things like
247 // 'h1 id="foo" to $element, which we don't want.
248 if ( str_contains( $element, ' ' ) ) {
249 wfWarn( __METHOD__ . " given element name with space '$element'" );
250 }
251
252 // Remove invalid input types
253 if ( $element == 'input' ) {
254 $validTypes = [
255 'hidden' => true,
256 'text' => true,
257 'password' => true,
258 'checkbox' => true,
259 'radio' => true,
260 'file' => true,
261 'submit' => true,
262 'image' => true,
263 'reset' => true,
264 'button' => true,
265
266 // HTML input types
267 'datetime' => true,
268 'datetime-local' => true,
269 'date' => true,
270 'month' => true,
271 'time' => true,
272 'week' => true,
273 'number' => true,
274 'range' => true,
275 'email' => true,
276 'url' => true,
277 'search' => true,
278 'tel' => true,
279 'color' => true,
280 ];
281 if ( isset( $attribs['type'] ) && !isset( $validTypes[$attribs['type']] ) ) {
282 unset( $attribs['type'] );
283 }
284 }
285
286 // According to standard the default type for <button> elements is "submit".
287 // Depending on compatibility mode IE might use "button", instead.
288 // We enforce the standard "submit".
289 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
290 $attribs['type'] = 'submit';
291 }
292
293 return "<$element" . self::expandAttributes(
294 self::dropDefaults( $element, $attribs ) ) . '>';
295 }
296
304 public static function closeElement( $element ) {
305 $element = strtolower( $element );
306
307 return "</$element>";
308 }
309
327 private static function dropDefaults( $element, array $attribs ) {
328 // Whenever altering this array, please provide a covering test case
329 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
330 static $attribDefaults = [
331 'area' => [ 'shape' => 'rect' ],
332 'button' => [
333 'formaction' => 'GET',
334 'formenctype' => 'application/x-www-form-urlencoded',
335 ],
336 'canvas' => [
337 'height' => '150',
338 'width' => '300',
339 ],
340 'form' => [
341 'action' => 'GET',
342 'autocomplete' => 'on',
343 'enctype' => 'application/x-www-form-urlencoded',
344 ],
345 'input' => [
346 'formaction' => 'GET',
347 'type' => 'text',
348 ],
349 'keygen' => [ 'keytype' => 'rsa' ],
350 'link' => [ 'media' => 'all' ],
351 'menu' => [ 'type' => 'list' ],
352 'script' => [ 'type' => 'text/javascript' ],
353 'style' => [
354 'media' => 'all',
355 'type' => 'text/css',
356 ],
357 'textarea' => [ 'wrap' => 'soft' ],
358 ];
359
360 foreach ( $attribs as $attrib => $value ) {
361 if ( $attrib === 'class' ) {
362 if ( $value === '' || $value === [] || $value === [ '' ] ) {
363 unset( $attribs[$attrib] );
364 }
365 } elseif ( isset( $attribDefaults[$element][$attrib] ) ) {
366 if ( is_array( $value ) ) {
367 $value = implode( ' ', $value );
368 } else {
369 $value = strval( $value );
370 }
371 if ( $attribDefaults[$element][$attrib] == $value ) {
372 unset( $attribs[$attrib] );
373 }
374 }
375 }
376
377 // More subtle checks
378 if ( $element === 'link'
379 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
380 ) {
381 unset( $attribs['type'] );
382 }
383 if ( $element === 'input' ) {
384 $type = $attribs['type'] ?? null;
385 $value = $attribs['value'] ?? null;
386 if ( $type === 'checkbox' || $type === 'radio' ) {
387 // The default value for checkboxes and radio buttons is 'on'
388 // not ''. By stripping value="" we break radio boxes that
389 // actually wants empty values.
390 if ( $value === 'on' ) {
391 unset( $attribs['value'] );
392 }
393 } elseif ( $type === 'submit' ) {
394 // The default value for submit appears to be "Submit" but
395 // let's not bother stripping out localized text that matches
396 // that.
397 } else {
398 // The default value for nearly every other field type is ''
399 // The 'range' and 'color' types use different defaults but
400 // stripping a value="" does not hurt them.
401 if ( $value === '' ) {
402 unset( $attribs['value'] );
403 }
404 }
405 }
406 if ( $element === 'select' && isset( $attribs['size'] ) ) {
407 $multiple = ( $attribs['multiple'] ?? false ) !== false ||
408 in_array( 'multiple', $attribs );
409 $default = $multiple ? 4 : 1;
410 if ( (int)$attribs['size'] === $default ) {
411 unset( $attribs['size'] );
412 }
413 }
414
415 return $attribs;
416 }
417
456 public static function expandAttributes( array $attribs ) {
457 $ret = '';
458 foreach ( $attribs as $key => $value ) {
459 // Support intuitive [ 'checked' => true/false ] form
460 if ( $value === false || $value === null ) {
461 continue;
462 }
463
464 // For boolean attributes, support [ 'foo' ] instead of
465 // requiring [ 'foo' => 'meaningless' ].
466 if ( is_int( $key ) && isset( self::$boolAttribs[strtolower( $value )] ) ) {
467 $key = $value;
468 }
469
470 // Not technically required in HTML5 but we'd like consistency
471 // and better compression anyway.
472 $key = strtolower( $key );
473
474 // https://www.w3.org/TR/html401/index/attributes.html ("space-separated")
475 // https://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
476 $spaceSeparatedListAttributes = [
477 'class' => true, // html4, html5
478 'accesskey' => true, // as of html5, multiple space-separated values allowed
479 // html4-spec doesn't document rel= as space-separated
480 // but has been used like that and is now documented as such
481 // in the html5-spec.
482 'rel' => true,
483 ];
484
485 // Specific features for attributes that allow a list of space-separated values
486 if ( isset( $spaceSeparatedListAttributes[$key] ) ) {
487 // Apply some normalization and remove duplicates
488
489 // Convert into correct array. Array can contain space-separated
490 // values. Implode/explode to get those into the main array as well.
491 if ( is_array( $value ) ) {
492 // If input wasn't an array, we can skip this step
493 $arrayValue = [];
494 foreach ( $value as $k => $v ) {
495 if ( is_string( $v ) ) {
496 // String values should be normal `[ 'foo' ]`
497 // Just append them
498 if ( !isset( $value[$v] ) ) {
499 // As a special case don't set 'foo' if a
500 // separate 'foo' => true/false exists in the array
501 // keys should be authoritative
502 foreach ( explode( ' ', $v ) as $part ) {
503 // Normalize spacing by fixing up cases where people used
504 // more than 1 space and/or a trailing/leading space
505 if ( $part !== '' && $part !== ' ' ) {
506 $arrayValue[] = $part;
507 }
508 }
509 }
510 } elseif ( $v ) {
511 // If the value is truthy but not a string this is likely
512 // an [ 'foo' => true ], falsy values don't add strings
513 $arrayValue[] = $k;
514 }
515 }
516 } else {
517 $arrayValue = explode( ' ', $value );
518 // Normalize spacing by fixing up cases where people used
519 // more than 1 space and/or a trailing/leading space
520 $arrayValue = array_diff( $arrayValue, [ '', ' ' ] );
521 }
522
523 // Remove duplicates and create the string
524 $value = implode( ' ', array_unique( $arrayValue ) );
525
526 // Optimization: Skip below boolAttribs check and jump straight
527 // to its `else` block. The current $spaceSeparatedListAttributes
528 // block is mutually exclusive with $boolAttribs.
529 // phpcs:ignore Generic.PHP.DiscourageGoto
530 goto not_bool; // NOSONAR
531 } elseif ( is_array( $value ) ) {
532 throw new UnexpectedValueException( "HTML attribute $key can not contain a list of values" );
533 }
534
535 if ( isset( self::$boolAttribs[$key] ) ) {
536 $ret .= " $key=\"\"";
537 } else {
538 // phpcs:ignore Generic.PHP.DiscourageGoto
539 not_bool:
540 // Inlined from Sanitizer::encodeAttribute() for improved performance
541 $encValue = htmlspecialchars( $value, ENT_QUOTES );
542 // Whitespace is normalized during attribute decoding,
543 // so if we've been passed non-spaces we must encode them
544 // ahead of time or they won't be preserved.
545 $encValue = strtr( $encValue, [
546 "\n" => '&#10;',
547 "\r" => '&#13;',
548 "\t" => '&#9;',
549 ] );
550 $ret .= " $key=\"$encValue\"";
551 }
552 }
553 return $ret;
554 }
555
569 public static function inlineScript( $contents, $nonce = null ) {
570 if ( preg_match( '/<\/?script/i', $contents ) ) {
571 wfLogWarning( __METHOD__ . ': Illegal character sequence found in inline script.' );
572 $contents = '/* ERROR: Invalid script */';
573 }
574
575 return self::rawElement( 'script', [], $contents );
576 }
577
586 public static function linkedScript( $url, $nonce = null ) {
587 $attrs = [ 'src' => $url ];
588 if ( $nonce !== null ) {
589 $attrs['nonce'] = $nonce;
590 } elseif ( ContentSecurityPolicy::isNonceRequired( MediaWikiServices::getInstance()->getMainConfig() ) ) {
591 wfWarn( "no nonce set on script. CSP will break it" );
592 }
593
594 return self::element( 'script', $attrs );
595 }
596
609 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
610 // Don't escape '>' since that is used
611 // as direct child selector.
612 // Remember, in css, there is no "x" for hexadecimal escapes, and
613 // the space immediately after an escape sequence is swallowed.
614 $contents = strtr( $contents, [
615 '<' => '\3C ',
616 // CDATA end tag for good measure, but the main security
617 // is from escaping the '<'.
618 ']]>' => '\5D\5D\3E '
619 ] );
620
621 if ( preg_match( '/[<&]/', $contents ) ) {
622 $contents = "/*<![CDATA[*/$contents/*]]>*/";
623 }
624
625 return self::rawElement( 'style', [
626 'media' => $media,
627 ] + $attribs, $contents );
628 }
629
638 public static function linkedStyle( $url, $media = 'all' ) {
639 return self::element( 'link', [
640 'rel' => 'stylesheet',
641 'href' => $url,
642 'media' => $media,
643 ] );
644 }
645
657 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
658 $attribs['type'] = $type;
659 $attribs['value'] = $value;
660 $attribs['name'] = $name;
661 return self::element( 'input', $attribs );
662 }
663
672 public static function check( $name, $checked = false, array $attribs = [] ) {
673 if ( isset( $attribs['value'] ) ) {
674 $value = $attribs['value'];
675 unset( $attribs['value'] );
676 } else {
677 $value = 1;
678 }
679
680 if ( $checked ) {
681 $attribs[] = 'checked';
682 }
683
684 return self::input( $name, $value, 'checkbox', $attribs );
685 }
686
697 private static function messageBox( $html, $className, $heading = '', $iconClassName = '' ) {
698 if ( $heading !== '' ) {
699 $html = self::element( 'h2', [], $heading ) . $html;
700 }
701 $coreClasses = [
702 'cdx-message',
703 'cdx-message--block'
704 ];
705 if ( is_array( $className ) ) {
706 $className = array_merge(
707 $coreClasses,
708 $className
709 );
710 } else {
711 $className .= ' ' . implode( ' ', $coreClasses );
712 }
713 return self::rawElement( 'div', [ 'class' => $className ],
714 self::element( 'span', [ 'class' => [
715 'cdx-message__icon',
716 $iconClassName
717 ] ] ) .
718 self::rawElement( 'div', [
719 'class' => 'cdx-message__content'
720 ], $html )
721 );
722 }
723
734 public static function noticeBox( $html, $className, $heading = '', $iconClassName = '' ) {
735 return self::messageBox( $html, [
736 'cdx-message--notice',
737 $className
738 ], $heading, $iconClassName );
739 }
740
750 public static function warningBox( $html, $className = '' ) {
751 return self::messageBox( $html, [
752 'cdx-message--warning', $className ] );
753 }
754
765 public static function errorBox( $html, $heading = '', $className = '' ) {
766 return self::messageBox( $html, [
767 'cdx-message--error', $className ], $heading );
768 }
769
779 public static function successBox( $html, $className = '' ) {
780 return self::messageBox( $html, [
781 'cdx-message--success', $className ] );
782 }
783
792 public static function radio( $name, $checked = false, array $attribs = [] ) {
793 if ( isset( $attribs['value'] ) ) {
794 $value = $attribs['value'];
795 unset( $attribs['value'] );
796 } else {
797 $value = 1;
798 }
799
800 if ( $checked ) {
801 $attribs[] = 'checked';
802 }
803
804 return self::input( $name, $value, 'radio', $attribs );
805 }
806
815 public static function label( $label, $id, array $attribs = [] ) {
816 $attribs += [
817 'for' => $id,
818 ];
819 return self::element( 'label', $attribs, $label );
820 }
821
831 public static function hidden( $name, $value, array $attribs = [] ) {
832 return self::input( $name, $value, 'hidden', $attribs );
833 }
834
847 public static function textarea( $name, $value = '', array $attribs = [] ) {
848 $attribs['name'] = $name;
849
850 if ( substr( $value, 0, 1 ) == "\n" ) {
851 // Workaround for T14130: browsers eat the initial newline
852 // assuming that it's just for show, but they do keep the later
853 // newlines, which we may want to preserve during editing.
854 // Prepending a single newline
855 $spacedValue = "\n" . $value;
856 } else {
857 $spacedValue = $value;
858 }
859 return self::element( 'textarea', $attribs, $spacedValue );
860 }
861
867 public static function namespaceSelectorOptions( array $params = [] ) {
868 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
869 $params['exclude'] = [];
870 }
871
872 if ( $params['in-user-lang'] ?? false ) {
873 global $wgLang;
874 $lang = $wgLang;
875 } else {
876 $lang = MediaWikiServices::getInstance()->getContentLanguage();
877 }
878
879 $optionsOut = [];
880 if ( isset( $params['all'] ) ) {
881 // add an option that would let the user select all namespaces.
882 // Value is provided by user, the name shown is localized for the user.
883 $optionsOut[$params['all']] = wfMessage( 'namespacesall' )->text();
884 }
885 // Add all namespaces as options
886 $options = $lang->getFormattedNamespaces();
887 // Filter out namespaces below 0 and massage labels
888 foreach ( $options as $nsId => $nsName ) {
889 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
890 continue;
891 }
892 if (
893 isset( $params['include'] ) &&
894 is_array( $params['include'] ) &&
895 !in_array( $nsId, $params['include'] )
896 ) {
897 continue;
898 }
899
900 if ( $nsId === NS_MAIN ) {
901 // For other namespaces use the namespace prefix as label, but for
902 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
903 $nsName = wfMessage( 'blanknamespace' )->text();
904 } elseif ( is_int( $nsId ) ) {
905 $converter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
906 ->getLanguageConverter( $lang );
907 $nsName = $converter->convertNamespace( $nsId );
908 }
909 $optionsOut[$nsId] = $nsName;
910 }
911
912 return $optionsOut;
913 }
914
931 public static function namespaceSelector(
932 array $params = [],
933 array $selectAttribs = []
934 ) {
935 ksort( $selectAttribs );
936
937 // Is a namespace selected?
938 if ( isset( $params['selected'] ) ) {
939 // If string only contains digits, convert to clean int. Selected could also
940 // be "all" or "" etc. which needs to be left untouched.
941 if ( !is_int( $params['selected'] ) && ctype_digit( (string)$params['selected'] ) ) {
942 $params['selected'] = (int)$params['selected'];
943 }
944 // else: leaves it untouched for later processing
945 } else {
946 $params['selected'] = '';
947 }
948
949 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
950 $params['disable'] = [];
951 }
952
953 // Associative array between option-values and option-labels
955
956 // Convert $options to HTML
957 $optionsHtml = [];
958 foreach ( $options as $nsId => $nsName ) {
959 $optionsHtml[] = self::element(
960 'option',
961 [
962 'disabled' => in_array( $nsId, $params['disable'] ),
963 'value' => $nsId,
964 'selected' => $nsId === $params['selected'],
965 ],
966 $nsName
967 );
968 }
969
970 $selectAttribs['id'] ??= 'namespace';
971 $selectAttribs['name'] ??= 'namespace';
972
973 $ret = '';
974 if ( isset( $params['label'] ) ) {
975 $ret .= self::element(
976 'label', [
977 'for' => $selectAttribs['id'],
978 ], $params['label']
979 ) . "\u{00A0}";
980 }
981
982 // Wrap options in a <select>
983 $ret .= self::openElement( 'select', $selectAttribs )
984 . "\n"
985 . implode( "\n", $optionsHtml )
986 . "\n"
987 . self::closeElement( 'select' );
988
989 return $ret;
990 }
991
1000 public static function htmlHeader( array $attribs = [] ) {
1001 $ret = '';
1002 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1003 $html5Version = $mainConfig->get( MainConfigNames::Html5Version );
1004 $mimeType = $mainConfig->get( MainConfigNames::MimeType );
1005 $xhtmlNamespaces = $mainConfig->get( MainConfigNames::XhtmlNamespaces );
1006
1007 $isXHTML = self::isXmlMimeType( $mimeType );
1008
1009 if ( $isXHTML ) { // XHTML5
1010 // XML MIME-typed markup should have an xml header.
1011 // However a DOCTYPE is not needed.
1012 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
1013
1014 // Add the standard xmlns
1015 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
1016
1017 // And support custom namespaces
1018 foreach ( $xhtmlNamespaces as $tag => $ns ) {
1019 $attribs["xmlns:$tag"] = $ns;
1020 }
1021 } else { // HTML5
1022 $ret .= "<!DOCTYPE html>\n";
1023 }
1024
1025 if ( $html5Version ) {
1026 $attribs['version'] = $html5Version;
1027 }
1028
1029 $ret .= self::openElement( 'html', $attribs );
1030
1031 return $ret;
1032 }
1033
1040 public static function isXmlMimeType( $mimetype ) {
1041 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
1042 # * text/xml
1043 # * application/xml
1044 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1045 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1046 }
1047
1071 public static function srcSet( array $urls ) {
1072 $candidates = [];
1073 foreach ( $urls as $density => $url ) {
1074 // Cast density to float to strip 'x', then back to string to serve
1075 // as array index.
1076 $density = (string)(float)$density;
1077 $candidates[$density] = $url;
1078 }
1079
1080 // Remove duplicates that are the same as a smaller value
1081 ksort( $candidates, SORT_NUMERIC );
1082 $candidates = array_unique( $candidates );
1083
1084 // Append density info to the url
1085 foreach ( $candidates as $density => $url ) {
1086 $candidates[$density] = $url . ' ' . $density . 'x';
1087 }
1088
1089 return implode( ", ", $candidates );
1090 }
1091
1106 public static function encodeJsVar( $value, $pretty = false ) {
1107 if ( $value instanceof HtmlJsCode ) {
1108 return $value->value;
1109 }
1110 return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
1111 }
1112
1127 public static function encodeJsCall( $name, $args, $pretty = false ) {
1128 $encodedArgs = self::encodeJsList( $args, $pretty );
1129 if ( $encodedArgs === false ) {
1130 return false;
1131 }
1132 return "$name($encodedArgs);";
1133 }
1134
1144 public static function encodeJsList( $args, $pretty = false ) {
1145 foreach ( $args as &$arg ) {
1146 $arg = self::encodeJsVar( $arg, $pretty );
1147 if ( $arg === false ) {
1148 return false;
1149 }
1150 }
1151 if ( $pretty ) {
1152 return ' ' . implode( ', ', $args ) . ' ';
1153 } else {
1154 return implode( ',', $args );
1155 }
1156 }
1157
1171 public static function listDropdownOptions( $list, $params = [] ) {
1172 $options = [];
1173
1174 if ( isset( $params['other'] ) ) {
1175 $options[ $params['other'] ] = 'other';
1176 }
1177
1178 $optgroup = false;
1179 foreach ( explode( "\n", $list ) as $option ) {
1180 $value = trim( $option );
1181 if ( $value == '' ) {
1182 continue;
1183 }
1184 if ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
1185 # A new group is starting...
1186 $value = trim( substr( $value, 1 ) );
1187 if ( $value !== '' &&
1188 // Do not use the value for 'other' as option group - T251351
1189 ( !isset( $params['other'] ) || $value !== $params['other'] )
1190 ) {
1191 $optgroup = $value;
1192 } else {
1193 $optgroup = false;
1194 }
1195 } elseif ( substr( $value, 0, 2 ) == '**' ) {
1196 # groupmember
1197 $opt = trim( substr( $value, 2 ) );
1198 if ( $optgroup === false ) {
1199 $options[$opt] = $opt;
1200 } else {
1201 $options[$optgroup][$opt] = $opt;
1202 }
1203 } else {
1204 # groupless reason list
1205 $optgroup = false;
1206 $options[$option] = $option;
1207 }
1208 }
1209
1210 return $options;
1211 }
1212
1221 public static function listDropdownOptionsOoui( $options ) {
1222 $optionsOoui = [];
1223
1224 foreach ( $options as $text => $value ) {
1225 if ( is_array( $value ) ) {
1226 $optionsOoui[] = [ 'optgroup' => (string)$text ];
1227 foreach ( $value as $text2 => $value2 ) {
1228 $optionsOoui[] = [ 'data' => (string)$value2, 'label' => (string)$text2 ];
1229 }
1230 } else {
1231 $optionsOoui[] = [ 'data' => (string)$value, 'label' => (string)$text ];
1232 }
1233 }
1234
1235 return $optionsOoui;
1236 }
1237
1246 public static function listDropdownOptionsCodex( $options ) {
1247 $optionsCodex = [];
1248
1249 foreach ( $options as $text => $value ) {
1250 if ( is_array( $value ) ) {
1251 // No support for optgroups in Codex yet (T367241)
1252 $optionsCodex[] = [ 'label' => (string)$text, 'value' => '', 'disabled' => true ];
1253 foreach ( $value as $text2 => $value2 ) {
1254 $optionsCodex[] = [ 'label' => (string)$text2, 'value' => (string)$value2 ];
1255 }
1256 } else {
1257 $optionsCodex[] = [ 'label' => (string)$text, 'value' => (string)$value ];
1258 }
1259 }
1260 return $optionsCodex;
1261 }
1262}
1263
1265class_alias( Html::class, 'Html' );
const NS_MAIN
Definition Defines.php:65
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgLang
Definition Setup.php:541
array $params
The job parameters.
A wrapper class which causes Html::encodeJsVar() and Html::encodeJsCall() (as well as their Xml::* co...
This class is a collection of static functions that serve two purposes:
Definition Html.php:56
static linkedScript( $url, $nonce=null)
Output a "<script>" tag linking to the given URL, e.g., "<script src=foo.js></script>".
Definition Html.php:586
static listDropdownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition Html.php:1221
static namespaceSelector(array $params=[], array $selectAttribs=[])
Build a drop-down box for selecting a namespace.
Definition Html.php:931
static warningBox( $html, $className='')
Return a warning box.
Definition Html.php:750
static check( $name, $checked=false, array $attribs=[])
Convenience function to produce a checkbox (input element with type=checkbox)
Definition Html.php:672
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition Html.php:1106
static listDropdownOptionsCodex( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition Html.php:1246
static label( $label, $id, array $attribs=[])
Convenience function for generating a label for inputs.
Definition Html.php:815
static expandAttributes(array $attribs)
Given an associative array of element attributes, generate a string to stick after the element name i...
Definition Html.php:456
static srcSet(array $urls)
Generate a srcset attribute value.
Definition Html.php:1071
static successBox( $html, $className='')
Return a success box.
Definition Html.php:779
static buttonAttributes(array $attrs, array $modifiers=[])
Modifies a set of attributes meant for button elements.
Definition Html.php:118
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition Html.php:1127
static htmlHeader(array $attribs=[])
Constructs the opening html-tag with necessary doctypes depending on global variables.
Definition Html.php:1000
static errorBox( $html, $heading='', $className='')
Return an error box.
Definition Html.php:765
static inlineScript( $contents, $nonce=null)
Output an HTML script tag with the given contents.
Definition Html.php:569
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition Html.php:240
static radio( $name, $checked=false, array $attribs=[])
Convenience function to produce a radio button (input element with type=radio)
Definition Html.php:792
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition Html.php:191
static isXmlMimeType( $mimetype)
Determines if the given MIME type is xml.
Definition Html.php:1040
static getTextInputAttributes(array $attrs)
Modifies a set of attributes meant for text input elements.
Definition Html.php:130
static input( $name, $value='', $type='text', array $attribs=[])
Convenience function to produce an <input> element.
Definition Html.php:657
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition Html.php:831
static textarea( $name, $value='', array $attribs=[])
Convenience function to produce a <textarea> element.
Definition Html.php:847
static namespaceSelectorOptions(array $params=[])
Helper for Html::namespaceSelector().
Definition Html.php:867
static inlineStyle( $contents, $media='all', $attribs=[])
Output a "<style>" tag with the given contents for the given media type (if any).
Definition Html.php:609
static closeElement( $element)
Returns "</$element>".
Definition Html.php:304
static linkButton( $text, array $attrs, array $modifiers=[])
Returns an HTML link element in a string.
Definition Html.php:145
static submitButton( $contents, array $attrs=[], array $modifiers=[])
Returns an HTML input element in a string.
Definition Html.php:163
static encodeJsList( $args, $pretty=false)
Encode a JavaScript comma-separated list.
Definition Html.php:1144
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition Html.php:216
static listDropdownOptions( $list, $params=[])
Build options for a drop-down box from a textual list.
Definition Html.php:1171
static linkedStyle( $url, $media='all')
Output a "<link rel=stylesheet>" linking to the given URL for the given media type (if any).
Definition Html.php:638
static noticeBox( $html, $className, $heading='', $iconClassName='')
Return the HTML for a notice message box.
Definition Html.php:734
JSON formatter wrapper class.
A class containing constants representing the names of configuration variables.
const MimeType
Name constant for the MimeType setting, for use with Config::get()
const XhtmlNamespaces
Name constant for the XhtmlNamespaces setting, for use with Config::get()
const Html5Version
Name constant for the Html5Version setting, for use with Config::get()
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
Handle sending Content-Security-Policy headers.