MediaWiki master
Html.php
Go to the documentation of this file.
1<?php
12namespace MediaWiki\Html;
13
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
183 public static function buttonAttributes( array $attrs, array $modifiers = [] ) {
184 wfDeprecated( __METHOD__, '1.42' );
185 return $attrs;
186 }
187
195 public static function getTextInputAttributes( array $attrs ) {
196 wfDeprecated( __METHOD__, '1.42' );
197 return $attrs;
198 }
199
210 public static function addClass( &$classes, string $class ): void {
211 $classes = (array)$classes;
212 // Detect mistakes where $attrs is passed as $classes instead of $attrs['class']
213 foreach ( $classes as $key => $val ) {
214 if (
215 ( is_int( $key ) && is_string( $val ) ) ||
216 ( is_string( $key ) && is_bool( $val ) )
217 ) {
218 // Valid formats for class array entries
219 continue;
220 }
221 wfWarn( __METHOD__ . ": Argument doesn't look like a class array: " . var_export( $classes, true ) );
222 break;
223 }
224 $classes[] = $class;
225 }
226
237 public static function linkButton( $text, array $attrs, array $modifiers = [] ) {
238 return self::element(
239 'a',
240 $attrs,
241 $text
242 );
243 }
244
255 public static function submitButton( $contents, array $attrs = [], array $modifiers = [] ) {
256 $attrs['type'] = 'submit';
257 $attrs['value'] = $contents;
258 return self::element( 'input', $attrs );
259 }
260
283 public static function rawElement( $element, $attribs = [], $contents = '' ) {
284 $start = self::openElement( $element, $attribs );
285 if ( isset( self::VOID_ELEMENTS[$element] ) ) {
286 return $start;
287 } else {
288 $contents = Sanitizer::escapeCombiningChar( $contents ?? '' );
289 return $start . $contents . self::closeElement( $element );
290 }
291 }
292
309 public static function element( $element, $attribs = [], $contents = '' ) {
310 return self::rawElement(
311 $element,
312 $attribs,
313 strtr( $contents ?? '', [
314 // There's no point in escaping quotes, >, etc. in the contents of
315 // elements.
316 '&' => '&amp;',
317 '<' => '&lt;',
318 ] )
319 );
320 }
321
333 public static function openElement( $element, $attribs = [] ) {
334 $attribs = (array)$attribs;
335 // This is not required in HTML5, but let's do it anyway, for
336 // consistency and better compression.
337 $element = strtolower( $element );
338
339 // Some people were abusing this by passing things like
340 // 'h1 id="foo" to $element, which we don't want.
341 if ( str_contains( $element, ' ' ) ) {
342 wfWarn( __METHOD__ . " given element name with space '$element'" );
343 }
344
345 // Remove invalid input types
346 if ( $element == 'input' ) {
347 if ( isset( $attribs['type'] ) && !isset( self::INPUT_ELEMENT_VALID_TYPES[$attribs['type']] ) ) {
348 unset( $attribs['type'] );
349 }
350 }
351
352 // According to standard the default type for <button> elements is "submit".
353 // Depending on compatibility mode IE might use "button", instead.
354 // We enforce the standard "submit".
355 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
356 $attribs['type'] = 'submit';
357 }
358
359 return "<$element" . self::expandAttributes(
360 self::dropDefaults( $element, $attribs ) ) . '>';
361 }
362
370 public static function closeElement( $element ) {
371 $element = strtolower( $element );
372
373 return "</$element>";
374 }
375
393 private static function dropDefaults( $element, array $attribs ) {
394 foreach ( $attribs as $attrib => $value ) {
395 if ( $attrib === 'class' ) {
396 if ( $value === '' || $value === [] || $value === [ '' ] ) {
397 unset( $attribs[$attrib] );
398 }
399 } elseif ( isset( self::ATTRIBS_DEFAULTS[$element][$attrib] ) ) {
400 if ( is_array( $value ) ) {
401 $value = implode( ' ', $value );
402 } else {
403 $value = strval( $value );
404 }
405 if ( self::ATTRIBS_DEFAULTS[$element][$attrib] == $value ) {
406 unset( $attribs[$attrib] );
407 }
408 }
409 }
410
411 // More subtle checks
412 if ( $element === 'input' ) {
413 $type = $attribs['type'] ?? null;
414 $value = $attribs['value'] ?? null;
415 if ( $type === 'checkbox' || $type === 'radio' ) {
416 // The default value for checkboxes and radio buttons is 'on'
417 // not ''. By stripping value="" we break radio boxes that
418 // actually wants empty values.
419 if ( $value === 'on' ) {
420 unset( $attribs['value'] );
421 }
422 } elseif ( $type === 'submit' ) {
423 // The default value for submit appears to be "Submit" but
424 // let's not bother stripping out localized text that matches
425 // that.
426 } else {
427 // The default value for nearly every other field type is ''
428 // The 'range' and 'color' types use different defaults but
429 // stripping a value="" does not hurt them.
430 if ( $value === '' ) {
431 unset( $attribs['value'] );
432 }
433 }
434 }
435 if ( $element === 'select' && isset( $attribs['size'] ) ) {
436 $multiple = ( $attribs['multiple'] ?? false ) !== false ||
437 in_array( 'multiple', $attribs );
438 $default = $multiple ? 4 : 1;
439 if ( (int)$attribs['size'] === $default ) {
440 unset( $attribs['size'] );
441 }
442 }
443
444 return $attribs;
445 }
446
457 public static function expandClassList( $classes ): string {
458 // Convert into correct array. Array can contain space-separated
459 // values. Implode/explode to get those into the main array as well.
460 if ( is_array( $classes ) ) {
461 // If input wasn't an array, we can skip this step
462 $arrayValue = [];
463 foreach ( $classes as $k => $v ) {
464 if ( is_string( $v ) ) {
465 // String values should be normal `[ 'foo' ]`
466 // Just append them
467 if ( !isset( $classes[$v] ) ) {
468 // As a special case don't set 'foo' if a
469 // separate 'foo' => true/false exists in the array
470 // keys should be authoritative
471 foreach ( explode( ' ', $v ) as $part ) {
472 // Normalize spacing by fixing up cases where people used
473 // more than 1 space and/or a trailing/leading space
474 if ( $part !== '' && $part !== ' ' ) {
475 $arrayValue[] = $part;
476 }
477 }
478 }
479 } elseif ( $v ) {
480 // If the value is truthy but not a string this is likely
481 // an [ 'foo' => true ], falsy values don't add strings
482 $arrayValue[] = $k;
483 }
484 }
485 } else {
486 $arrayValue = explode( ' ', $classes );
487 // Normalize spacing by fixing up cases where people used
488 // more than 1 space and/or a trailing/leading space
489 $arrayValue = array_diff( $arrayValue, [ '', ' ' ] );
490 }
491
492 // Remove duplicates and create the string
493 return implode( ' ', array_unique( $arrayValue ) );
494 }
495
534 public static function expandAttributes( array $attribs ) {
535 $ret = '';
536 foreach ( $attribs as $key => $value ) {
537 // Support intuitive [ 'checked' => true/false ] form
538 if ( $value === false || $value === null ) {
539 continue;
540 }
541
542 // For boolean attributes, support [ 'foo' ] instead of
543 // requiring [ 'foo' => 'meaningless' ].
544 if ( is_int( $key ) && isset( self::BOOL_ATTRIBS[strtolower( $value )] ) ) {
545 $key = $value;
546 }
547
548 // Not technically required in HTML5 but we'd like consistency
549 // and better compression anyway.
550 $key = strtolower( $key );
551
552 // Specific features for attributes that allow a list of space-separated values
553 if ( isset( self::SPACE_SEPARATED_LIST_ATTRIBUTES[$key] ) ) {
554 // Apply some normalization and remove duplicates
555 $value = self::expandClassList( $value );
556
557 // Optimization: Skip below boolAttribs check and jump straight
558 // to its `else` block. The current self::SPACE_SEPARATED_LIST_ATTRIBUTES
559 // block is mutually exclusive with self::BOOL_ATTRIBS.
560 // phpcs:ignore Generic.PHP.DiscourageGoto
561 goto not_bool; // NOSONAR
562 } elseif ( is_array( $value ) ) {
563 throw new UnexpectedValueException( "HTML attribute $key can not contain a list of values" );
564 }
565
566 if ( isset( self::BOOL_ATTRIBS[$key] ) ) {
567 $ret .= " $key=\"\"";
568 } else {
569 // phpcs:ignore Generic.PHP.DiscourageGoto
570 not_bool:
571 // Inlined from Sanitizer::encodeAttribute() for improved performance
572 $encValue = htmlspecialchars( $value, ENT_QUOTES );
573 // Whitespace is normalized during attribute decoding,
574 // so if we've been passed non-spaces we must encode them
575 // ahead of time or they won't be preserved.
576 $encValue = strtr( $encValue, [
577 "\n" => '&#10;',
578 "\r" => '&#13;',
579 "\t" => '&#9;',
580 ] );
581 $ret .= " $key=\"$encValue\"";
582 }
583 }
584 return $ret;
585 }
586
600 public static function inlineScript( $contents, $nonce = null ) {
601 if ( preg_match( '/<\/?script/i', $contents ) ) {
602 wfLogWarning( __METHOD__ . ': Illegal character sequence found in inline script.' );
603 $contents = '/* ERROR: Invalid script */';
604 }
605
606 return self::rawElement( 'script', [], $contents );
607 }
608
617 public static function linkedScript( $url, $nonce = null ) {
618 $attrs = [ 'src' => $url ];
619 if ( $nonce !== null ) {
620 $attrs['nonce'] = $nonce;
621 } elseif ( ContentSecurityPolicy::isNonceRequired( MediaWikiServices::getInstance()->getMainConfig() ) ) {
622 wfWarn( "no nonce set on script. CSP will break it" );
623 }
624
625 return self::element( 'script', $attrs );
626 }
627
640 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
641 // Don't escape '>' since that is used
642 // as direct child selector.
643 // Remember, in css, there is no "x" for hexadecimal escapes, and
644 // the space immediately after an escape sequence is swallowed.
645 $contents = strtr( $contents, [
646 '<' => '\3C ',
647 // CDATA end tag for good measure, but the main security
648 // is from escaping the '<'.
649 ']]>' => '\5D\5D\3E '
650 ] );
651
652 if ( preg_match( '/[<&]/', $contents ) ) {
653 $contents = "/*<![CDATA[*/$contents/*]]>*/";
654 }
655
656 return self::rawElement( 'style', [
657 'media' => $media,
658 ] + $attribs, $contents );
659 }
660
669 public static function linkedStyle( $url, $media = 'all' ) {
670 return self::element( 'link', [
671 'rel' => 'stylesheet',
672 'href' => $url,
673 'media' => $media,
674 ] );
675 }
676
688 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
689 $attribs['type'] = $type;
690 $attribs['value'] = $value;
691 $attribs['name'] = $name;
692 return self::element( 'input', $attribs );
693 }
694
703 public static function check( $name, $checked = false, array $attribs = [] ) {
704 $value = $attribs['value'] ?? 1;
705 unset( $attribs['value'] );
706 return self::element( 'input', [
707 ...$attribs,
708 'checked' => (bool)$checked,
709 'type' => 'checkbox',
710 'value' => $value,
711 'name' => $name,
712 ] );
713 }
714
726 private static function messageBox( $html, $className, $heading = '', $iconClassName = '', array $attribs = [] ) {
727 if ( $heading !== '' ) {
728 $html = self::element( 'h2', [], $heading ) . $html;
729 }
730 self::addClass( $className, 'cdx-message' );
731 self::addClass( $className, 'cdx-message--block' );
732 return self::rawElement( 'div', array_merge( [ 'class' => $className ], $attribs ),
733 self::element( 'span', [ 'class' => [
734 'cdx-message__icon',
735 $iconClassName
736 ] ] ) .
737 self::rawElement( 'div', [
738 'class' => 'cdx-message__content'
739 ], $html )
740 );
741 }
742
758 public static function noticeBox( $html, $className = '', $heading = '', $iconClassName = '' ) {
759 return self::messageBox( $html, [
760 'cdx-message--notice',
761 $className
762 ], $heading, $iconClassName );
763 }
764
779 public static function warningBox( $html, $className = '' ) {
780 return self::messageBox( $html, [
781 'cdx-message--warning', $className ], '', '', [ 'aria-live' => 'polite' ] );
782 }
783
799 public static function errorBox( $html, $heading = '', $className = '' ) {
800 return self::messageBox( $html, [
801 'cdx-message--error', $className ], $heading, '', [ 'role' => 'alert' ] );
802 }
803
818 public static function successBox( $html, $className = '' ) {
819 return self::messageBox( $html, [
820 'cdx-message--success', $className ] );
821 }
822
831 public static function radio( $name, $checked = false, array $attribs = [] ) {
832 $value = $attribs['value'] ?? 1;
833 unset( $attribs['value'] );
834 return self::element( 'input', [
835 ...$attribs,
836 'checked' => (bool)$checked,
837 'type' => 'radio',
838 'value' => $value,
839 'name' => $name,
840 ] );
841 }
842
851 public static function label( $label, $id, array $attribs = [] ) {
852 $attribs += [
853 'for' => $id,
854 ];
855 return self::element( 'label', $attribs, $label );
856 }
857
867 public static function hidden( $name, $value, array $attribs = [] ) {
868 return self::element( 'input', [
869 ...$attribs,
870 'type' => 'hidden',
871 'value' => $value,
872 'name' => $name,
873 ] );
874 }
875
888 public static function textarea( $name, $value = '', array $attribs = [] ) {
889 $attribs['name'] = $name;
890
891 if ( str_starts_with( $value ?? '', "\n" ) ) {
892 // Workaround for T14130: browsers eat the initial newline
893 // assuming that it's just for show, but they do keep the later
894 // newlines, which we may want to preserve during editing.
895 // Prepending a single newline
896 $spacedValue = "\n" . $value;
897 } else {
898 $spacedValue = $value;
899 }
900 return self::element( 'textarea', $attribs, $spacedValue );
901 }
902
908 public static function namespaceSelectorOptions( array $params = [] ) {
909 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
910 $params['exclude'] = [];
911 }
912
913 if ( $params['in-user-lang'] ?? false ) {
914 $lang = RequestContext::getMain()->getLanguage();
915 } else {
916 $lang = MediaWikiServices::getInstance()->getContentLanguage();
917 }
918
919 $optionsOut = [];
920 if ( isset( $params['all'] ) ) {
921 // add an option that would let the user select all namespaces.
922 // Value is provided by user, the name shown is localized for the user.
923 $optionsOut[$params['all']] = wfMessage( 'namespacesall' )->text();
924 }
925 // Add all namespaces as options
926 $options = $lang->getFormattedNamespaces();
927 // Filter out namespaces below 0 and massage labels
928 foreach ( $options as $nsId => $nsName ) {
929 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
930 continue;
931 }
932 if (
933 isset( $params['include'] ) &&
934 is_array( $params['include'] ) &&
935 !in_array( $nsId, $params['include'] )
936 ) {
937 continue;
938 }
939
940 if ( $nsId === NS_MAIN ) {
941 // For other namespaces use the namespace prefix as label, but for
942 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
943 $nsName = wfMessage( 'blanknamespace' )->text();
944 } elseif ( is_int( $nsId ) ) {
945 $converter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
946 ->getLanguageConverter( $lang );
947 $nsName = $converter->convertNamespace( $nsId );
948 }
949 $optionsOut[$nsId] = $nsName;
950 }
951
952 return $optionsOut;
953 }
954
971 public static function namespaceSelector(
972 array $params = [],
973 array $selectAttribs = []
974 ) {
975 ksort( $selectAttribs );
976
977 // Is a namespace selected?
978 if ( isset( $params['selected'] ) ) {
979 // If string only contains digits, convert to clean int. Selected could also
980 // be "all" or "" etc. which needs to be left untouched.
981 if ( !is_int( $params['selected'] ) && ctype_digit( (string)$params['selected'] ) ) {
982 $params['selected'] = (int)$params['selected'];
983 }
984 // else: leaves it untouched for later processing
985 } else {
986 $params['selected'] = '';
987 }
988
989 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
990 $params['disable'] = [];
991 }
992
993 // Associative array between option-values and option-labels
994 $options = self::namespaceSelectorOptions( $params );
995
996 // Convert $options to HTML
997 $optionsHtml = [];
998 foreach ( $options as $nsId => $nsName ) {
999 $optionsHtml[] = self::element(
1000 'option',
1001 [
1002 'disabled' => in_array( $nsId, $params['disable'] ),
1003 'value' => $nsId,
1004 'selected' => $nsId === $params['selected'],
1005 ],
1006 $nsName
1007 );
1008 }
1009
1010 $selectAttribs['id'] ??= 'namespace';
1011 $selectAttribs['name'] ??= 'namespace';
1012
1013 $label = '';
1014 if ( isset( $params['label'] ) ) {
1015 $label = self::element( 'label', [ 'for' => $selectAttribs['id'] ],
1016 $params['label']
1017 ) . "\u{00A0}";
1018 }
1019
1020 // Wrap options in a <select>
1021 return $label . self::rawElement( 'select', $selectAttribs,
1022 "\n" . implode( "\n", $optionsHtml ) . "\n"
1023 );
1024 }
1025
1034 public static function htmlHeader( array $attribs = [] ) {
1035 $ret = '';
1036 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1037 $html5Version = $mainConfig->get( MainConfigNames::Html5Version );
1038 $mimeType = $mainConfig->get( MainConfigNames::MimeType );
1039 $xhtmlNamespaces = $mainConfig->get( MainConfigNames::XhtmlNamespaces );
1040
1041 $isXHTML = self::isXmlMimeType( $mimeType );
1042
1043 if ( $isXHTML ) { // XHTML5
1044 // XML MIME-typed markup should have an xml header.
1045 // However a DOCTYPE is not needed.
1046 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
1047
1048 // Add the standard xmlns
1049 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
1050
1051 // And support custom namespaces
1052 foreach ( $xhtmlNamespaces as $tag => $ns ) {
1053 $attribs["xmlns:$tag"] = $ns;
1054 }
1055 } else { // HTML5
1056 $ret .= "<!DOCTYPE html>\n";
1057 }
1058
1059 if ( $html5Version ) {
1060 $attribs['version'] = $html5Version;
1061 }
1062
1063 $ret .= self::openElement( 'html', $attribs );
1064
1065 return $ret;
1066 }
1067
1074 public static function isXmlMimeType( $mimetype ) {
1075 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
1076 # * text/xml
1077 # * application/xml
1078 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1079 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1080 }
1081
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(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:71
Group all the pieces relevant to the context of a request into one instance.
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: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:617
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:971
static warningBox( $html, $className='')
Return a warning box.
Definition Html.php:779
static check( $name, $checked=false, array $attribs=[])
Convenience function to produce a checkbox (input element with type=checkbox)
Definition Html.php:703
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:851
static expandAttributes(array $attribs)
Given an associative array of element attributes, generate a string to stick after the element name i...
Definition Html.php:534
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:758
static successBox( $html, $className='')
Return a success box.
Definition Html.php:818
static buttonAttributes(array $attrs, array $modifiers=[])
Modifies a set of attributes meant for button elements.
Definition Html.php:183
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:1034
static errorBox( $html, $heading='', $className='')
Return an error box.
Definition Html.php:799
static inlineScript( $contents, $nonce=null)
Output an HTML script tag with the given contents.
Definition Html.php:600
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition Html.php:333
static radio( $name, $checked=false, array $attribs=[])
Convenience function to produce a radio button (input element with type=radio)
Definition Html.php:831
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition Html.php:283
static isXmlMimeType( $mimetype)
Determines if the given MIME type is xml.
Definition Html.php:1074
static getTextInputAttributes(array $attrs)
Modifies a set of attributes meant for text input elements.
Definition Html.php:195
static expandClassList( $classes)
Convert a value for a 'class' attribute in a format accepted by Html::element() and similar methods t...
Definition Html.php:457
static input( $name, $value='', $type='text', array $attribs=[])
Convenience function to produce an <input> element.
Definition Html.php:688
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition Html.php:867
static textarea( $name, $value='', array $attribs=[])
Convenience function to produce a <textarea> element.
Definition Html.php:888
static namespaceSelectorOptions(array $params=[])
Helper for Html::namespaceSelector().
Definition Html.php:908
static inlineStyle( $contents, $media='all', $attribs=[])
Output a "<style>" tag with the given contents for the given media type (if any).
Definition Html.php:640
static closeElement( $element)
Returns "</$element>".
Definition Html.php:370
static linkButton( $text, array $attrs, array $modifiers=[])
Returns an HTML link element in a string.
Definition Html.php:237
static submitButton( $contents, array $attrs=[], array $modifiers=[])
Returns an HTML input element in a string.
Definition Html.php:255
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:309
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:669
static addClass(&$classes, string $class)
Add a class to a 'class' attribute in a format accepted by Html::element().
Definition Html.php:210
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:34
Handle sending Content-Security-Policy headers.
element(SerializerNode $parent, SerializerNode $node, $contents)