MediaWiki master
Html.php
Go to the documentation of this file.
1<?php
26namespace MediaWiki\Html;
27
33use UnexpectedValueException;
34
57class Html {
59 private static $voidElements = [
60 'area' => true,
61 'base' => true,
62 'br' => true,
63 'col' => true,
64 'embed' => true,
65 'hr' => true,
66 'img' => true,
67 'input' => true,
68 'keygen' => true,
69 'link' => true,
70 'meta' => true,
71 'param' => true,
72 'source' => true,
73 'track' => true,
74 'wbr' => true,
75 ];
76
82 private static $boolAttribs = [
83 'async' => true,
84 'autofocus' => true,
85 'autoplay' => true,
86 'checked' => true,
87 'controls' => true,
88 'default' => true,
89 'defer' => true,
90 'disabled' => true,
91 'formnovalidate' => true,
92 'hidden' => true,
93 'ismap' => true,
94 'itemscope' => true,
95 'loop' => true,
96 'multiple' => true,
97 'muted' => true,
98 'novalidate' => true,
99 'open' => true,
100 'pubdate' => true,
101 'readonly' => true,
102 'required' => true,
103 'reversed' => true,
104 'scoped' => true,
105 'seamless' => true,
106 'selected' => true,
107 'truespeed' => true,
108 'typemustmatch' => true,
109 ];
110
119 public static function buttonAttributes( array $attrs, array $modifiers = [] ) {
120 wfDeprecated( __METHOD__, '1.42' );
121 return $attrs;
122 }
123
131 public static function getTextInputAttributes( array $attrs ) {
132 wfDeprecated( __METHOD__, '1.42' );
133 return $attrs;
134 }
135
146 public static function addClass( &$classes, string $class ): void {
147 $classes = (array)$classes;
148 // Detect mistakes where $attrs is passed as $classes instead of $attrs['class']
149 foreach ( $classes as $key => $val ) {
150 if (
151 ( is_int( $key ) && is_string( $val ) ) ||
152 ( is_string( $key ) && is_bool( $val ) )
153 ) {
154 // Valid formats for class array entries
155 continue;
156 }
157 wfWarn( __METHOD__ . ": Argument doesn't look like a class array: " . var_export( $classes, true ) );
158 break;
159 }
160 $classes[] = $class;
161 }
162
173 public static function linkButton( $text, array $attrs, array $modifiers = [] ) {
174 return self::element(
175 'a',
176 $attrs,
177 $text
178 );
179 }
180
191 public static function submitButton( $contents, array $attrs = [], array $modifiers = [] ) {
192 $attrs['type'] = 'submit';
193 $attrs['value'] = $contents;
194 return self::element( 'input', $attrs );
195 }
196
219 public static function rawElement( $element, $attribs = [], $contents = '' ) {
220 $start = self::openElement( $element, $attribs );
221 if ( isset( self::$voidElements[$element] ) ) {
222 return $start;
223 } else {
224 $contents = Sanitizer::escapeCombiningChar( $contents ?? '' );
225 return $start . $contents . self::closeElement( $element );
226 }
227 }
228
245 public static function element( $element, $attribs = [], $contents = '' ) {
246 return self::rawElement(
247 $element,
248 $attribs,
249 strtr( $contents ?? '', [
250 // There's no point in escaping quotes, >, etc. in the contents of
251 // elements.
252 '&' => '&amp;',
253 '<' => '&lt;',
254 ] )
255 );
256 }
257
269 public static function openElement( $element, $attribs = [] ) {
270 $attribs = (array)$attribs;
271 // This is not required in HTML5, but let's do it anyway, for
272 // consistency and better compression.
273 $element = strtolower( $element );
274
275 // Some people were abusing this by passing things like
276 // 'h1 id="foo" to $element, which we don't want.
277 if ( str_contains( $element, ' ' ) ) {
278 wfWarn( __METHOD__ . " given element name with space '$element'" );
279 }
280
281 // Remove invalid input types
282 if ( $element == 'input' ) {
283 $validTypes = [
284 'hidden' => true,
285 'text' => true,
286 'password' => true,
287 'checkbox' => true,
288 'radio' => true,
289 'file' => true,
290 'submit' => true,
291 'image' => true,
292 'reset' => true,
293 'button' => true,
294
295 // HTML input types
296 'datetime' => true,
297 'datetime-local' => true,
298 'date' => true,
299 'month' => true,
300 'time' => true,
301 'week' => true,
302 'number' => true,
303 'range' => true,
304 'email' => true,
305 'url' => true,
306 'search' => true,
307 'tel' => true,
308 'color' => true,
309 ];
310 if ( isset( $attribs['type'] ) && !isset( $validTypes[$attribs['type']] ) ) {
311 unset( $attribs['type'] );
312 }
313 }
314
315 // According to standard the default type for <button> elements is "submit".
316 // Depending on compatibility mode IE might use "button", instead.
317 // We enforce the standard "submit".
318 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
319 $attribs['type'] = 'submit';
320 }
321
322 return "<$element" . self::expandAttributes(
323 self::dropDefaults( $element, $attribs ) ) . '>';
324 }
325
333 public static function closeElement( $element ) {
334 $element = strtolower( $element );
335
336 return "</$element>";
337 }
338
356 private static function dropDefaults( $element, array $attribs ) {
357 // Whenever altering this array, please provide a covering test case
358 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
359 static $attribDefaults = [
360 'area' => [ 'shape' => 'rect' ],
361 'button' => [
362 'formaction' => 'GET',
363 'formenctype' => 'application/x-www-form-urlencoded',
364 ],
365 'canvas' => [
366 'height' => '150',
367 'width' => '300',
368 ],
369 'form' => [
370 'action' => 'GET',
371 'autocomplete' => 'on',
372 'enctype' => 'application/x-www-form-urlencoded',
373 ],
374 'input' => [
375 'formaction' => 'GET',
376 'type' => 'text',
377 ],
378 'keygen' => [ 'keytype' => 'rsa' ],
379 'link' => [ 'media' => 'all' ],
380 'menu' => [ 'type' => 'list' ],
381 'script' => [ 'type' => 'text/javascript' ],
382 'style' => [
383 'media' => 'all',
384 'type' => 'text/css',
385 ],
386 'textarea' => [ 'wrap' => 'soft' ],
387 ];
388
389 foreach ( $attribs as $attrib => $value ) {
390 if ( $attrib === 'class' ) {
391 if ( $value === '' || $value === [] || $value === [ '' ] ) {
392 unset( $attribs[$attrib] );
393 }
394 } elseif ( isset( $attribDefaults[$element][$attrib] ) ) {
395 if ( is_array( $value ) ) {
396 $value = implode( ' ', $value );
397 } else {
398 $value = strval( $value );
399 }
400 if ( $attribDefaults[$element][$attrib] == $value ) {
401 unset( $attribs[$attrib] );
402 }
403 }
404 }
405
406 // More subtle checks
407 if ( $element === 'link'
408 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
409 ) {
410 unset( $attribs['type'] );
411 }
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::$boolAttribs[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 // https://www.w3.org/TR/html401/index/attributes.html ("space-separated")
553 // https://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
554 $spaceSeparatedListAttributes = [
555 'class' => true, // html4, html5
556 'accesskey' => true, // as of html5, multiple space-separated values allowed
557 // html4-spec doesn't document rel= as space-separated
558 // but has been used like that and is now documented as such
559 // in the html5-spec.
560 'rel' => true,
561 ];
562
563 // Specific features for attributes that allow a list of space-separated values
564 if ( isset( $spaceSeparatedListAttributes[$key] ) ) {
565 // Apply some normalization and remove duplicates
566 $value = self::expandClassList( $value );
567
568 // Optimization: Skip below boolAttribs check and jump straight
569 // to its `else` block. The current $spaceSeparatedListAttributes
570 // block is mutually exclusive with $boolAttribs.
571 // phpcs:ignore Generic.PHP.DiscourageGoto
572 goto not_bool; // NOSONAR
573 } elseif ( is_array( $value ) ) {
574 throw new UnexpectedValueException( "HTML attribute $key can not contain a list of values" );
575 }
576
577 if ( isset( self::$boolAttribs[$key] ) ) {
578 $ret .= " $key=\"\"";
579 } else {
580 // phpcs:ignore Generic.PHP.DiscourageGoto
581 not_bool:
582 // Inlined from Sanitizer::encodeAttribute() for improved performance
583 $encValue = htmlspecialchars( $value, ENT_QUOTES );
584 // Whitespace is normalized during attribute decoding,
585 // so if we've been passed non-spaces we must encode them
586 // ahead of time or they won't be preserved.
587 $encValue = strtr( $encValue, [
588 "\n" => '&#10;',
589 "\r" => '&#13;',
590 "\t" => '&#9;',
591 ] );
592 $ret .= " $key=\"$encValue\"";
593 }
594 }
595 return $ret;
596 }
597
611 public static function inlineScript( $contents, $nonce = null ) {
612 if ( preg_match( '/<\/?script/i', $contents ) ) {
613 wfLogWarning( __METHOD__ . ': Illegal character sequence found in inline script.' );
614 $contents = '/* ERROR: Invalid script */';
615 }
616
617 return self::rawElement( 'script', [], $contents );
618 }
619
628 public static function linkedScript( $url, $nonce = null ) {
629 $attrs = [ 'src' => $url ];
630 if ( $nonce !== null ) {
631 $attrs['nonce'] = $nonce;
632 } elseif ( ContentSecurityPolicy::isNonceRequired( MediaWikiServices::getInstance()->getMainConfig() ) ) {
633 wfWarn( "no nonce set on script. CSP will break it" );
634 }
635
636 return self::element( 'script', $attrs );
637 }
638
651 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
652 // Don't escape '>' since that is used
653 // as direct child selector.
654 // Remember, in css, there is no "x" for hexadecimal escapes, and
655 // the space immediately after an escape sequence is swallowed.
656 $contents = strtr( $contents, [
657 '<' => '\3C ',
658 // CDATA end tag for good measure, but the main security
659 // is from escaping the '<'.
660 ']]>' => '\5D\5D\3E '
661 ] );
662
663 if ( preg_match( '/[<&]/', $contents ) ) {
664 $contents = "/*<![CDATA[*/$contents/*]]>*/";
665 }
666
667 return self::rawElement( 'style', [
668 'media' => $media,
669 ] + $attribs, $contents );
670 }
671
680 public static function linkedStyle( $url, $media = 'all' ) {
681 return self::element( 'link', [
682 'rel' => 'stylesheet',
683 'href' => $url,
684 'media' => $media,
685 ] );
686 }
687
699 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
700 $attribs['type'] = $type;
701 $attribs['value'] = $value;
702 $attribs['name'] = $name;
703 return self::element( 'input', $attribs );
704 }
705
714 public static function check( $name, $checked = false, array $attribs = [] ) {
715 if ( isset( $attribs['value'] ) ) {
716 $value = $attribs['value'];
717 unset( $attribs['value'] );
718 } else {
719 $value = 1;
720 }
721
722 if ( $checked ) {
723 $attribs[] = 'checked';
724 }
725
726 return self::input( $name, $value, 'checkbox', $attribs );
727 }
728
739 private static function messageBox( $html, $className, $heading = '', $iconClassName = '' ) {
740 if ( $heading !== '' ) {
741 $html = self::element( 'h2', [], $heading ) . $html;
742 }
743 self::addClass( $className, 'cdx-message' );
744 self::addClass( $className, 'cdx-message--block' );
745 return self::rawElement( 'div', [ 'class' => $className ],
746 self::element( 'span', [ 'class' => [
747 'cdx-message__icon',
748 $iconClassName
749 ] ] ) .
750 self::rawElement( 'div', [
751 'class' => 'cdx-message__content'
752 ], $html )
753 );
754 }
755
771 public static function noticeBox( $html, $className, $heading = '', $iconClassName = '' ) {
772 return self::messageBox( $html, [
773 'cdx-message--notice',
774 $className
775 ], $heading, $iconClassName );
776 }
777
792 public static function warningBox( $html, $className = '' ) {
793 return self::messageBox( $html, [
794 'cdx-message--warning', $className ] );
795 }
796
812 public static function errorBox( $html, $heading = '', $className = '' ) {
813 return self::messageBox( $html, [
814 'cdx-message--error', $className ], $heading );
815 }
816
831 public static function successBox( $html, $className = '' ) {
832 return self::messageBox( $html, [
833 'cdx-message--success', $className ] );
834 }
835
844 public static function radio( $name, $checked = false, array $attribs = [] ) {
845 if ( isset( $attribs['value'] ) ) {
846 $value = $attribs['value'];
847 unset( $attribs['value'] );
848 } else {
849 $value = 1;
850 }
851
852 if ( $checked ) {
853 $attribs[] = 'checked';
854 }
855
856 return self::input( $name, $value, 'radio', $attribs );
857 }
858
867 public static function label( $label, $id, array $attribs = [] ) {
868 $attribs += [
869 'for' => $id,
870 ];
871 return self::element( 'label', $attribs, $label );
872 }
873
883 public static function hidden( $name, $value, array $attribs = [] ) {
884 return self::input( $name, $value, 'hidden', $attribs );
885 }
886
899 public static function textarea( $name, $value = '', array $attribs = [] ) {
900 $attribs['name'] = $name;
901
902 if ( str_starts_with( $value ?? '', "\n" ) ) {
903 // Workaround for T14130: browsers eat the initial newline
904 // assuming that it's just for show, but they do keep the later
905 // newlines, which we may want to preserve during editing.
906 // Prepending a single newline
907 $spacedValue = "\n" . $value;
908 } else {
909 $spacedValue = $value;
910 }
911 return self::element( 'textarea', $attribs, $spacedValue );
912 }
913
919 public static function namespaceSelectorOptions( array $params = [] ) {
920 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
921 $params['exclude'] = [];
922 }
923
924 if ( $params['in-user-lang'] ?? false ) {
925 global $wgLang;
926 $lang = $wgLang;
927 } else {
928 $lang = MediaWikiServices::getInstance()->getContentLanguage();
929 }
930
931 $optionsOut = [];
932 if ( isset( $params['all'] ) ) {
933 // add an option that would let the user select all namespaces.
934 // Value is provided by user, the name shown is localized for the user.
935 $optionsOut[$params['all']] = wfMessage( 'namespacesall' )->text();
936 }
937 // Add all namespaces as options
938 $options = $lang->getFormattedNamespaces();
939 // Filter out namespaces below 0 and massage labels
940 foreach ( $options as $nsId => $nsName ) {
941 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
942 continue;
943 }
944 if (
945 isset( $params['include'] ) &&
946 is_array( $params['include'] ) &&
947 !in_array( $nsId, $params['include'] )
948 ) {
949 continue;
950 }
951
952 if ( $nsId === NS_MAIN ) {
953 // For other namespaces use the namespace prefix as label, but for
954 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
955 $nsName = wfMessage( 'blanknamespace' )->text();
956 } elseif ( is_int( $nsId ) ) {
957 $converter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
958 ->getLanguageConverter( $lang );
959 $nsName = $converter->convertNamespace( $nsId );
960 }
961 $optionsOut[$nsId] = $nsName;
962 }
963
964 return $optionsOut;
965 }
966
983 public static function namespaceSelector(
984 array $params = [],
985 array $selectAttribs = []
986 ) {
987 ksort( $selectAttribs );
988
989 // Is a namespace selected?
990 if ( isset( $params['selected'] ) ) {
991 // If string only contains digits, convert to clean int. Selected could also
992 // be "all" or "" etc. which needs to be left untouched.
993 if ( !is_int( $params['selected'] ) && ctype_digit( (string)$params['selected'] ) ) {
994 $params['selected'] = (int)$params['selected'];
995 }
996 // else: leaves it untouched for later processing
997 } else {
998 $params['selected'] = '';
999 }
1000
1001 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
1002 $params['disable'] = [];
1003 }
1004
1005 // Associative array between option-values and option-labels
1006 $options = self::namespaceSelectorOptions( $params );
1007
1008 // Convert $options to HTML
1009 $optionsHtml = [];
1010 foreach ( $options as $nsId => $nsName ) {
1011 $optionsHtml[] = self::element(
1012 'option',
1013 [
1014 'disabled' => in_array( $nsId, $params['disable'] ),
1015 'value' => $nsId,
1016 'selected' => $nsId === $params['selected'],
1017 ],
1018 $nsName
1019 );
1020 }
1021
1022 $selectAttribs['id'] ??= 'namespace';
1023 $selectAttribs['name'] ??= 'namespace';
1024
1025 $ret = '';
1026 if ( isset( $params['label'] ) ) {
1027 $ret .= self::element(
1028 'label', [
1029 'for' => $selectAttribs['id'],
1030 ], $params['label']
1031 ) . "\u{00A0}";
1032 }
1033
1034 // Wrap options in a <select>
1035 $ret .= self::openElement( 'select', $selectAttribs )
1036 . "\n"
1037 . implode( "\n", $optionsHtml )
1038 . "\n"
1039 . self::closeElement( 'select' );
1040
1041 return $ret;
1042 }
1043
1052 public static function htmlHeader( array $attribs = [] ) {
1053 $ret = '';
1054 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1055 $html5Version = $mainConfig->get( MainConfigNames::Html5Version );
1056 $mimeType = $mainConfig->get( MainConfigNames::MimeType );
1057 $xhtmlNamespaces = $mainConfig->get( MainConfigNames::XhtmlNamespaces );
1058
1059 $isXHTML = self::isXmlMimeType( $mimeType );
1060
1061 if ( $isXHTML ) { // XHTML5
1062 // XML MIME-typed markup should have an xml header.
1063 // However a DOCTYPE is not needed.
1064 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
1065
1066 // Add the standard xmlns
1067 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
1068
1069 // And support custom namespaces
1070 foreach ( $xhtmlNamespaces as $tag => $ns ) {
1071 $attribs["xmlns:$tag"] = $ns;
1072 }
1073 } else { // HTML5
1074 $ret .= "<!DOCTYPE html>\n";
1075 }
1076
1077 if ( $html5Version ) {
1078 $attribs['version'] = $html5Version;
1079 }
1080
1081 $ret .= self::openElement( 'html', $attribs );
1082
1083 return $ret;
1084 }
1085
1092 public static function isXmlMimeType( $mimetype ) {
1093 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
1094 # * text/xml
1095 # * application/xml
1096 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1097 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1098 }
1099
1123 public static function srcSet( array $urls ) {
1124 $candidates = [];
1125 foreach ( $urls as $density => $url ) {
1126 // Cast density to float to strip 'x', then back to string to serve
1127 // as array index.
1128 $density = (string)(float)$density;
1129 $candidates[$density] = $url;
1130 }
1131
1132 // Remove duplicates that are the same as a smaller value
1133 ksort( $candidates, SORT_NUMERIC );
1134 $candidates = array_unique( $candidates );
1135
1136 // Append density info to the url
1137 foreach ( $candidates as $density => $url ) {
1138 $candidates[$density] = $url . ' ' . $density . 'x';
1139 }
1140
1141 return implode( ", ", $candidates );
1142 }
1143
1158 public static function encodeJsVar( $value, $pretty = false ) {
1159 if ( $value instanceof HtmlJsCode ) {
1160 return $value->value;
1161 }
1162 return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
1163 }
1164
1179 public static function encodeJsCall( $name, $args, $pretty = false ) {
1180 $encodedArgs = self::encodeJsList( $args, $pretty );
1181 if ( $encodedArgs === false ) {
1182 return false;
1183 }
1184 return "$name($encodedArgs);";
1185 }
1186
1196 public static function encodeJsList( $args, $pretty = false ) {
1197 foreach ( $args as &$arg ) {
1198 $arg = self::encodeJsVar( $arg, $pretty );
1199 if ( $arg === false ) {
1200 return false;
1201 }
1202 }
1203 if ( $pretty ) {
1204 return ' ' . implode( ', ', $args ) . ' ';
1205 } else {
1206 return implode( ',', $args );
1207 }
1208 }
1209
1223 public static function listDropdownOptions( $list, $params = [] ) {
1224 $options = [];
1225
1226 if ( isset( $params['other'] ) ) {
1227 $options[ $params['other'] ] = 'other';
1228 }
1229
1230 $optgroup = false;
1231 foreach ( explode( "\n", $list ) as $option ) {
1232 $value = trim( $option );
1233 if ( $value == '' ) {
1234 continue;
1235 }
1236 if ( str_starts_with( $value, '*' ) && !str_starts_with( $value, '**' ) ) {
1237 # A new group is starting...
1238 $value = trim( substr( $value, 1 ) );
1239 if ( $value !== '' &&
1240 // Do not use the value for 'other' as option group - T251351
1241 ( !isset( $params['other'] ) || $value !== $params['other'] )
1242 ) {
1243 $optgroup = $value;
1244 } else {
1245 $optgroup = false;
1246 }
1247 } elseif ( str_starts_with( $value, '**' ) ) {
1248 # groupmember
1249 $opt = trim( substr( $value, 2 ) );
1250 if ( $optgroup === false ) {
1251 $options[$opt] = $opt;
1252 } else {
1253 $options[$optgroup][$opt] = $opt;
1254 }
1255 } else {
1256 # groupless reason list
1257 $optgroup = false;
1258 $options[$option] = $option;
1259 }
1260 }
1261
1262 return $options;
1263 }
1264
1273 public static function listDropdownOptionsOoui( $options ) {
1274 $optionsOoui = [];
1275
1276 foreach ( $options as $text => $value ) {
1277 if ( is_array( $value ) ) {
1278 $optionsOoui[] = [ 'optgroup' => (string)$text ];
1279 foreach ( $value as $text2 => $value2 ) {
1280 $optionsOoui[] = [ 'data' => (string)$value2, 'label' => (string)$text2 ];
1281 }
1282 } else {
1283 $optionsOoui[] = [ 'data' => (string)$value, 'label' => (string)$text ];
1284 }
1285 }
1286
1287 return $optionsOoui;
1288 }
1289
1298 public static function listDropdownOptionsCodex( $options ) {
1299 $optionsCodex = [];
1300
1301 foreach ( $options as $text => $value ) {
1302 if ( is_array( $value ) ) {
1303 $optionsCodex[] = [
1304 'label' => (string)$text,
1305 'items' => array_map( static function ( $text2, $value2 ) {
1306 return [ 'label' => (string)$text2, 'value' => (string)$value2 ];
1307 }, array_keys( $value ), $value )
1308 ];
1309 } else {
1310 $optionsCodex[] = [ 'label' => (string)$text, 'value' => (string)$value ];
1311 }
1312 }
1313 return $optionsCodex;
1314 }
1315}
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:559
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:82
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:57
static linkedScript( $url, $nonce=null)
Output a "<script>" tag linking to the given URL, e.g., "<script src=foo.js></script>".
Definition Html.php:628
static listDropdownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition Html.php:1273
static namespaceSelector(array $params=[], array $selectAttribs=[])
Build a drop-down box for selecting a namespace.
Definition Html.php:983
static warningBox( $html, $className='')
Return a warning box.
Definition Html.php:792
static check( $name, $checked=false, array $attribs=[])
Convenience function to produce a checkbox (input element with type=checkbox)
Definition Html.php:714
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition Html.php:1158
static listDropdownOptionsCodex( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition Html.php:1298
static label( $label, $id, array $attribs=[])
Convenience function for generating a label for inputs.
Definition Html.php:867
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:1123
static successBox( $html, $className='')
Return a success box.
Definition Html.php:831
static buttonAttributes(array $attrs, array $modifiers=[])
Modifies a set of attributes meant for button elements.
Definition Html.php:119
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition Html.php:1179
static htmlHeader(array $attribs=[])
Constructs the opening html-tag with necessary doctypes depending on global variables.
Definition Html.php:1052
static errorBox( $html, $heading='', $className='')
Return an error box.
Definition Html.php:812
static inlineScript( $contents, $nonce=null)
Output an HTML script tag with the given contents.
Definition Html.php:611
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition Html.php:269
static radio( $name, $checked=false, array $attribs=[])
Convenience function to produce a radio button (input element with type=radio)
Definition Html.php:844
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition Html.php:219
static isXmlMimeType( $mimetype)
Determines if the given MIME type is xml.
Definition Html.php:1092
static getTextInputAttributes(array $attrs)
Modifies a set of attributes meant for text input elements.
Definition Html.php:131
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:699
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition Html.php:883
static textarea( $name, $value='', array $attribs=[])
Convenience function to produce a <textarea> element.
Definition Html.php:899
static namespaceSelectorOptions(array $params=[])
Helper for Html::namespaceSelector().
Definition Html.php:919
static inlineStyle( $contents, $media='all', $attribs=[])
Output a "<style>" tag with the given contents for the given media type (if any).
Definition Html.php:651
static closeElement( $element)
Returns "</$element>".
Definition Html.php:333
static linkButton( $text, array $attrs, array $modifiers=[])
Returns an HTML link element in a string.
Definition Html.php:173
static submitButton( $contents, array $attrs=[], array $modifiers=[])
Returns an HTML input element in a string.
Definition Html.php:191
static encodeJsList( $args, $pretty=false)
Encode a JavaScript comma-separated list.
Definition Html.php:1196
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition Html.php:245
static listDropdownOptions( $list, $params=[])
Build options for a drop-down box from a textual list.
Definition Html.php:1223
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:680
static addClass(&$classes, string $class)
Add a class to a 'class' attribute in a format accepted by Html::element().
Definition Html.php:146
static noticeBox( $html, $className, $heading='', $iconClassName='')
Return the HTML for a notice message box.
Definition Html.php:771
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:46
Handle sending Content-Security-Policy headers.
element(SerializerNode $parent, SerializerNode $node, $contents)