MediaWiki 1.43.1
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 linkButton( $text, array $attrs, array $modifiers = [] ) {
147 return self::element(
148 'a',
149 $attrs,
150 $text
151 );
152 }
153
164 public static function submitButton( $contents, array $attrs = [], array $modifiers = [] ) {
165 $attrs['type'] = 'submit';
166 $attrs['value'] = $contents;
167 return self::element( 'input', $attrs );
168 }
169
192 public static function rawElement( $element, $attribs = [], $contents = '' ) {
193 $start = self::openElement( $element, $attribs );
194 if ( isset( self::$voidElements[$element] ) ) {
195 return $start;
196 } else {
197 $contents = Sanitizer::escapeCombiningChar( $contents ?? '' );
198 return $start . $contents . self::closeElement( $element );
199 }
200 }
201
218 public static function element( $element, $attribs = [], $contents = '' ) {
219 return self::rawElement(
220 $element,
221 $attribs,
222 strtr( $contents ?? '', [
223 // There's no point in escaping quotes, >, etc. in the contents of
224 // elements.
225 '&' => '&amp;',
226 '<' => '&lt;',
227 ] )
228 );
229 }
230
242 public static function openElement( $element, $attribs = [] ) {
243 $attribs = (array)$attribs;
244 // This is not required in HTML5, but let's do it anyway, for
245 // consistency and better compression.
246 $element = strtolower( $element );
247
248 // Some people were abusing this by passing things like
249 // 'h1 id="foo" to $element, which we don't want.
250 if ( str_contains( $element, ' ' ) ) {
251 wfWarn( __METHOD__ . " given element name with space '$element'" );
252 }
253
254 // Remove invalid input types
255 if ( $element == 'input' ) {
256 $validTypes = [
257 'hidden' => true,
258 'text' => true,
259 'password' => true,
260 'checkbox' => true,
261 'radio' => true,
262 'file' => true,
263 'submit' => true,
264 'image' => true,
265 'reset' => true,
266 'button' => true,
267
268 // HTML input types
269 'datetime' => true,
270 'datetime-local' => true,
271 'date' => true,
272 'month' => true,
273 'time' => true,
274 'week' => true,
275 'number' => true,
276 'range' => true,
277 'email' => true,
278 'url' => true,
279 'search' => true,
280 'tel' => true,
281 'color' => true,
282 ];
283 if ( isset( $attribs['type'] ) && !isset( $validTypes[$attribs['type']] ) ) {
284 unset( $attribs['type'] );
285 }
286 }
287
288 // According to standard the default type for <button> elements is "submit".
289 // Depending on compatibility mode IE might use "button", instead.
290 // We enforce the standard "submit".
291 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
292 $attribs['type'] = 'submit';
293 }
294
295 return "<$element" . self::expandAttributes(
296 self::dropDefaults( $element, $attribs ) ) . '>';
297 }
298
306 public static function closeElement( $element ) {
307 $element = strtolower( $element );
308
309 return "</$element>";
310 }
311
329 private static function dropDefaults( $element, array $attribs ) {
330 // Whenever altering this array, please provide a covering test case
331 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
332 static $attribDefaults = [
333 'area' => [ 'shape' => 'rect' ],
334 'button' => [
335 'formaction' => 'GET',
336 'formenctype' => 'application/x-www-form-urlencoded',
337 ],
338 'canvas' => [
339 'height' => '150',
340 'width' => '300',
341 ],
342 'form' => [
343 'action' => 'GET',
344 'autocomplete' => 'on',
345 'enctype' => 'application/x-www-form-urlencoded',
346 ],
347 'input' => [
348 'formaction' => 'GET',
349 'type' => 'text',
350 ],
351 'keygen' => [ 'keytype' => 'rsa' ],
352 'link' => [ 'media' => 'all' ],
353 'menu' => [ 'type' => 'list' ],
354 'script' => [ 'type' => 'text/javascript' ],
355 'style' => [
356 'media' => 'all',
357 'type' => 'text/css',
358 ],
359 'textarea' => [ 'wrap' => 'soft' ],
360 ];
361
362 foreach ( $attribs as $attrib => $value ) {
363 if ( $attrib === 'class' ) {
364 if ( $value === '' || $value === [] || $value === [ '' ] ) {
365 unset( $attribs[$attrib] );
366 }
367 } elseif ( isset( $attribDefaults[$element][$attrib] ) ) {
368 if ( is_array( $value ) ) {
369 $value = implode( ' ', $value );
370 } else {
371 $value = strval( $value );
372 }
373 if ( $attribDefaults[$element][$attrib] == $value ) {
374 unset( $attribs[$attrib] );
375 }
376 }
377 }
378
379 // More subtle checks
380 if ( $element === 'link'
381 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
382 ) {
383 unset( $attribs['type'] );
384 }
385 if ( $element === 'input' ) {
386 $type = $attribs['type'] ?? null;
387 $value = $attribs['value'] ?? null;
388 if ( $type === 'checkbox' || $type === 'radio' ) {
389 // The default value for checkboxes and radio buttons is 'on'
390 // not ''. By stripping value="" we break radio boxes that
391 // actually wants empty values.
392 if ( $value === 'on' ) {
393 unset( $attribs['value'] );
394 }
395 } elseif ( $type === 'submit' ) {
396 // The default value for submit appears to be "Submit" but
397 // let's not bother stripping out localized text that matches
398 // that.
399 } else {
400 // The default value for nearly every other field type is ''
401 // The 'range' and 'color' types use different defaults but
402 // stripping a value="" does not hurt them.
403 if ( $value === '' ) {
404 unset( $attribs['value'] );
405 }
406 }
407 }
408 if ( $element === 'select' && isset( $attribs['size'] ) ) {
409 $multiple = ( $attribs['multiple'] ?? false ) !== false ||
410 in_array( 'multiple', $attribs );
411 $default = $multiple ? 4 : 1;
412 if ( (int)$attribs['size'] === $default ) {
413 unset( $attribs['size'] );
414 }
415 }
416
417 return $attribs;
418 }
419
458 public static function expandAttributes( array $attribs ) {
459 $ret = '';
460 foreach ( $attribs as $key => $value ) {
461 // Support intuitive [ 'checked' => true/false ] form
462 if ( $value === false || $value === null ) {
463 continue;
464 }
465
466 // For boolean attributes, support [ 'foo' ] instead of
467 // requiring [ 'foo' => 'meaningless' ].
468 if ( is_int( $key ) && isset( self::$boolAttribs[strtolower( $value )] ) ) {
469 $key = $value;
470 }
471
472 // Not technically required in HTML5 but we'd like consistency
473 // and better compression anyway.
474 $key = strtolower( $key );
475
476 // https://www.w3.org/TR/html401/index/attributes.html ("space-separated")
477 // https://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
478 $spaceSeparatedListAttributes = [
479 'class' => true, // html4, html5
480 'accesskey' => true, // as of html5, multiple space-separated values allowed
481 // html4-spec doesn't document rel= as space-separated
482 // but has been used like that and is now documented as such
483 // in the html5-spec.
484 'rel' => true,
485 ];
486
487 // Specific features for attributes that allow a list of space-separated values
488 if ( isset( $spaceSeparatedListAttributes[$key] ) ) {
489 // Apply some normalization and remove duplicates
490
491 // Convert into correct array. Array can contain space-separated
492 // values. Implode/explode to get those into the main array as well.
493 if ( is_array( $value ) ) {
494 // If input wasn't an array, we can skip this step
495 $arrayValue = [];
496 foreach ( $value as $k => $v ) {
497 if ( is_string( $v ) ) {
498 // String values should be normal `[ 'foo' ]`
499 // Just append them
500 if ( !isset( $value[$v] ) ) {
501 // As a special case don't set 'foo' if a
502 // separate 'foo' => true/false exists in the array
503 // keys should be authoritative
504 foreach ( explode( ' ', $v ) as $part ) {
505 // Normalize spacing by fixing up cases where people used
506 // more than 1 space and/or a trailing/leading space
507 if ( $part !== '' && $part !== ' ' ) {
508 $arrayValue[] = $part;
509 }
510 }
511 }
512 } elseif ( $v ) {
513 // If the value is truthy but not a string this is likely
514 // an [ 'foo' => true ], falsy values don't add strings
515 $arrayValue[] = $k;
516 }
517 }
518 } else {
519 $arrayValue = explode( ' ', $value );
520 // Normalize spacing by fixing up cases where people used
521 // more than 1 space and/or a trailing/leading space
522 $arrayValue = array_diff( $arrayValue, [ '', ' ' ] );
523 }
524
525 // Remove duplicates and create the string
526 $value = implode( ' ', array_unique( $arrayValue ) );
527
528 // Optimization: Skip below boolAttribs check and jump straight
529 // to its `else` block. The current $spaceSeparatedListAttributes
530 // block is mutually exclusive with $boolAttribs.
531 // phpcs:ignore Generic.PHP.DiscourageGoto
532 goto not_bool; // NOSONAR
533 } elseif ( is_array( $value ) ) {
534 throw new UnexpectedValueException( "HTML attribute $key can not contain a list of values" );
535 }
536
537 if ( isset( self::$boolAttribs[$key] ) ) {
538 $ret .= " $key=\"\"";
539 } else {
540 // phpcs:ignore Generic.PHP.DiscourageGoto
541 not_bool:
542 // Inlined from Sanitizer::encodeAttribute() for improved performance
543 $encValue = htmlspecialchars( $value, ENT_QUOTES );
544 // Whitespace is normalized during attribute decoding,
545 // so if we've been passed non-spaces we must encode them
546 // ahead of time or they won't be preserved.
547 $encValue = strtr( $encValue, [
548 "\n" => '&#10;',
549 "\r" => '&#13;',
550 "\t" => '&#9;',
551 ] );
552 $ret .= " $key=\"$encValue\"";
553 }
554 }
555 return $ret;
556 }
557
571 public static function inlineScript( $contents, $nonce = null ) {
572 if ( preg_match( '/<\/?script/i', $contents ) ) {
573 wfLogWarning( __METHOD__ . ': Illegal character sequence found in inline script.' );
574 $contents = '/* ERROR: Invalid script */';
575 }
576
577 return self::rawElement( 'script', [], $contents );
578 }
579
588 public static function linkedScript( $url, $nonce = null ) {
589 $attrs = [ 'src' => $url ];
590 if ( $nonce !== null ) {
591 $attrs['nonce'] = $nonce;
592 } elseif ( ContentSecurityPolicy::isNonceRequired( MediaWikiServices::getInstance()->getMainConfig() ) ) {
593 wfWarn( "no nonce set on script. CSP will break it" );
594 }
595
596 return self::element( 'script', $attrs );
597 }
598
611 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
612 // Don't escape '>' since that is used
613 // as direct child selector.
614 // Remember, in css, there is no "x" for hexadecimal escapes, and
615 // the space immediately after an escape sequence is swallowed.
616 $contents = strtr( $contents, [
617 '<' => '\3C ',
618 // CDATA end tag for good measure, but the main security
619 // is from escaping the '<'.
620 ']]>' => '\5D\5D\3E '
621 ] );
622
623 if ( preg_match( '/[<&]/', $contents ) ) {
624 $contents = "/*<![CDATA[*/$contents/*]]>*/";
625 }
626
627 return self::rawElement( 'style', [
628 'media' => $media,
629 ] + $attribs, $contents );
630 }
631
640 public static function linkedStyle( $url, $media = 'all' ) {
641 return self::element( 'link', [
642 'rel' => 'stylesheet',
643 'href' => $url,
644 'media' => $media,
645 ] );
646 }
647
659 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
660 $attribs['type'] = $type;
661 $attribs['value'] = $value;
662 $attribs['name'] = $name;
663 return self::element( 'input', $attribs );
664 }
665
674 public static function check( $name, $checked = false, array $attribs = [] ) {
675 if ( isset( $attribs['value'] ) ) {
676 $value = $attribs['value'];
677 unset( $attribs['value'] );
678 } else {
679 $value = 1;
680 }
681
682 if ( $checked ) {
683 $attribs[] = 'checked';
684 }
685
686 return self::input( $name, $value, 'checkbox', $attribs );
687 }
688
699 private static function messageBox( $html, $className, $heading = '', $iconClassName = '' ) {
700 if ( $heading !== '' ) {
701 $html = self::element( 'h2', [], $heading ) . $html;
702 }
703 $coreClasses = [
704 'cdx-message',
705 'cdx-message--block'
706 ];
707 if ( is_array( $className ) ) {
708 $className = array_merge(
709 $coreClasses,
710 $className
711 );
712 } else {
713 $className .= ' ' . implode( ' ', $coreClasses );
714 }
715 return self::rawElement( 'div', [ 'class' => $className ],
716 self::element( 'span', [ 'class' => [
717 'cdx-message__icon',
718 $iconClassName
719 ] ] ) .
720 self::rawElement( 'div', [
721 'class' => 'cdx-message__content'
722 ], $html )
723 );
724 }
725
736 public static function noticeBox( $html, $className, $heading = '', $iconClassName = '' ) {
737 return self::messageBox( $html, [
738 'cdx-message--notice',
739 $className
740 ], $heading, $iconClassName );
741 }
742
752 public static function warningBox( $html, $className = '' ) {
753 return self::messageBox( $html, [
754 'cdx-message--warning', $className ] );
755 }
756
767 public static function errorBox( $html, $heading = '', $className = '' ) {
768 return self::messageBox( $html, [
769 'cdx-message--error', $className ], $heading );
770 }
771
781 public static function successBox( $html, $className = '' ) {
782 return self::messageBox( $html, [
783 'cdx-message--success', $className ] );
784 }
785
794 public static function radio( $name, $checked = false, array $attribs = [] ) {
795 if ( isset( $attribs['value'] ) ) {
796 $value = $attribs['value'];
797 unset( $attribs['value'] );
798 } else {
799 $value = 1;
800 }
801
802 if ( $checked ) {
803 $attribs[] = 'checked';
804 }
805
806 return self::input( $name, $value, 'radio', $attribs );
807 }
808
817 public static function label( $label, $id, array $attribs = [] ) {
818 $attribs += [
819 'for' => $id,
820 ];
821 return self::element( 'label', $attribs, $label );
822 }
823
833 public static function hidden( $name, $value, array $attribs = [] ) {
834 return self::input( $name, $value, 'hidden', $attribs );
835 }
836
849 public static function textarea( $name, $value = '', array $attribs = [] ) {
850 $attribs['name'] = $name;
851
852 if ( substr( $value ?? '', 0, 1 ) == "\n" ) {
853 // Workaround for T14130: browsers eat the initial newline
854 // assuming that it's just for show, but they do keep the later
855 // newlines, which we may want to preserve during editing.
856 // Prepending a single newline
857 $spacedValue = "\n" . $value;
858 } else {
859 $spacedValue = $value;
860 }
861 return self::element( 'textarea', $attribs, $spacedValue );
862 }
863
869 public static function namespaceSelectorOptions( array $params = [] ) {
870 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
871 $params['exclude'] = [];
872 }
873
874 if ( $params['in-user-lang'] ?? false ) {
875 global $wgLang;
876 $lang = $wgLang;
877 } else {
878 $lang = MediaWikiServices::getInstance()->getContentLanguage();
879 }
880
881 $optionsOut = [];
882 if ( isset( $params['all'] ) ) {
883 // add an option that would let the user select all namespaces.
884 // Value is provided by user, the name shown is localized for the user.
885 $optionsOut[$params['all']] = wfMessage( 'namespacesall' )->text();
886 }
887 // Add all namespaces as options
888 $options = $lang->getFormattedNamespaces();
889 // Filter out namespaces below 0 and massage labels
890 foreach ( $options as $nsId => $nsName ) {
891 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
892 continue;
893 }
894 if ( $nsId === NS_MAIN ) {
895 // For other namespaces use the namespace prefix as label, but for
896 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
897 $nsName = wfMessage( 'blanknamespace' )->text();
898 } elseif ( is_int( $nsId ) ) {
899 $converter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
900 ->getLanguageConverter( $lang );
901 $nsName = $converter->convertNamespace( $nsId );
902 }
903 $optionsOut[$nsId] = $nsName;
904 }
905
906 return $optionsOut;
907 }
908
925 public static function namespaceSelector(
926 array $params = [],
927 array $selectAttribs = []
928 ) {
929 ksort( $selectAttribs );
930
931 // Is a namespace selected?
932 if ( isset( $params['selected'] ) ) {
933 // If string only contains digits, convert to clean int. Selected could also
934 // be "all" or "" etc. which needs to be left untouched.
935 if ( !is_int( $params['selected'] ) && ctype_digit( (string)$params['selected'] ) ) {
936 $params['selected'] = (int)$params['selected'];
937 }
938 // else: leaves it untouched for later processing
939 } else {
940 $params['selected'] = '';
941 }
942
943 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
944 $params['disable'] = [];
945 }
946
947 // Associative array between option-values and option-labels
949
950 // Convert $options to HTML
951 $optionsHtml = [];
952 foreach ( $options as $nsId => $nsName ) {
953 $optionsHtml[] = self::element(
954 'option',
955 [
956 'disabled' => in_array( $nsId, $params['disable'] ),
957 'value' => $nsId,
958 'selected' => $nsId === $params['selected'],
959 ],
960 $nsName
961 );
962 }
963
964 $selectAttribs['id'] ??= 'namespace';
965 $selectAttribs['name'] ??= 'namespace';
966
967 $ret = '';
968 if ( isset( $params['label'] ) ) {
969 $ret .= self::element(
970 'label', [
971 'for' => $selectAttribs['id'],
972 ], $params['label']
973 ) . "\u{00A0}";
974 }
975
976 // Wrap options in a <select>
977 $ret .= self::openElement( 'select', $selectAttribs )
978 . "\n"
979 . implode( "\n", $optionsHtml )
980 . "\n"
981 . self::closeElement( 'select' );
982
983 return $ret;
984 }
985
994 public static function htmlHeader( array $attribs = [] ) {
995 $ret = '';
996 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
997 $html5Version = $mainConfig->get( MainConfigNames::Html5Version );
998 $mimeType = $mainConfig->get( MainConfigNames::MimeType );
999 $xhtmlNamespaces = $mainConfig->get( MainConfigNames::XhtmlNamespaces );
1000
1001 $isXHTML = self::isXmlMimeType( $mimeType );
1002
1003 if ( $isXHTML ) { // XHTML5
1004 // XML MIME-typed markup should have an xml header.
1005 // However a DOCTYPE is not needed.
1006 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
1007
1008 // Add the standard xmlns
1009 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
1010
1011 // And support custom namespaces
1012 foreach ( $xhtmlNamespaces as $tag => $ns ) {
1013 $attribs["xmlns:$tag"] = $ns;
1014 }
1015 } else { // HTML5
1016 $ret .= "<!DOCTYPE html>\n";
1017 }
1018
1019 if ( $html5Version ) {
1020 $attribs['version'] = $html5Version;
1021 }
1022
1023 $ret .= self::openElement( 'html', $attribs );
1024
1025 return $ret;
1026 }
1027
1034 public static function isXmlMimeType( $mimetype ) {
1035 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
1036 # * text/xml
1037 # * application/xml
1038 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1039 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1040 }
1041
1065 public static function srcSet( array $urls ) {
1066 $candidates = [];
1067 foreach ( $urls as $density => $url ) {
1068 // Cast density to float to strip 'x', then back to string to serve
1069 // as array index.
1070 $density = (string)(float)$density;
1071 $candidates[$density] = $url;
1072 }
1073
1074 // Remove duplicates that are the same as a smaller value
1075 ksort( $candidates, SORT_NUMERIC );
1076 $candidates = array_unique( $candidates );
1077
1078 // Append density info to the url
1079 foreach ( $candidates as $density => $url ) {
1080 $candidates[$density] = $url . ' ' . $density . 'x';
1081 }
1082
1083 return implode( ", ", $candidates );
1084 }
1085
1100 public static function encodeJsVar( $value, $pretty = false ) {
1101 if ( $value instanceof HtmlJsCode ) {
1102 return $value->value;
1103 }
1104 return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
1105 }
1106
1121 public static function encodeJsCall( $name, $args, $pretty = false ) {
1122 $encodedArgs = self::encodeJsList( $args, $pretty );
1123 if ( $encodedArgs === false ) {
1124 return false;
1125 }
1126 return "$name($encodedArgs);";
1127 }
1128
1138 public static function encodeJsList( $args, $pretty = false ) {
1139 foreach ( $args as &$arg ) {
1140 $arg = self::encodeJsVar( $arg, $pretty );
1141 if ( $arg === false ) {
1142 return false;
1143 }
1144 }
1145 if ( $pretty ) {
1146 return ' ' . implode( ', ', $args ) . ' ';
1147 } else {
1148 return implode( ',', $args );
1149 }
1150 }
1151
1165 public static function listDropdownOptions( $list, $params = [] ) {
1166 $options = [];
1167
1168 if ( isset( $params['other'] ) ) {
1169 $options[ $params['other'] ] = 'other';
1170 }
1171
1172 $optgroup = false;
1173 foreach ( explode( "\n", $list ) as $option ) {
1174 $value = trim( $option );
1175 if ( $value == '' ) {
1176 continue;
1177 }
1178 if ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
1179 # A new group is starting...
1180 $value = trim( substr( $value, 1 ) );
1181 if ( $value !== '' &&
1182 // Do not use the value for 'other' as option group - T251351
1183 ( !isset( $params['other'] ) || $value !== $params['other'] )
1184 ) {
1185 $optgroup = $value;
1186 } else {
1187 $optgroup = false;
1188 }
1189 } elseif ( substr( $value, 0, 2 ) == '**' ) {
1190 # groupmember
1191 $opt = trim( substr( $value, 2 ) );
1192 if ( $optgroup === false ) {
1193 $options[$opt] = $opt;
1194 } else {
1195 $options[$optgroup][$opt] = $opt;
1196 }
1197 } else {
1198 # groupless reason list
1199 $optgroup = false;
1200 $options[$option] = $option;
1201 }
1202 }
1203
1204 return $options;
1205 }
1206
1215 public static function listDropdownOptionsOoui( $options ) {
1216 $optionsOoui = [];
1217
1218 foreach ( $options as $text => $value ) {
1219 if ( is_array( $value ) ) {
1220 $optionsOoui[] = [ 'optgroup' => (string)$text ];
1221 foreach ( $value as $text2 => $value2 ) {
1222 $optionsOoui[] = [ 'data' => (string)$value2, 'label' => (string)$text2 ];
1223 }
1224 } else {
1225 $optionsOoui[] = [ 'data' => (string)$value, 'label' => (string)$text ];
1226 }
1227 }
1228
1229 return $optionsOoui;
1230 }
1231
1240 public static function listDropdownOptionsCodex( $options ) {
1241 $optionsCodex = [];
1242
1243 foreach ( $options as $text => $value ) {
1244 if ( is_array( $value ) ) {
1245 // No support for optgroups in Codex yet (T367241)
1246 $optionsCodex[] = [ 'label' => (string)$text, 'value' => '', 'disabled' => true ];
1247 foreach ( $value as $text2 => $value2 ) {
1248 $optionsCodex[] = [ 'label' => (string)$text2, 'value' => (string)$value2 ];
1249 }
1250 } else {
1251 $optionsCodex[] = [ 'label' => (string)$text, 'value' => (string)$value ];
1252 }
1253 }
1254 return $optionsCodex;
1255 }
1256}
1257
1259class_alias( Html::class, 'Html' );
const NS_MAIN
Definition Defines.php:65
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgLang
Definition Setup.php:541
array $params
The job parameters.
A wrapper class which causes Html::encodeJsVar() and Html::encodeJsCall() (as well as their Xml::* co...
This class is a collection of static functions that serve two purposes:
Definition Html.php: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:588
static listDropdownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition Html.php:1215
static namespaceSelector(array $params=[], array $selectAttribs=[])
Build a drop-down box for selecting a namespace.
Definition Html.php:925
static warningBox( $html, $className='')
Return a warning box.
Definition Html.php:752
static check( $name, $checked=false, array $attribs=[])
Convenience function to produce a checkbox (input element with type=checkbox)
Definition Html.php:674
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition Html.php:1100
static listDropdownOptionsCodex( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition Html.php:1240
static label( $label, $id, array $attribs=[])
Convenience function for generating a label for inputs.
Definition Html.php:817
static expandAttributes(array $attribs)
Given an associative array of element attributes, generate a string to stick after the element name i...
Definition Html.php:458
static srcSet(array $urls)
Generate a srcset attribute value.
Definition Html.php:1065
static successBox( $html, $className='')
Return a success box.
Definition Html.php:781
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:1121
static htmlHeader(array $attribs=[])
Constructs the opening html-tag with necessary doctypes depending on global variables.
Definition Html.php:994
static errorBox( $html, $heading='', $className='')
Return an error box.
Definition Html.php:767
static inlineScript( $contents, $nonce=null)
Output an HTML script tag with the given contents.
Definition Html.php:571
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition Html.php:242
static radio( $name, $checked=false, array $attribs=[])
Convenience function to produce a radio button (input element with type=radio)
Definition Html.php:794
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition Html.php:192
static isXmlMimeType( $mimetype)
Determines if the given MIME type is xml.
Definition Html.php:1034
static getTextInputAttributes(array $attrs)
Modifies a set of attributes meant for text input elements.
Definition Html.php:131
static input( $name, $value='', $type='text', array $attribs=[])
Convenience function to produce an <input> element.
Definition Html.php:659
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition Html.php:833
static textarea( $name, $value='', array $attribs=[])
Convenience function to produce a <textarea> element.
Definition Html.php:849
static namespaceSelectorOptions(array $params=[])
Helper for Html::namespaceSelector().
Definition Html.php:869
static inlineStyle( $contents, $media='all', $attribs=[])
Output a "<style>" tag with the given contents for the given media type (if any).
Definition Html.php:611
static closeElement( $element)
Returns "</$element>".
Definition Html.php:306
static linkButton( $text, array $attrs, array $modifiers=[])
Returns an HTML link element in a string.
Definition Html.php:146
static submitButton( $contents, array $attrs=[], array $modifiers=[])
Returns an HTML input element in a string.
Definition Html.php:164
static encodeJsList( $args, $pretty=false)
Encode a JavaScript comma-separated list.
Definition Html.php:1138
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition Html.php:218
static listDropdownOptions( $list, $params=[])
Build options for a drop-down box from a textual list.
Definition Html.php:1165
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:640
static noticeBox( $html, $className, $heading='', $iconClassName='')
Return the HTML for a notice message box.
Definition Html.php:736
JSON formatter wrapper class.
A class containing constants representing the names of configuration variables.
const MimeType
Name constant for the MimeType setting, for use with Config::get()
const XhtmlNamespaces
Name constant for the XhtmlNamespaces setting, for use with Config::get()
const Html5Version
Name constant for the Html5Version setting, for use with Config::get()
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
HTML sanitizer for MediaWiki.
Definition Sanitizer.php:46
Handle sending Content-Security-Policy headers.