MediaWiki master
Html.php
Go to the documentation of this file.
1<?php
12namespace MediaWiki\Html;
13
19use UnexpectedValueException;
20
43class Html {
45 private const VOID_ELEMENTS = [
46 'area' => true,
47 'base' => true,
48 'br' => true,
49 'col' => true,
50 'embed' => true,
51 'hr' => true,
52 'img' => true,
53 'input' => true,
54 'keygen' => true,
55 'link' => true,
56 'meta' => true,
57 'param' => true,
58 'source' => true,
59 'track' => true,
60 'wbr' => true,
61 ];
62
67 private const BOOL_ATTRIBS = [
68 'async' => true,
69 'autofocus' => true,
70 'autoplay' => true,
71 'checked' => true,
72 'controls' => true,
73 'default' => true,
74 'defer' => true,
75 'disabled' => true,
76 'formnovalidate' => true,
77 'hidden' => true,
78 'ismap' => true,
79 'itemscope' => true,
80 'loop' => true,
81 'multiple' => true,
82 'muted' => true,
83 'novalidate' => true,
84 'open' => true,
85 'pubdate' => true,
86 'readonly' => true,
87 'required' => true,
88 'reversed' => true,
89 'scoped' => true,
90 'seamless' => true,
91 'selected' => true,
92 'truespeed' => true,
93 'typemustmatch' => true,
94 ];
95
100 private const ATTRIBS_DEFAULTS = [
101 'area' => [ 'shape' => 'rect' ],
102 'button' => [
103 'formaction' => 'GET',
104 'formenctype' => 'application/x-www-form-urlencoded',
105 ],
106 'canvas' => [
107 'height' => '150',
108 'width' => '300',
109 ],
110 'form' => [
111 'action' => 'GET',
112 'autocomplete' => 'on',
113 'enctype' => 'application/x-www-form-urlencoded',
114 ],
115 'input' => [
116 'formaction' => 'GET',
117 'type' => 'text',
118 ],
119 'keygen' => [ 'keytype' => 'rsa' ],
120 'link' => [
121 'media' => 'all',
122 'type' => 'text/css',
123 ],
124 'menu' => [ 'type' => 'list' ],
125 'script' => [ 'type' => 'text/javascript' ],
126 'style' => [
127 'media' => 'all',
128 'type' => 'text/css',
129 ],
130 'textarea' => [ 'wrap' => 'soft' ],
131 ];
132
137 private const SPACE_SEPARATED_LIST_ATTRIBUTES = [
138 'class' => true, // html4, html5
139 'accesskey' => true, // as of html5, multiple space-separated values allowed
140 // html4-spec doesn't document rel= as space-separated
141 // but has been used like that and is now documented as such
142 // in the html5-spec.
143 'rel' => true,
144 ];
145
146 private const INPUT_ELEMENT_VALID_TYPES = [
147 'hidden' => true,
148 'text' => true,
149 'password' => true,
150 'checkbox' => true,
151 'radio' => true,
152 'file' => true,
153 'submit' => true,
154 'image' => true,
155 'reset' => true,
156 'button' => true,
157
158 // HTML input types
159 'datetime' => true,
160 'datetime-local' => true,
161 'date' => true,
162 'month' => true,
163 'time' => true,
164 'week' => true,
165 'number' => true,
166 'range' => true,
167 'email' => true,
168 'url' => true,
169 'search' => true,
170 'tel' => true,
171 'color' => true,
172 ];
173
182 public static function buttonAttributes( array $attrs, array $modifiers = [] ) {
183 wfDeprecated( __METHOD__, '1.42' );
184 return $attrs;
185 }
186
194 public static function getTextInputAttributes( array $attrs ) {
195 wfDeprecated( __METHOD__, '1.42' );
196 return $attrs;
197 }
198
209 public static function addClass( &$classes, string $class ): void {
210 $classes = (array)$classes;
211 // Detect mistakes where $attrs is passed as $classes instead of $attrs['class']
212 foreach ( $classes as $key => $val ) {
213 if (
214 ( is_int( $key ) && is_string( $val ) ) ||
215 ( is_string( $key ) && is_bool( $val ) )
216 ) {
217 // Valid formats for class array entries
218 continue;
219 }
220 wfWarn( __METHOD__ . ": Argument doesn't look like a class array: " . var_export( $classes, true ) );
221 break;
222 }
223 $classes[] = $class;
224 }
225
236 public static function linkButton( $text, array $attrs, array $modifiers = [] ) {
237 return self::element(
238 'a',
239 $attrs,
240 $text
241 );
242 }
243
254 public static function submitButton( $contents, array $attrs = [], array $modifiers = [] ) {
255 $attrs['type'] = 'submit';
256 $attrs['value'] = $contents;
257 return self::element( 'input', $attrs );
258 }
259
282 public static function rawElement( $element, $attribs = [], $contents = '' ) {
283 $start = self::openElement( $element, $attribs );
284 if ( isset( self::VOID_ELEMENTS[$element] ) ) {
285 return $start;
286 } else {
287 $contents = Sanitizer::escapeCombiningChar( $contents ?? '' );
288 return $start . $contents . self::closeElement( $element );
289 }
290 }
291
308 public static function element( $element, $attribs = [], $contents = '' ) {
309 return self::rawElement(
310 $element,
311 $attribs,
312 strtr( $contents ?? '', [
313 // There's no point in escaping quotes, >, etc. in the contents of
314 // elements.
315 '&' => '&amp;',
316 '<' => '&lt;',
317 ] )
318 );
319 }
320
332 public static function openElement( $element, $attribs = [] ) {
333 $attribs = (array)$attribs;
334 // This is not required in HTML5, but let's do it anyway, for
335 // consistency and better compression.
336 $element = strtolower( $element );
337
338 // Some people were abusing this by passing things like
339 // 'h1 id="foo" to $element, which we don't want.
340 if ( str_contains( $element, ' ' ) ) {
341 wfWarn( __METHOD__ . " given element name with space '$element'" );
342 }
343
344 // Remove invalid input types
345 if ( $element == 'input' ) {
346 if ( isset( $attribs['type'] ) && !isset( self::INPUT_ELEMENT_VALID_TYPES[$attribs['type']] ) ) {
347 unset( $attribs['type'] );
348 }
349 }
350
351 // According to standard the default type for <button> elements is "submit".
352 // Depending on compatibility mode IE might use "button", instead.
353 // We enforce the standard "submit".
354 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
355 $attribs['type'] = 'submit';
356 }
357
358 return "<$element" . self::expandAttributes(
359 self::dropDefaults( $element, $attribs ) ) . '>';
360 }
361
369 public static function closeElement( $element ) {
370 $element = strtolower( $element );
371
372 return "</$element>";
373 }
374
392 private static function dropDefaults( $element, array $attribs ) {
393 foreach ( $attribs as $attrib => $value ) {
394 if ( $attrib === 'class' ) {
395 if ( $value === '' || $value === [] || $value === [ '' ] ) {
396 unset( $attribs[$attrib] );
397 }
398 } elseif ( isset( self::ATTRIBS_DEFAULTS[$element][$attrib] ) ) {
399 if ( is_array( $value ) ) {
400 $value = implode( ' ', $value );
401 } else {
402 $value = strval( $value );
403 }
404 if ( self::ATTRIBS_DEFAULTS[$element][$attrib] == $value ) {
405 unset( $attribs[$attrib] );
406 }
407 }
408 }
409
410 // More subtle checks
411 if ( $element === 'input' ) {
412 $type = $attribs['type'] ?? null;
413 $value = $attribs['value'] ?? null;
414 if ( $type === 'checkbox' || $type === 'radio' ) {
415 // The default value for checkboxes and radio buttons is 'on'
416 // not ''. By stripping value="" we break radio boxes that
417 // actually wants empty values.
418 if ( $value === 'on' ) {
419 unset( $attribs['value'] );
420 }
421 } elseif ( $type === 'submit' ) {
422 // The default value for submit appears to be "Submit" but
423 // let's not bother stripping out localized text that matches
424 // that.
425 } else {
426 // The default value for nearly every other field type is ''
427 // The 'range' and 'color' types use different defaults but
428 // stripping a value="" does not hurt them.
429 if ( $value === '' ) {
430 unset( $attribs['value'] );
431 }
432 }
433 }
434 if ( $element === 'select' && isset( $attribs['size'] ) ) {
435 $multiple = ( $attribs['multiple'] ?? false ) !== false ||
436 in_array( 'multiple', $attribs );
437 $default = $multiple ? 4 : 1;
438 if ( (int)$attribs['size'] === $default ) {
439 unset( $attribs['size'] );
440 }
441 }
442
443 return $attribs;
444 }
445
456 public static function expandClassList( $classes ): string {
457 // Convert into correct array. Array can contain space-separated
458 // values. Implode/explode to get those into the main array as well.
459 if ( is_array( $classes ) ) {
460 // If input wasn't an array, we can skip this step
461 $arrayValue = [];
462 foreach ( $classes as $k => $v ) {
463 if ( is_string( $v ) ) {
464 // String values should be normal `[ 'foo' ]`
465 // Just append them
466 if ( !isset( $classes[$v] ) ) {
467 // As a special case don't set 'foo' if a
468 // separate 'foo' => true/false exists in the array
469 // keys should be authoritative
470 foreach ( explode( ' ', $v ) as $part ) {
471 // Normalize spacing by fixing up cases where people used
472 // more than 1 space and/or a trailing/leading space
473 if ( $part !== '' && $part !== ' ' ) {
474 $arrayValue[] = $part;
475 }
476 }
477 }
478 } elseif ( $v ) {
479 // If the value is truthy but not a string this is likely
480 // an [ 'foo' => true ], falsy values don't add strings
481 $arrayValue[] = $k;
482 }
483 }
484 } else {
485 $arrayValue = explode( ' ', $classes );
486 // Normalize spacing by fixing up cases where people used
487 // more than 1 space and/or a trailing/leading space
488 $arrayValue = array_diff( $arrayValue, [ '', ' ' ] );
489 }
490
491 // Remove duplicates and create the string
492 return implode( ' ', array_unique( $arrayValue ) );
493 }
494
533 public static function expandAttributes( array $attribs ) {
534 $ret = '';
535 foreach ( $attribs as $key => $value ) {
536 // Support intuitive [ 'checked' => true/false ] form
537 if ( $value === false || $value === null ) {
538 continue;
539 }
540
541 // For boolean attributes, support [ 'foo' ] instead of
542 // requiring [ 'foo' => 'meaningless' ].
543 if ( is_int( $key ) && isset( self::BOOL_ATTRIBS[strtolower( $value )] ) ) {
544 $key = $value;
545 }
546
547 // Not technically required in HTML5 but we'd like consistency
548 // and better compression anyway.
549 $key = strtolower( $key );
550
551 // Specific features for attributes that allow a list of space-separated values
552 if ( isset( self::SPACE_SEPARATED_LIST_ATTRIBUTES[$key] ) ) {
553 // Apply some normalization and remove duplicates
554 $value = self::expandClassList( $value );
555
556 // Optimization: Skip below boolAttribs check and jump straight
557 // to its `else` block. The current self::SPACE_SEPARATED_LIST_ATTRIBUTES
558 // block is mutually exclusive with self::BOOL_ATTRIBS.
559 // phpcs:ignore Generic.PHP.DiscourageGoto
560 goto not_bool; // NOSONAR
561 } elseif ( is_array( $value ) ) {
562 throw new UnexpectedValueException( "HTML attribute $key can not contain a list of values" );
563 }
564
565 if ( isset( self::BOOL_ATTRIBS[$key] ) ) {
566 $ret .= " $key=\"\"";
567 } else {
568 // phpcs:ignore Generic.PHP.DiscourageGoto
569 not_bool:
570 // Inlined from Sanitizer::encodeAttribute() for improved performance
571 $encValue = htmlspecialchars( $value, ENT_QUOTES );
572 // Whitespace is normalized during attribute decoding,
573 // so if we've been passed non-spaces we must encode them
574 // ahead of time or they won't be preserved.
575 $encValue = strtr( $encValue, [
576 "\n" => '&#10;',
577 "\r" => '&#13;',
578 "\t" => '&#9;',
579 ] );
580 $ret .= " $key=\"$encValue\"";
581 }
582 }
583 return $ret;
584 }
585
599 public static function inlineScript( $contents, $nonce = null ) {
600 if ( preg_match( '/<\/?script/i', $contents ) ) {
601 wfLogWarning( __METHOD__ . ': Illegal character sequence found in inline script.' );
602 $contents = '/* ERROR: Invalid script */';
603 }
604
605 return self::rawElement( 'script', [], $contents );
606 }
607
616 public static function linkedScript( $url, $nonce = null ) {
617 $attrs = [ 'src' => $url ];
618 if ( $nonce !== null ) {
619 $attrs['nonce'] = $nonce;
620 } elseif ( ContentSecurityPolicy::isNonceRequired( MediaWikiServices::getInstance()->getMainConfig() ) ) {
621 wfWarn( "no nonce set on script. CSP will break it" );
622 }
623
624 return self::element( 'script', $attrs );
625 }
626
639 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
640 // Don't escape '>' since that is used
641 // as direct child selector.
642 // Remember, in css, there is no "x" for hexadecimal escapes, and
643 // the space immediately after an escape sequence is swallowed.
644 $contents = strtr( $contents, [
645 '<' => '\3C ',
646 // CDATA end tag for good measure, but the main security
647 // is from escaping the '<'.
648 ']]>' => '\5D\5D\3E '
649 ] );
650
651 if ( preg_match( '/[<&]/', $contents ) ) {
652 $contents = "/*<![CDATA[*/$contents/*]]>*/";
653 }
654
655 return self::rawElement( 'style', [
656 'media' => $media,
657 ] + $attribs, $contents );
658 }
659
668 public static function linkedStyle( $url, $media = 'all' ) {
669 return self::element( 'link', [
670 'rel' => 'stylesheet',
671 'href' => $url,
672 'media' => $media,
673 ] );
674 }
675
687 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
688 $attribs['type'] = $type;
689 $attribs['value'] = $value;
690 $attribs['name'] = $name;
691 return self::element( 'input', $attribs );
692 }
693
702 public static function check( $name, $checked = false, array $attribs = [] ) {
703 $value = $attribs['value'] ?? 1;
704 unset( $attribs['value'] );
705 return self::element( 'input', [
706 ...$attribs,
707 'checked' => (bool)$checked,
708 'type' => 'checkbox',
709 'value' => $value,
710 'name' => $name,
711 ] );
712 }
713
724 private static function messageBox( $html, $className, $heading = '', $iconClassName = '' ) {
725 if ( $heading !== '' ) {
726 $html = self::element( 'h2', [], $heading ) . $html;
727 }
728 self::addClass( $className, 'cdx-message' );
729 self::addClass( $className, 'cdx-message--block' );
730 return self::rawElement( 'div', [ 'class' => $className ],
731 self::element( 'span', [ 'class' => [
732 'cdx-message__icon',
733 $iconClassName
734 ] ] ) .
735 self::rawElement( 'div', [
736 'class' => 'cdx-message__content'
737 ], $html )
738 );
739 }
740
756 public static function noticeBox( $html, $className = '', $heading = '', $iconClassName = '' ) {
757 return self::messageBox( $html, [
758 'cdx-message--notice',
759 $className
760 ], $heading, $iconClassName );
761 }
762
777 public static function warningBox( $html, $className = '' ) {
778 return self::messageBox( $html, [
779 'cdx-message--warning', $className ] );
780 }
781
797 public static function errorBox( $html, $heading = '', $className = '' ) {
798 return self::messageBox( $html, [
799 'cdx-message--error', $className ], $heading );
800 }
801
816 public static function successBox( $html, $className = '' ) {
817 return self::messageBox( $html, [
818 'cdx-message--success', $className ] );
819 }
820
829 public static function radio( $name, $checked = false, array $attribs = [] ) {
830 $value = $attribs['value'] ?? 1;
831 unset( $attribs['value'] );
832 return self::element( 'input', [
833 ...$attribs,
834 'checked' => (bool)$checked,
835 'type' => 'radio',
836 'value' => $value,
837 'name' => $name,
838 ] );
839 }
840
849 public static function label( $label, $id, array $attribs = [] ) {
850 $attribs += [
851 'for' => $id,
852 ];
853 return self::element( 'label', $attribs, $label );
854 }
855
865 public static function hidden( $name, $value, array $attribs = [] ) {
866 return self::element( 'input', [
867 ...$attribs,
868 'type' => 'hidden',
869 'value' => $value,
870 'name' => $name,
871 ] );
872 }
873
886 public static function textarea( $name, $value = '', array $attribs = [] ) {
887 $attribs['name'] = $name;
888
889 if ( str_starts_with( $value ?? '', "\n" ) ) {
890 // Workaround for T14130: browsers eat the initial newline
891 // assuming that it's just for show, but they do keep the later
892 // newlines, which we may want to preserve during editing.
893 // Prepending a single newline
894 $spacedValue = "\n" . $value;
895 } else {
896 $spacedValue = $value;
897 }
898 return self::element( 'textarea', $attribs, $spacedValue );
899 }
900
906 public static function namespaceSelectorOptions( array $params = [] ) {
907 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
908 $params['exclude'] = [];
909 }
910
911 if ( $params['in-user-lang'] ?? false ) {
912 global $wgLang;
913 $lang = $wgLang;
914 } else {
915 $lang = MediaWikiServices::getInstance()->getContentLanguage();
916 }
917
918 $optionsOut = [];
919 if ( isset( $params['all'] ) ) {
920 // add an option that would let the user select all namespaces.
921 // Value is provided by user, the name shown is localized for the user.
922 $optionsOut[$params['all']] = wfMessage( 'namespacesall' )->text();
923 }
924 // Add all namespaces as options
925 $options = $lang->getFormattedNamespaces();
926 // Filter out namespaces below 0 and massage labels
927 foreach ( $options as $nsId => $nsName ) {
928 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
929 continue;
930 }
931 if (
932 isset( $params['include'] ) &&
933 is_array( $params['include'] ) &&
934 !in_array( $nsId, $params['include'] )
935 ) {
936 continue;
937 }
938
939 if ( $nsId === NS_MAIN ) {
940 // For other namespaces use the namespace prefix as label, but for
941 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
942 $nsName = wfMessage( 'blanknamespace' )->text();
943 } elseif ( is_int( $nsId ) ) {
944 $converter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
945 ->getLanguageConverter( $lang );
946 $nsName = $converter->convertNamespace( $nsId );
947 }
948 $optionsOut[$nsId] = $nsName;
949 }
950
951 return $optionsOut;
952 }
953
970 public static function namespaceSelector(
971 array $params = [],
972 array $selectAttribs = []
973 ) {
974 ksort( $selectAttribs );
975
976 // Is a namespace selected?
977 if ( isset( $params['selected'] ) ) {
978 // If string only contains digits, convert to clean int. Selected could also
979 // be "all" or "" etc. which needs to be left untouched.
980 if ( !is_int( $params['selected'] ) && ctype_digit( (string)$params['selected'] ) ) {
981 $params['selected'] = (int)$params['selected'];
982 }
983 // else: leaves it untouched for later processing
984 } else {
985 $params['selected'] = '';
986 }
987
988 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
989 $params['disable'] = [];
990 }
991
992 // Associative array between option-values and option-labels
993 $options = self::namespaceSelectorOptions( $params );
994
995 // Convert $options to HTML
996 $optionsHtml = [];
997 foreach ( $options as $nsId => $nsName ) {
998 $optionsHtml[] = self::element(
999 'option',
1000 [
1001 'disabled' => in_array( $nsId, $params['disable'] ),
1002 'value' => $nsId,
1003 'selected' => $nsId === $params['selected'],
1004 ],
1005 $nsName
1006 );
1007 }
1008
1009 $selectAttribs['id'] ??= 'namespace';
1010 $selectAttribs['name'] ??= 'namespace';
1011
1012 $label = '';
1013 if ( isset( $params['label'] ) ) {
1014 $label = self::element( 'label', [ 'for' => $selectAttribs['id'] ],
1015 $params['label']
1016 ) . "\u{00A0}";
1017 }
1018
1019 // Wrap options in a <select>
1020 return $label . self::rawElement( 'select', $selectAttribs,
1021 "\n" . implode( "\n", $optionsHtml ) . "\n"
1022 );
1023 }
1024
1033 public static function htmlHeader( array $attribs = [] ) {
1034 $ret = '';
1035 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1036 $html5Version = $mainConfig->get( MainConfigNames::Html5Version );
1037 $mimeType = $mainConfig->get( MainConfigNames::MimeType );
1038 $xhtmlNamespaces = $mainConfig->get( MainConfigNames::XhtmlNamespaces );
1039
1040 $isXHTML = self::isXmlMimeType( $mimeType );
1041
1042 if ( $isXHTML ) { // XHTML5
1043 // XML MIME-typed markup should have an xml header.
1044 // However a DOCTYPE is not needed.
1045 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
1046
1047 // Add the standard xmlns
1048 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
1049
1050 // And support custom namespaces
1051 foreach ( $xhtmlNamespaces as $tag => $ns ) {
1052 $attribs["xmlns:$tag"] = $ns;
1053 }
1054 } else { // HTML5
1055 $ret .= "<!DOCTYPE html>\n";
1056 }
1057
1058 if ( $html5Version ) {
1059 $attribs['version'] = $html5Version;
1060 }
1061
1062 $ret .= self::openElement( 'html', $attribs );
1063
1064 return $ret;
1065 }
1066
1073 public static function isXmlMimeType( $mimetype ) {
1074 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
1075 # * text/xml
1076 # * application/xml
1077 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1078 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1079 }
1080
1104 public static function srcSet( array $urls ) {
1105 $candidates = [];
1106 foreach ( $urls as $density => $url ) {
1107 // Cast density to float to strip 'x', then back to string to serve
1108 // as array index.
1109 $density = (string)(float)$density;
1110 $candidates[$density] = $url;
1111 }
1112
1113 // Remove duplicates that are the same as a smaller value
1114 ksort( $candidates, SORT_NUMERIC );
1115 $candidates = array_unique( $candidates );
1116
1117 // Append density info to the url
1118 foreach ( $candidates as $density => $url ) {
1119 $candidates[$density] = $url . ' ' . $density . 'x';
1120 }
1121
1122 return implode( ", ", $candidates );
1123 }
1124
1139 public static function encodeJsVar( $value, $pretty = false ) {
1140 if ( $value instanceof HtmlJsCode ) {
1141 return $value->value;
1142 }
1143 return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
1144 }
1145
1160 public static function encodeJsCall( $name, $args, $pretty = false ) {
1161 $encodedArgs = self::encodeJsList( $args, $pretty );
1162 if ( $encodedArgs === false ) {
1163 return false;
1164 }
1165 return "$name($encodedArgs);";
1166 }
1167
1177 public static function encodeJsList( $args, $pretty = false ) {
1178 foreach ( $args as &$arg ) {
1179 $arg = self::encodeJsVar( $arg, $pretty );
1180 if ( $arg === false ) {
1181 return false;
1182 }
1183 }
1184 if ( $pretty ) {
1185 return ' ' . implode( ', ', $args ) . ' ';
1186 } else {
1187 return implode( ',', $args );
1188 }
1189 }
1190
1204 public static function listDropdownOptions( $list, $params = [] ) {
1205 $options = [];
1206
1207 if ( isset( $params['other'] ) ) {
1208 $options[ $params['other'] ] = 'other';
1209 }
1210
1211 $optgroup = false;
1212 foreach ( explode( "\n", $list ) as $option ) {
1213 $value = trim( $option );
1214 if ( $value == '' ) {
1215 continue;
1216 }
1217 if ( str_starts_with( $value, '*' ) && !str_starts_with( $value, '**' ) ) {
1218 # A new group is starting...
1219 $value = trim( substr( $value, 1 ) );
1220 if ( $value !== '' &&
1221 // Do not use the value for 'other' as option group - T251351
1222 ( !isset( $params['other'] ) || $value !== $params['other'] )
1223 ) {
1224 $optgroup = $value;
1225 } else {
1226 $optgroup = false;
1227 }
1228 } elseif ( str_starts_with( $value, '**' ) ) {
1229 # groupmember
1230 $opt = trim( substr( $value, 2 ) );
1231 if ( $optgroup === false ) {
1232 $options[$opt] = $opt;
1233 } else {
1234 $options[$optgroup][$opt] = $opt;
1235 }
1236 } else {
1237 # groupless reason list
1238 $optgroup = false;
1239 $options[$option] = $option;
1240 }
1241 }
1242
1243 return $options;
1244 }
1245
1254 public static function listDropdownOptionsOoui( $options ) {
1255 $optionsOoui = [];
1256
1257 foreach ( $options as $text => $value ) {
1258 if ( is_array( $value ) ) {
1259 $optionsOoui[] = [ 'optgroup' => (string)$text ];
1260 foreach ( $value as $text2 => $value2 ) {
1261 $optionsOoui[] = [ 'data' => (string)$value2, 'label' => (string)$text2 ];
1262 }
1263 } else {
1264 $optionsOoui[] = [ 'data' => (string)$value, 'label' => (string)$text ];
1265 }
1266 }
1267
1268 return $optionsOoui;
1269 }
1270
1279 public static function listDropdownOptionsCodex( $options ) {
1280 $optionsCodex = [];
1281
1282 foreach ( $options as $text => $value ) {
1283 if ( is_array( $value ) ) {
1284 $optionsCodex[] = [
1285 'label' => (string)$text,
1286 'items' => array_map( static function ( $text2, $value2 ) {
1287 return [ 'label' => (string)$text2, 'value' => (string)$value2 ];
1288 }, array_keys( $value ), $value )
1289 ];
1290 } else {
1291 $optionsCodex[] = [ 'label' => (string)$text, 'value' => (string)$value ];
1292 }
1293 }
1294 return $optionsCodex;
1295 }
1296}
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.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
if(MW_ENTRY_POINT==='index') if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgLang
Definition Setup.php:551
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:69
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:43
static linkedScript( $url, $nonce=null)
Output a "<script>" tag linking to the given URL, e.g., "<script src=foo.js></script>".
Definition Html.php:616
static listDropdownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition Html.php:1254
static namespaceSelector(array $params=[], array $selectAttribs=[])
Build a drop-down box for selecting a namespace.
Definition Html.php:970
static warningBox( $html, $className='')
Return a warning box.
Definition Html.php:777
static check( $name, $checked=false, array $attribs=[])
Convenience function to produce a checkbox (input element with type=checkbox)
Definition Html.php:702
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition Html.php:1139
static listDropdownOptionsCodex( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition Html.php:1279
static label( $label, $id, array $attribs=[])
Convenience function for generating a label for inputs.
Definition Html.php:849
static expandAttributes(array $attribs)
Given an associative array of element attributes, generate a string to stick after the element name i...
Definition Html.php:533
static srcSet(array $urls)
Generate a srcset attribute value.
Definition Html.php:1104
static noticeBox( $html, $className='', $heading='', $iconClassName='')
Return the HTML for a notice message box.
Definition Html.php:756
static successBox( $html, $className='')
Return a success box.
Definition Html.php:816
static buttonAttributes(array $attrs, array $modifiers=[])
Modifies a set of attributes meant for button elements.
Definition Html.php:182
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition Html.php:1160
static htmlHeader(array $attribs=[])
Constructs the opening html-tag with necessary doctypes depending on global variables.
Definition Html.php:1033
static errorBox( $html, $heading='', $className='')
Return an error box.
Definition Html.php:797
static inlineScript( $contents, $nonce=null)
Output an HTML script tag with the given contents.
Definition Html.php:599
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition Html.php:332
static radio( $name, $checked=false, array $attribs=[])
Convenience function to produce a radio button (input element with type=radio)
Definition Html.php:829
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition Html.php:282
static isXmlMimeType( $mimetype)
Determines if the given MIME type is xml.
Definition Html.php:1073
static getTextInputAttributes(array $attrs)
Modifies a set of attributes meant for text input elements.
Definition Html.php:194
static expandClassList( $classes)
Convert a value for a 'class' attribute in a format accepted by Html::element() and similar methods t...
Definition Html.php:456
static input( $name, $value='', $type='text', array $attribs=[])
Convenience function to produce an <input> element.
Definition Html.php:687
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition Html.php:865
static textarea( $name, $value='', array $attribs=[])
Convenience function to produce a <textarea> element.
Definition Html.php:886
static namespaceSelectorOptions(array $params=[])
Helper for Html::namespaceSelector().
Definition Html.php:906
static inlineStyle( $contents, $media='all', $attribs=[])
Output a "<style>" tag with the given contents for the given media type (if any).
Definition Html.php:639
static closeElement( $element)
Returns "</$element>".
Definition Html.php:369
static linkButton( $text, array $attrs, array $modifiers=[])
Returns an HTML link element in a string.
Definition Html.php:236
static submitButton( $contents, array $attrs=[], array $modifiers=[])
Returns an HTML input element in a string.
Definition Html.php:254
static encodeJsList( $args, $pretty=false)
Encode a JavaScript comma-separated list.
Definition Html.php:1177
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition Html.php:308
static listDropdownOptions( $list, $params=[])
Build options for a drop-down box from a textual list.
Definition Html.php:1204
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:668
static addClass(&$classes, string $class)
Add a class to a 'class' attribute in a format accepted by Html::element().
Definition Html.php:209
JSON formatter wrapper class.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
HTML sanitizer for MediaWiki.
Definition Sanitizer.php:32
Handle sending Content-Security-Policy headers.
element(SerializerNode $parent, SerializerNode $node, $contents)