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
696 private static function messageBox( $html, $className, $heading = '', $iconClassName = '' ) {
697 if ( $heading !== '' ) {
698 $html = self::element( 'h2', [], $heading ) . $html;
699 }
700 $coreClasses = [
701 'mw-message-box',
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
733 public static function noticeBox( $html, $className, $heading = '', $iconClassName = '' ) {
734 return self::messageBox( $html, [
735 'mw-message-box-notice',
736 'cdx-message--notice',
737 $className
738 ], $heading, $iconClassName );
739 }
740
749 public static function warningBox( $html, $className = '' ) {
750 return self::messageBox( $html, [
751 'mw-message-box-warning',
752 'cdx-message--warning', $className ] );
753 }
754
764 public static function errorBox( $html, $heading = '', $className = '' ) {
765 return self::messageBox( $html, [
766 'mw-message-box-error',
767 'cdx-message--error', $className ], $heading );
768 }
769
778 public static function successBox( $html, $className = '' ) {
779 return self::messageBox( $html, [
780 'mw-message-box-success',
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 ( $nsId === NS_MAIN ) {
893 // For other namespaces use the namespace prefix as label, but for
894 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
895 $nsName = wfMessage( 'blanknamespace' )->text();
896 } elseif ( is_int( $nsId ) ) {
897 $converter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
898 ->getLanguageConverter( $lang );
899 $nsName = $converter->convertNamespace( $nsId );
900 }
901 $optionsOut[$nsId] = $nsName;
902 }
903
904 return $optionsOut;
905 }
906
923 public static function namespaceSelector(
924 array $params = [],
925 array $selectAttribs = []
926 ) {
927 ksort( $selectAttribs );
928
929 // Is a namespace selected?
930 if ( isset( $params['selected'] ) ) {
931 // If string only contains digits, convert to clean int. Selected could also
932 // be "all" or "" etc. which needs to be left untouched.
933 if ( !is_int( $params['selected'] ) && ctype_digit( (string)$params['selected'] ) ) {
934 $params['selected'] = (int)$params['selected'];
935 }
936 // else: leaves it untouched for later processing
937 } else {
938 $params['selected'] = '';
939 }
940
941 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
942 $params['disable'] = [];
943 }
944
945 // Associative array between option-values and option-labels
947
948 // Convert $options to HTML
949 $optionsHtml = [];
950 foreach ( $options as $nsId => $nsName ) {
951 $optionsHtml[] = self::element(
952 'option',
953 [
954 'disabled' => in_array( $nsId, $params['disable'] ),
955 'value' => $nsId,
956 'selected' => $nsId === $params['selected'],
957 ],
958 $nsName
959 );
960 }
961
962 $selectAttribs['id'] ??= 'namespace';
963 $selectAttribs['name'] ??= 'namespace';
964
965 $ret = '';
966 if ( isset( $params['label'] ) ) {
967 $ret .= self::element(
968 'label', [
969 'for' => $selectAttribs['id'],
970 ], $params['label']
971 ) . "\u{00A0}";
972 }
973
974 // Wrap options in a <select>
975 $ret .= self::openElement( 'select', $selectAttribs )
976 . "\n"
977 . implode( "\n", $optionsHtml )
978 . "\n"
979 . self::closeElement( 'select' );
980
981 return $ret;
982 }
983
992 public static function htmlHeader( array $attribs = [] ) {
993 $ret = '';
994 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
995 $html5Version = $mainConfig->get( MainConfigNames::Html5Version );
996 $mimeType = $mainConfig->get( MainConfigNames::MimeType );
997 $xhtmlNamespaces = $mainConfig->get( MainConfigNames::XhtmlNamespaces );
998
999 $isXHTML = self::isXmlMimeType( $mimeType );
1000
1001 if ( $isXHTML ) { // XHTML5
1002 // XML MIME-typed markup should have an xml header.
1003 // However a DOCTYPE is not needed.
1004 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
1005
1006 // Add the standard xmlns
1007 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
1008
1009 // And support custom namespaces
1010 foreach ( $xhtmlNamespaces as $tag => $ns ) {
1011 $attribs["xmlns:$tag"] = $ns;
1012 }
1013 } else { // HTML5
1014 $ret .= "<!DOCTYPE html>\n";
1015 }
1016
1017 if ( $html5Version ) {
1018 $attribs['version'] = $html5Version;
1019 }
1020
1021 $ret .= self::openElement( 'html', $attribs );
1022
1023 return $ret;
1024 }
1025
1032 public static function isXmlMimeType( $mimetype ) {
1033 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
1034 # * text/xml
1035 # * application/xml
1036 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1037 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1038 }
1039
1063 public static function srcSet( array $urls ) {
1064 $candidates = [];
1065 foreach ( $urls as $density => $url ) {
1066 // Cast density to float to strip 'x', then back to string to serve
1067 // as array index.
1068 $density = (string)(float)$density;
1069 $candidates[$density] = $url;
1070 }
1071
1072 // Remove duplicates that are the same as a smaller value
1073 ksort( $candidates, SORT_NUMERIC );
1074 $candidates = array_unique( $candidates );
1075
1076 // Append density info to the url
1077 foreach ( $candidates as $density => $url ) {
1078 $candidates[$density] = $url . ' ' . $density . 'x';
1079 }
1080
1081 return implode( ", ", $candidates );
1082 }
1083
1098 public static function encodeJsVar( $value, $pretty = false ) {
1099 if ( $value instanceof HtmlJsCode ) {
1100 return $value->value;
1101 }
1102 return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
1103 }
1104
1119 public static function encodeJsCall( $name, $args, $pretty = false ) {
1120 $encodedArgs = self::encodeJsList( $args, $pretty );
1121 if ( $encodedArgs === false ) {
1122 return false;
1123 }
1124 return "$name($encodedArgs);";
1125 }
1126
1136 public static function encodeJsList( $args, $pretty = false ) {
1137 foreach ( $args as &$arg ) {
1138 $arg = self::encodeJsVar( $arg, $pretty );
1139 if ( $arg === false ) {
1140 return false;
1141 }
1142 }
1143 if ( $pretty ) {
1144 return ' ' . implode( ', ', $args ) . ' ';
1145 } else {
1146 return implode( ',', $args );
1147 }
1148 }
1149
1163 public static function listDropdownOptions( $list, $params = [] ) {
1164 $options = [];
1165
1166 if ( isset( $params['other'] ) ) {
1167 $options[ $params['other'] ] = 'other';
1168 }
1169
1170 $optgroup = false;
1171 foreach ( explode( "\n", $list ) as $option ) {
1172 $value = trim( $option );
1173 if ( $value == '' ) {
1174 continue;
1175 }
1176 if ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
1177 # A new group is starting...
1178 $value = trim( substr( $value, 1 ) );
1179 if ( $value !== '' &&
1180 // Do not use the value for 'other' as option group - T251351
1181 ( !isset( $params['other'] ) || $value !== $params['other'] )
1182 ) {
1183 $optgroup = $value;
1184 } else {
1185 $optgroup = false;
1186 }
1187 } elseif ( substr( $value, 0, 2 ) == '**' ) {
1188 # groupmember
1189 $opt = trim( substr( $value, 2 ) );
1190 if ( $optgroup === false ) {
1191 $options[$opt] = $opt;
1192 } else {
1193 $options[$optgroup][$opt] = $opt;
1194 }
1195 } else {
1196 # groupless reason list
1197 $optgroup = false;
1198 $options[$option] = $option;
1199 }
1200 }
1201
1202 return $options;
1203 }
1204
1213 public static function listDropdownOptionsOoui( $options ) {
1214 $optionsOoui = [];
1215
1216 foreach ( $options as $text => $value ) {
1217 if ( is_array( $value ) ) {
1218 $optionsOoui[] = [ 'optgroup' => (string)$text ];
1219 foreach ( $value as $text2 => $value2 ) {
1220 $optionsOoui[] = [ 'data' => (string)$value2, 'label' => (string)$text2 ];
1221 }
1222 } else {
1223 $optionsOoui[] = [ 'data' => (string)$value, 'label' => (string)$text ];
1224 }
1225 }
1226
1227 return $optionsOoui;
1228 }
1229}
1230
1232class_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:538
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:1213
static namespaceSelector(array $params=[], array $selectAttribs=[])
Build a drop-down box for selecting a namespace.
Definition Html.php:923
static warningBox( $html, $className='')
Return a warning box.
Definition Html.php:749
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:1098
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:1063
static successBox( $html, $className='')
Return a success box.
Definition Html.php:778
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:1119
static htmlHeader(array $attribs=[])
Constructs the opening html-tag with necessary doctypes depending on global variables.
Definition Html.php:992
static errorBox( $html, $heading='', $className='')
Return an error box.
Definition Html.php:764
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:1032
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:1136
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:1163
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:733
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.