MediaWiki master
Html.php
Go to the documentation of this file.
1<?php
11
12namespace MediaWiki\Html;
13
14use MediaWiki\Context\RequestContext;
15use MediaWiki\Json\FormatJson;
16use MediaWiki\MainConfigNames;
17use MediaWiki\MediaWikiServices;
18use MediaWiki\Parser\Sanitizer;
19use MediaWiki\Request\ContentSecurityPolicy;
20use UnexpectedValueException;
21
44class Html {
46 private const VOID_ELEMENTS = [
47 'area' => true,
48 'base' => true,
49 'br' => true,
50 'col' => true,
51 'embed' => true,
52 'hr' => true,
53 'img' => true,
54 'input' => true,
55 'keygen' => true,
56 'link' => true,
57 'meta' => true,
58 'param' => true,
59 'source' => true,
60 'track' => true,
61 'wbr' => true,
62 ];
63
68 private const BOOL_ATTRIBS = [
69 'async' => true,
70 'autofocus' => true,
71 'autoplay' => true,
72 'checked' => true,
73 'controls' => true,
74 'default' => true,
75 'defer' => true,
76 'disabled' => true,
77 'formnovalidate' => true,
78 'hidden' => true,
79 'ismap' => true,
80 'itemscope' => true,
81 'loop' => true,
82 'multiple' => true,
83 'muted' => true,
84 'novalidate' => true,
85 'open' => true,
86 'pubdate' => true,
87 'readonly' => true,
88 'required' => true,
89 'reversed' => true,
90 'scoped' => true,
91 'seamless' => true,
92 'selected' => true,
93 'truespeed' => true,
94 'typemustmatch' => true,
95 ];
96
101 private const ATTRIBS_DEFAULTS = [
102 'area' => [ 'shape' => 'rect' ],
103 'button' => [
104 'formaction' => 'GET',
105 'formenctype' => 'application/x-www-form-urlencoded',
106 ],
107 'canvas' => [
108 'height' => '150',
109 'width' => '300',
110 ],
111 'form' => [
112 'action' => 'GET',
113 'autocomplete' => 'on',
114 'enctype' => 'application/x-www-form-urlencoded',
115 ],
116 'input' => [
117 'formaction' => 'GET',
118 'type' => 'text',
119 ],
120 'keygen' => [ 'keytype' => 'rsa' ],
121 'link' => [
122 'media' => 'all',
123 'type' => 'text/css',
124 ],
125 'menu' => [ 'type' => 'list' ],
126 'script' => [ 'type' => 'text/javascript' ],
127 'style' => [
128 'media' => 'all',
129 'type' => 'text/css',
130 ],
131 'textarea' => [ 'wrap' => 'soft' ],
132 ];
133
138 private const SPACE_SEPARATED_LIST_ATTRIBUTES = [
139 'class' => true, // html4, html5
140 'accesskey' => true, // as of html5, multiple space-separated values allowed
141 // html4-spec doesn't document rel= as space-separated
142 // but has been used like that and is now documented as such
143 // in the html5-spec.
144 'rel' => true,
145 ];
146
147 private const INPUT_ELEMENT_VALID_TYPES = [
148 'hidden' => true,
149 'text' => true,
150 'password' => true,
151 'checkbox' => true,
152 'radio' => true,
153 'file' => true,
154 'submit' => true,
155 'image' => true,
156 'reset' => true,
157 'button' => true,
158
159 // HTML input types
160 'datetime' => true,
161 'datetime-local' => true,
162 'date' => true,
163 'month' => true,
164 'time' => true,
165 'week' => true,
166 'number' => true,
167 'range' => true,
168 'email' => true,
169 'url' => true,
170 'search' => true,
171 'tel' => true,
172 'color' => true,
173 ];
174
185 public static function addClass( &$classes, string $class ): void {
186 $classes = (array)$classes;
187 // Detect mistakes where $attrs is passed as $classes instead of $attrs['class']
188 foreach ( $classes as $key => $val ) {
189 if (
190 ( is_int( $key ) && is_string( $val ) ) ||
191 ( is_string( $key ) && is_bool( $val ) )
192 ) {
193 // Valid formats for class array entries
194 continue;
195 }
196 wfWarn( __METHOD__ . ": Argument doesn't look like a class array: " . var_export( $classes, true ) );
197 break;
198 }
199 $classes[] = $class;
200 }
201
212 public static function linkButton( $text, array $attrs, array $modifiers = [] ) {
213 return self::element(
214 'a',
215 $attrs,
216 $text
217 );
218 }
219
230 public static function submitButton( $contents, array $attrs = [], array $modifiers = [] ) {
231 $attrs['type'] = 'submit';
232 $attrs['value'] = $contents;
233 return self::element( 'input', $attrs );
234 }
235
258 public static function rawElement( $element, $attribs = [], $contents = '' ) {
259 $start = self::openElement( $element, $attribs );
260 if ( isset( self::VOID_ELEMENTS[$element] ) ) {
261 return $start;
262 } else {
263 $contents = Sanitizer::escapeCombiningChar( $contents ?? '' );
264 return $start . $contents . self::closeElement( $element );
265 }
266 }
267
284 public static function element( $element, $attribs = [], $contents = '' ) {
285 return self::rawElement(
286 $element,
287 $attribs,
288 strtr( $contents ?? '', [
289 // There's no point in escaping quotes, >, etc. in the contents of
290 // elements.
291 '&' => '&amp;',
292 '<' => '&lt;',
293 ] )
294 );
295 }
296
308 public static function openElement( $element, $attribs = [] ) {
309 $attribs = (array)$attribs;
310 // This is not required in HTML5, but let's do it anyway, for
311 // consistency and better compression.
312 $element = strtolower( $element );
313
314 // Some people were abusing this by passing things like
315 // 'h1 id="foo" to $element, which we don't want.
316 if ( str_contains( $element, ' ' ) ) {
317 wfWarn( __METHOD__ . " given element name with space '$element'" );
318 }
319
320 // Remove invalid input types
321 if ( $element == 'input' ) {
322 if ( isset( $attribs['type'] ) && !isset( self::INPUT_ELEMENT_VALID_TYPES[$attribs['type']] ) ) {
323 unset( $attribs['type'] );
324 }
325 }
326
327 // According to standard the default type for <button> elements is "submit".
328 // Depending on compatibility mode IE might use "button", instead.
329 // We enforce the standard "submit".
330 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
331 $attribs['type'] = 'submit';
332 }
333
334 return "<$element" . self::expandAttributes(
335 self::dropDefaults( $element, $attribs ) ) . '>';
336 }
337
345 public static function closeElement( $element ) {
346 $element = strtolower( $element );
347
348 return "</$element>";
349 }
350
368 private static function dropDefaults( $element, array $attribs ) {
369 foreach ( $attribs as $attrib => $value ) {
370 if ( $attrib === 'class' ) {
371 if ( $value === '' || $value === [] || $value === [ '' ] ) {
372 unset( $attribs[$attrib] );
373 }
374 } elseif ( isset( self::ATTRIBS_DEFAULTS[$element][$attrib] ) ) {
375 if ( is_array( $value ) ) {
376 $value = implode( ' ', $value );
377 } else {
378 $value = strval( $value );
379 }
380 if ( self::ATTRIBS_DEFAULTS[$element][$attrib] == $value ) {
381 unset( $attribs[$attrib] );
382 }
383 }
384 }
385
386 // More subtle checks
387 if ( $element === 'input' ) {
388 $type = $attribs['type'] ?? null;
389 $value = $attribs['value'] ?? null;
390 if ( $type === 'checkbox' || $type === 'radio' ) {
391 // The default value for checkboxes and radio buttons is 'on'
392 // not ''. By stripping value="" we break radio boxes that
393 // actually wants empty values.
394 if ( $value === 'on' ) {
395 unset( $attribs['value'] );
396 }
397 } elseif ( $type === 'submit' ) {
398 // The default value for submit appears to be "Submit" but
399 // let's not bother stripping out localized text that matches
400 // that.
401 } else {
402 // The default value for nearly every other field type is ''
403 // The 'range' and 'color' types use different defaults but
404 // stripping a value="" does not hurt them.
405 if ( $value === '' ) {
406 unset( $attribs['value'] );
407 }
408 }
409 }
410 if ( $element === 'select' && isset( $attribs['size'] ) ) {
411 $multiple = ( $attribs['multiple'] ?? false ) !== false ||
412 in_array( 'multiple', $attribs );
413 $default = $multiple ? 4 : 1;
414 if ( (int)$attribs['size'] === $default ) {
415 unset( $attribs['size'] );
416 }
417 }
418
419 return $attribs;
420 }
421
432 public static function expandClassList( $classes ): string {
433 // Convert into correct array. Array can contain space-separated
434 // values. Implode/explode to get those into the main array as well.
435 if ( is_array( $classes ) ) {
436 // If input wasn't an array, we can skip this step
437 $arrayValue = [];
438 foreach ( $classes as $k => $v ) {
439 if ( is_string( $v ) ) {
440 // String values should be normal `[ 'foo' ]`
441 // Just append them
442 if ( !isset( $classes[$v] ) ) {
443 // As a special case don't set 'foo' if a
444 // separate 'foo' => true/false exists in the array
445 // keys should be authoritative
446 foreach ( explode( ' ', $v ) as $part ) {
447 // Normalize spacing by fixing up cases where people used
448 // more than 1 space and/or a trailing/leading space
449 if ( $part !== '' && $part !== ' ' ) {
450 $arrayValue[] = $part;
451 }
452 }
453 }
454 } elseif ( $v ) {
455 // If the value is truthy but not a string this is likely
456 // an [ 'foo' => true ], falsy values don't add strings
457 $arrayValue[] = $k;
458 }
459 }
460 } else {
461 $arrayValue = explode( ' ', $classes );
462 // Normalize spacing by fixing up cases where people used
463 // more than 1 space and/or a trailing/leading space
464 $arrayValue = array_diff( $arrayValue, [ '', ' ' ] );
465 }
466
467 // Remove duplicates and create the string
468 return implode( ' ', array_unique( $arrayValue ) );
469 }
470
509 public static function expandAttributes( array $attribs ) {
510 $ret = '';
511 foreach ( $attribs as $key => $value ) {
512 // Support intuitive [ 'checked' => true/false ] form
513 if ( $value === false || $value === null ) {
514 continue;
515 }
516
517 // For boolean attributes, support [ 'foo' ] instead of
518 // requiring [ 'foo' => 'meaningless' ].
519 if ( is_int( $key ) && isset( self::BOOL_ATTRIBS[strtolower( $value )] ) ) {
520 $key = $value;
521 }
522
523 // Not technically required in HTML5 but we'd like consistency
524 // and better compression anyway.
525 $key = strtolower( $key );
526
527 // Specific features for attributes that allow a list of space-separated values
528 if ( isset( self::SPACE_SEPARATED_LIST_ATTRIBUTES[$key] ) ) {
529 // Apply some normalization and remove duplicates
530 $value = self::expandClassList( $value );
531
532 // Optimization: Skip below boolAttribs check and jump straight
533 // to its `else` block. The current self::SPACE_SEPARATED_LIST_ATTRIBUTES
534 // block is mutually exclusive with self::BOOL_ATTRIBS.
535 // phpcs:ignore Generic.PHP.DiscourageGoto
536 goto not_bool; // NOSONAR
537 } elseif ( is_array( $value ) ) {
538 throw new UnexpectedValueException( "HTML attribute $key can not contain a list of values" );
539 }
540
541 if ( isset( self::BOOL_ATTRIBS[$key] ) ) {
542 $ret .= " $key=\"\"";
543 } else {
544 // phpcs:ignore Generic.PHP.DiscourageGoto
545 not_bool:
546 // Inlined from Sanitizer::encodeAttribute() for improved performance
547 $encValue = htmlspecialchars( $value, ENT_QUOTES );
548 // Whitespace is normalized during attribute decoding,
549 // so if we've been passed non-spaces we must encode them
550 // ahead of time or they won't be preserved.
551 $encValue = strtr( $encValue, [
552 "\n" => '&#10;',
553 "\r" => '&#13;',
554 "\t" => '&#9;',
555 ] );
556 $ret .= " $key=\"$encValue\"";
557 }
558 }
559 return $ret;
560 }
561
575 public static function inlineScript( $contents, $nonce = null ) {
576 if ( preg_match( '/<\/?script/i', $contents ) ) {
577 wfLogWarning( __METHOD__ . ': Illegal character sequence found in inline script.' );
578 $contents = '/* ERROR: Invalid script */';
579 }
580
581 return self::rawElement( 'script', [], $contents );
582 }
583
592 public static function linkedScript( $url, $nonce = null ) {
593 $attrs = [ 'src' => $url ];
594 if ( $nonce !== null ) {
595 $attrs['nonce'] = $nonce;
596 } elseif ( ContentSecurityPolicy::isNonceRequired( MediaWikiServices::getInstance()->getMainConfig() ) ) {
597 wfWarn( "no nonce set on script. CSP will break it" );
598 }
599
600 return self::element( 'script', $attrs );
601 }
602
615 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
616 // Don't escape '>' since that is used
617 // as direct child selector.
618 // Remember, in css, there is no "x" for hexadecimal escapes, and
619 // the space immediately after an escape sequence is swallowed.
620 $contents = strtr( $contents, [
621 '<' => '\3C ',
622 // CDATA end tag for good measure, but the main security
623 // is from escaping the '<'.
624 ']]>' => '\5D\5D\3E '
625 ] );
626
627 if ( preg_match( '/[<&]/', $contents ) ) {
628 $contents = "/*<![CDATA[*/$contents/*]]>*/";
629 }
630
631 return self::rawElement( 'style', [
632 'media' => $media,
633 ] + $attribs, $contents );
634 }
635
644 public static function linkedStyle( $url, $media = 'all' ) {
645 return self::element( 'link', [
646 'rel' => 'stylesheet',
647 'href' => $url,
648 'media' => $media,
649 ] );
650 }
651
663 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
664 $attribs['type'] = $type;
665 $attribs['value'] = $value;
666 $attribs['name'] = $name;
667 return self::element( 'input', $attribs );
668 }
669
678 public static function check( $name, $checked = false, array $attribs = [] ) {
679 $value = $attribs['value'] ?? 1;
680 unset( $attribs['value'] );
681 return self::element( 'input', [
682 ...$attribs,
683 'checked' => (bool)$checked,
684 'type' => 'checkbox',
685 'value' => $value,
686 'name' => $name,
687 ] );
688 }
689
701 private static function messageBox( $html, $className, $heading = '', $iconClassName = '', array $attribs = [] ) {
702 if ( $heading !== '' ) {
703 $html = self::element( 'h2', [], $heading ) . $html;
704 }
705 self::addClass( $className, 'cdx-message' );
706 self::addClass( $className, 'cdx-message--block' );
707 return self::rawElement( 'div', array_merge( [ 'class' => $className ], $attribs ),
708 self::element( 'span', [ 'class' => [
709 'cdx-message__icon',
710 $iconClassName
711 ] ] ) .
712 self::rawElement( 'div', [
713 'class' => 'cdx-message__content'
714 ], $html )
715 );
716 }
717
733 public static function noticeBox( $html, $className = '', $heading = '', $iconClassName = '' ) {
734 return self::messageBox( $html, [
735 'cdx-message--notice',
736 $className
737 ], $heading, $iconClassName );
738 }
739
754 public static function warningBox( $html, $className = '' ) {
755 return self::messageBox( $html, [
756 'cdx-message--warning', $className ], '', '', [ 'aria-live' => 'polite' ] );
757 }
758
774 public static function errorBox( $html, $heading = '', $className = '' ) {
775 return self::messageBox( $html, [
776 'cdx-message--error', $className ], $heading, '', [ 'role' => 'alert' ] );
777 }
778
793 public static function successBox( $html, $className = '' ) {
794 return self::messageBox( $html, [
795 'cdx-message--success', $className ] );
796 }
797
806 public static function radio( $name, $checked = false, array $attribs = [] ) {
807 $value = $attribs['value'] ?? 1;
808 unset( $attribs['value'] );
809 return self::element( 'input', [
810 ...$attribs,
811 'checked' => (bool)$checked,
812 'type' => 'radio',
813 'value' => $value,
814 'name' => $name,
815 ] );
816 }
817
826 public static function label( $label, $id, array $attribs = [] ) {
827 $attribs += [
828 'for' => $id,
829 ];
830 return self::element( 'label', $attribs, $label );
831 }
832
842 public static function hidden( $name, $value, array $attribs = [] ) {
843 return self::element( 'input', [
844 ...$attribs,
845 'type' => 'hidden',
846 'value' => $value,
847 'name' => $name,
848 ] );
849 }
850
863 public static function textarea( $name, $value = '', array $attribs = [] ) {
864 $attribs['name'] = $name;
865
866 if ( str_starts_with( $value ?? '', "\n" ) ) {
867 // Workaround for T14130: browsers eat the initial newline
868 // assuming that it's just for show, but they do keep the later
869 // newlines, which we may want to preserve during editing.
870 // Prepending a single newline
871 $spacedValue = "\n" . $value;
872 } else {
873 $spacedValue = $value;
874 }
875 return self::element( 'textarea', $attribs, $spacedValue );
876 }
877
883 public static function namespaceSelectorOptions( array $params = [] ) {
884 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
885 $params['exclude'] = [];
886 }
887
888 if ( $params['in-user-lang'] ?? false ) {
889 $lang = RequestContext::getMain()->getLanguage();
890 } else {
891 $lang = MediaWikiServices::getInstance()->getContentLanguage();
892 }
893
894 $optionsOut = [];
895 if ( isset( $params['all'] ) ) {
896 // add an option that would let the user select all namespaces.
897 // Value is provided by user, the name shown is localized for the user.
898 $optionsOut[$params['all']] = wfMessage( 'namespacesall' )->text();
899 }
900 // Add all namespaces as options
901 $options = $lang->getFormattedNamespaces();
902 // Filter out namespaces below 0 and massage labels
903 foreach ( $options as $nsId => $nsName ) {
904 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
905 continue;
906 }
907 if (
908 isset( $params['include'] ) &&
909 is_array( $params['include'] ) &&
910 !in_array( $nsId, $params['include'] )
911 ) {
912 continue;
913 }
914
915 if ( $nsId === NS_MAIN ) {
916 // For other namespaces use the namespace prefix as label, but for
917 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
918 $nsName = wfMessage( 'blanknamespace' )->text();
919 } elseif ( is_int( $nsId ) ) {
920 $converter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
921 ->getLanguageConverter( $lang );
922 $nsName = $converter->convertNamespace( $nsId );
923 }
924 $optionsOut[$nsId] = $nsName;
925 }
926
927 return $optionsOut;
928 }
929
946 public static function namespaceSelector(
947 array $params = [],
948 array $selectAttribs = []
949 ) {
950 ksort( $selectAttribs );
951
952 // Is a namespace selected?
953 if ( isset( $params['selected'] ) ) {
954 // If string only contains digits, convert to clean int. Selected could also
955 // be "all" or "" etc. which needs to be left untouched.
956 if ( !is_int( $params['selected'] ) && ctype_digit( (string)$params['selected'] ) ) {
957 $params['selected'] = (int)$params['selected'];
958 }
959 // else: leaves it untouched for later processing
960 } else {
961 $params['selected'] = '';
962 }
963
964 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
965 $params['disable'] = [];
966 }
967
968 // Associative array between option-values and option-labels
969 $options = self::namespaceSelectorOptions( $params );
970
971 // Convert $options to HTML
972 $optionsHtml = [];
973 foreach ( $options as $nsId => $nsName ) {
974 $optionsHtml[] = self::element(
975 'option',
976 [
977 'disabled' => in_array( $nsId, $params['disable'] ),
978 'value' => $nsId,
979 'selected' => $nsId === $params['selected'],
980 ],
981 $nsName
982 );
983 }
984
985 $selectAttribs['id'] ??= 'namespace';
986 $selectAttribs['name'] ??= 'namespace';
987
988 $label = '';
989 if ( isset( $params['label'] ) ) {
990 $label = self::element( 'label', [ 'for' => $selectAttribs['id'] ],
991 $params['label']
992 ) . "\u{00A0}";
993 }
994
995 // Wrap options in a <select>
996 return $label . self::rawElement( 'select', $selectAttribs,
997 "\n" . implode( "\n", $optionsHtml ) . "\n"
998 );
999 }
1000
1009 public static function htmlHeader( array $attribs = [] ) {
1010 $ret = '';
1011 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1012 $html5Version = $mainConfig->get( MainConfigNames::Html5Version );
1013 $mimeType = $mainConfig->get( MainConfigNames::MimeType );
1014 $xhtmlNamespaces = $mainConfig->get( MainConfigNames::XhtmlNamespaces );
1015
1016 $isXHTML = self::isXmlMimeType( $mimeType );
1017
1018 if ( $isXHTML ) { // XHTML5
1019 // XML MIME-typed markup should have an xml header.
1020 // However a DOCTYPE is not needed.
1021 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
1022
1023 // Add the standard xmlns
1024 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
1025
1026 // And support custom namespaces
1027 foreach ( $xhtmlNamespaces as $tag => $ns ) {
1028 $attribs["xmlns:$tag"] = $ns;
1029 }
1030 } else { // HTML5
1031 $ret .= "<!DOCTYPE html>\n";
1032 }
1033
1034 if ( $html5Version ) {
1035 $attribs['version'] = $html5Version;
1036 }
1037
1038 $ret .= self::openElement( 'html', $attribs );
1039
1040 return $ret;
1041 }
1042
1049 public static function isXmlMimeType( $mimetype ) {
1050 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
1051 # * text/xml
1052 # * application/xml
1053 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1054 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1055 }
1056
1079 public static function srcSet( array $urls ) {
1080 $candidates = [];
1081 foreach ( $urls as $density => $url ) {
1082 // Cast density to float to strip 'x', then back to string to serve
1083 // as array index.
1084 $density = (string)(float)$density;
1085 $candidates[$density] = $url;
1086 }
1087
1088 // Remove duplicates that are the same as a smaller value
1089 ksort( $candidates, SORT_NUMERIC );
1090 $candidates = array_unique( $candidates );
1091
1092 // Append density info to the url
1093 foreach ( $candidates as $density => $url ) {
1094 $candidates[$density] = $url . ' ' . $density . 'x';
1095 }
1096
1097 return implode( ", ", $candidates );
1098 }
1099
1114 public static function encodeJsVar( $value, $pretty = false ) {
1115 if ( $value instanceof HtmlJsCode ) {
1116 return $value->value;
1117 }
1118 return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
1119 }
1120
1135 public static function encodeJsCall( $name, $args, $pretty = false ) {
1136 $encodedArgs = self::encodeJsList( $args, $pretty );
1137 if ( $encodedArgs === false ) {
1138 return false;
1139 }
1140 return "$name($encodedArgs);";
1141 }
1142
1152 public static function encodeJsList( $args, $pretty = false ) {
1153 foreach ( $args as &$arg ) {
1154 $arg = self::encodeJsVar( $arg, $pretty );
1155 if ( $arg === false ) {
1156 return false;
1157 }
1158 }
1159 if ( $pretty ) {
1160 return ' ' . implode( ', ', $args ) . ' ';
1161 } else {
1162 return implode( ',', $args );
1163 }
1164 }
1165
1179 public static function listDropdownOptions( $list, $params = [] ) {
1180 $options = [];
1181
1182 if ( isset( $params['other'] ) ) {
1183 $options[ $params['other'] ] = 'other';
1184 }
1185
1186 $optgroup = false;
1187 foreach ( explode( "\n", $list ) as $option ) {
1188 $value = trim( $option );
1189 if ( $value == '' ) {
1190 continue;
1191 }
1192 if ( str_starts_with( $value, '*' ) && !str_starts_with( $value, '**' ) ) {
1193 # A new group is starting...
1194 $value = trim( substr( $value, 1 ) );
1195 if ( $value !== '' &&
1196 // Do not use the value for 'other' as option group - T251351
1197 ( !isset( $params['other'] ) || $value !== $params['other'] )
1198 ) {
1199 $optgroup = $value;
1200 } else {
1201 $optgroup = false;
1202 }
1203 } elseif ( str_starts_with( $value, '**' ) ) {
1204 # groupmember
1205 $opt = trim( substr( $value, 2 ) );
1206 if ( $optgroup === false ) {
1207 $options[$opt] = $opt;
1208 } else {
1209 $options[$optgroup][$opt] = $opt;
1210 }
1211 } else {
1212 # groupless reason list
1213 $optgroup = false;
1214 $options[$option] = $option;
1215 }
1216 }
1217
1218 return $options;
1219 }
1220
1229 public static function listDropdownOptionsOoui( $options ) {
1230 $optionsOoui = [];
1231
1232 foreach ( $options as $text => $value ) {
1233 if ( is_array( $value ) ) {
1234 $optionsOoui[] = [ 'optgroup' => (string)$text ];
1235 foreach ( $value as $text2 => $value2 ) {
1236 $optionsOoui[] = [ 'data' => (string)$value2, 'label' => (string)$text2 ];
1237 }
1238 } else {
1239 $optionsOoui[] = [ 'data' => (string)$value, 'label' => (string)$text ];
1240 }
1241 }
1242
1243 return $optionsOoui;
1244 }
1245
1254 public static function listDropdownOptionsCodex( $options ) {
1255 $optionsCodex = [];
1256
1257 foreach ( $options as $text => $value ) {
1258 if ( is_array( $value ) ) {
1259 $optionsCodex[] = [
1260 'label' => (string)$text,
1261 'items' => array_map( static function ( $text2, $value2 ) {
1262 return [ 'label' => (string)$text2, 'value' => (string)$value2 ];
1263 }, array_keys( $value ), $value )
1264 ];
1265 } else {
1266 $optionsCodex[] = [ 'label' => (string)$text, 'value' => (string)$value ];
1267 }
1268 }
1269 return $optionsCodex;
1270 }
1271}
const NS_MAIN
Definition Defines.php:51
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.
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:72
A wrapper class which causes Html\encodeJsVar() and Html\encodeJsCall() (as well as their Xml::* coun...
This class is a collection of static functions that serve two purposes:
Definition Html.php:44
static linkedScript( $url, $nonce=null)
Output a "<script>" tag linking to the given URL, e.g., "<script src=foo.js></script>".
Definition Html.php:592
static listDropdownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition Html.php:1229
static namespaceSelector(array $params=[], array $selectAttribs=[])
Build a drop-down box for selecting a namespace.
Definition Html.php:946
static warningBox( $html, $className='')
Return a warning box.
Definition Html.php:754
static check( $name, $checked=false, array $attribs=[])
Convenience function to produce a checkbox (input element with type=checkbox).
Definition Html.php:678
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition Html.php:1114
static listDropdownOptionsCodex( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition Html.php:1254
static label( $label, $id, array $attribs=[])
Convenience function for generating a label for inputs.
Definition Html.php:826
static expandAttributes(array $attribs)
Given an associative array of element attributes, generate a string to stick after the element name i...
Definition Html.php:509
static srcSet(array $urls)
Generate a srcset attribute value.
Definition Html.php:1079
static noticeBox( $html, $className='', $heading='', $iconClassName='')
Return the HTML for a notice message box.
Definition Html.php:733
static successBox( $html, $className='')
Return a success box.
Definition Html.php:793
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition Html.php:1135
static htmlHeader(array $attribs=[])
Constructs the opening html-tag with necessary doctypes depending on global variables.
Definition Html.php:1009
static errorBox( $html, $heading='', $className='')
Return an error box.
Definition Html.php:774
static inlineScript( $contents, $nonce=null)
Output an HTML script tag with the given contents.
Definition Html.php:575
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition Html.php:308
static radio( $name, $checked=false, array $attribs=[])
Convenience function to produce a radio button (input element with type=radio).
Definition Html.php:806
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition Html.php:258
static isXmlMimeType( $mimetype)
Determines if the given MIME type is xml.
Definition Html.php:1049
static expandClassList( $classes)
Convert a value for a 'class' attribute in a format accepted by Html\element() and similar methods to...
Definition Html.php:432
static input( $name, $value='', $type='text', array $attribs=[])
Convenience function to produce an <input> element.
Definition Html.php:663
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition Html.php:842
static textarea( $name, $value='', array $attribs=[])
Convenience function to produce a <textarea> element.
Definition Html.php:863
static namespaceSelectorOptions(array $params=[])
Helper for Html\namespaceSelector().
Definition Html.php:883
static inlineStyle( $contents, $media='all', $attribs=[])
Output a "<style>" tag with the given contents for the given media type (if any).
Definition Html.php:615
static closeElement( $element)
Returns "</$element>".
Definition Html.php:345
static linkButton( $text, array $attrs, array $modifiers=[])
Returns an HTML link element in a string.
Definition Html.php:212
static submitButton( $contents, array $attrs=[], array $modifiers=[])
Returns an HTML input element in a string.
Definition Html.php:230
static encodeJsList( $args, $pretty=false)
Encode a JavaScript comma-separated list.
Definition Html.php:1152
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml\element()).
Definition Html.php:284
static listDropdownOptions( $list, $params=[])
Build options for a drop-down box from a textual list.
Definition Html.php:1179
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:644
static addClass(&$classes, string $class)
Add a class to a 'class' attribute in a format accepted by Html\element().
Definition Html.php:185
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().
static getInstance()
Returns the global default instance of the top level service locator.
element(SerializerNode $parent, SerializerNode $node, $contents)