MediaWiki master
Html.php
Go to the documentation of this file.
1<?php
26namespace MediaWiki\Html;
27
32use UnexpectedValueException;
33
56class Html {
58 private static $voidElements = [
59 'area' => true,
60 'base' => true,
61 'br' => true,
62 'col' => true,
63 'embed' => true,
64 'hr' => true,
65 'img' => true,
66 'input' => true,
67 'keygen' => true,
68 'link' => true,
69 'meta' => true,
70 'param' => true,
71 'source' => true,
72 'track' => true,
73 'wbr' => true,
74 ];
75
81 private static $boolAttribs = [
82 'async' => true,
83 'autofocus' => true,
84 'autoplay' => true,
85 'checked' => true,
86 'controls' => true,
87 'default' => true,
88 'defer' => true,
89 'disabled' => true,
90 'formnovalidate' => true,
91 'hidden' => true,
92 'ismap' => true,
93 'itemscope' => true,
94 'loop' => true,
95 'multiple' => true,
96 'muted' => true,
97 'novalidate' => true,
98 'open' => true,
99 'pubdate' => true,
100 'readonly' => true,
101 'required' => true,
102 'reversed' => true,
103 'scoped' => true,
104 'seamless' => true,
105 'selected' => true,
106 'truespeed' => true,
107 'typemustmatch' => true,
108 ];
109
118 public static function buttonAttributes( array $attrs, array $modifiers = [] ) {
119 wfDeprecated( __METHOD__, '1.42' );
120 return $attrs;
121 }
122
130 public static function getTextInputAttributes( array $attrs ) {
131 wfDeprecated( __METHOD__, '1.42' );
132 return $attrs;
133 }
134
145 public static function linkButton( $text, array $attrs, array $modifiers = [] ) {
146 return self::element(
147 'a',
148 $attrs,
149 $text
150 );
151 }
152
163 public static function submitButton( $contents, array $attrs = [], array $modifiers = [] ) {
164 $attrs['type'] = 'submit';
165 $attrs['value'] = $contents;
166 return self::element( 'input', $attrs );
167 }
168
191 public static function rawElement( $element, $attribs = [], $contents = '' ) {
192 $start = self::openElement( $element, $attribs );
193 if ( isset( self::$voidElements[$element] ) ) {
194 return $start;
195 } else {
196 return $start . $contents . self::closeElement( $element );
197 }
198 }
199
216 public static function element( $element, $attribs = [], $contents = '' ) {
217 return self::rawElement(
218 $element,
219 $attribs,
220 strtr( $contents ?? '', [
221 // There's no point in escaping quotes, >, etc. in the contents of
222 // elements.
223 '&' => '&amp;',
224 '<' => '&lt;',
225 ] )
226 );
227 }
228
240 public static function openElement( $element, $attribs = [] ) {
241 $attribs = (array)$attribs;
242 // This is not required in HTML5, but let's do it anyway, for
243 // consistency and better compression.
244 $element = strtolower( $element );
245
246 // Some people were abusing this by passing things like
247 // 'h1 id="foo" to $element, which we don't want.
248 if ( str_contains( $element, ' ' ) ) {
249 wfWarn( __METHOD__ . " given element name with space '$element'" );
250 }
251
252 // Remove invalid input types
253 if ( $element == 'input' ) {
254 $validTypes = [
255 'hidden' => true,
256 'text' => true,
257 'password' => true,
258 'checkbox' => true,
259 'radio' => true,
260 'file' => true,
261 'submit' => true,
262 'image' => true,
263 'reset' => true,
264 'button' => true,
265
266 // HTML input types
267 'datetime' => true,
268 'datetime-local' => true,
269 'date' => true,
270 'month' => true,
271 'time' => true,
272 'week' => true,
273 'number' => true,
274 'range' => true,
275 'email' => true,
276 'url' => true,
277 'search' => true,
278 'tel' => true,
279 'color' => true,
280 ];
281 if ( isset( $attribs['type'] ) && !isset( $validTypes[$attribs['type']] ) ) {
282 unset( $attribs['type'] );
283 }
284 }
285
286 // According to standard the default type for <button> elements is "submit".
287 // Depending on compatibility mode IE might use "button", instead.
288 // We enforce the standard "submit".
289 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
290 $attribs['type'] = 'submit';
291 }
292
293 return "<$element" . self::expandAttributes(
294 self::dropDefaults( $element, $attribs ) ) . '>';
295 }
296
304 public static function closeElement( $element ) {
305 $element = strtolower( $element );
306
307 return "</$element>";
308 }
309
327 private static function dropDefaults( $element, array $attribs ) {
328 // Whenever altering this array, please provide a covering test case
329 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
330 static $attribDefaults = [
331 'area' => [ 'shape' => 'rect' ],
332 'button' => [
333 'formaction' => 'GET',
334 'formenctype' => 'application/x-www-form-urlencoded',
335 ],
336 'canvas' => [
337 'height' => '150',
338 'width' => '300',
339 ],
340 'form' => [
341 'action' => 'GET',
342 'autocomplete' => 'on',
343 'enctype' => 'application/x-www-form-urlencoded',
344 ],
345 'input' => [
346 'formaction' => 'GET',
347 'type' => 'text',
348 ],
349 'keygen' => [ 'keytype' => 'rsa' ],
350 'link' => [ 'media' => 'all' ],
351 'menu' => [ 'type' => 'list' ],
352 'script' => [ 'type' => 'text/javascript' ],
353 'style' => [
354 'media' => 'all',
355 'type' => 'text/css',
356 ],
357 'textarea' => [ 'wrap' => 'soft' ],
358 ];
359
360 foreach ( $attribs as $attrib => $value ) {
361 if ( $attrib === 'class' ) {
362 if ( $value === '' || $value === [] || $value === [ '' ] ) {
363 unset( $attribs[$attrib] );
364 }
365 } elseif ( isset( $attribDefaults[$element][$attrib] ) ) {
366 if ( is_array( $value ) ) {
367 $value = implode( ' ', $value );
368 } else {
369 $value = strval( $value );
370 }
371 if ( $attribDefaults[$element][$attrib] == $value ) {
372 unset( $attribs[$attrib] );
373 }
374 }
375 }
376
377 // More subtle checks
378 if ( $element === 'link'
379 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
380 ) {
381 unset( $attribs['type'] );
382 }
383 if ( $element === 'input' ) {
384 $type = $attribs['type'] ?? null;
385 $value = $attribs['value'] ?? null;
386 if ( $type === 'checkbox' || $type === 'radio' ) {
387 // The default value for checkboxes and radio buttons is 'on'
388 // not ''. By stripping value="" we break radio boxes that
389 // actually wants empty values.
390 if ( $value === 'on' ) {
391 unset( $attribs['value'] );
392 }
393 } elseif ( $type === 'submit' ) {
394 // The default value for submit appears to be "Submit" but
395 // let's not bother stripping out localized text that matches
396 // that.
397 } else {
398 // The default value for nearly every other field type is ''
399 // The 'range' and 'color' types use different defaults but
400 // stripping a value="" does not hurt them.
401 if ( $value === '' ) {
402 unset( $attribs['value'] );
403 }
404 }
405 }
406 if ( $element === 'select' && isset( $attribs['size'] ) ) {
407 $multiple = ( $attribs['multiple'] ?? false ) !== false ||
408 in_array( 'multiple', $attribs );
409 $default = $multiple ? 4 : 1;
410 if ( (int)$attribs['size'] === $default ) {
411 unset( $attribs['size'] );
412 }
413 }
414
415 return $attribs;
416 }
417
456 public static function expandAttributes( array $attribs ) {
457 $ret = '';
458 foreach ( $attribs as $key => $value ) {
459 // Support intuitive [ 'checked' => true/false ] form
460 if ( $value === false || $value === null ) {
461 continue;
462 }
463
464 // For boolean attributes, support [ 'foo' ] instead of
465 // requiring [ 'foo' => 'meaningless' ].
466 if ( is_int( $key ) && isset( self::$boolAttribs[strtolower( $value )] ) ) {
467 $key = $value;
468 }
469
470 // Not technically required in HTML5 but we'd like consistency
471 // and better compression anyway.
472 $key = strtolower( $key );
473
474 // https://www.w3.org/TR/html401/index/attributes.html ("space-separated")
475 // https://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
476 $spaceSeparatedListAttributes = [
477 'class' => true, // html4, html5
478 'accesskey' => true, // as of html5, multiple space-separated values allowed
479 // html4-spec doesn't document rel= as space-separated
480 // but has been used like that and is now documented as such
481 // in the html5-spec.
482 'rel' => true,
483 ];
484
485 // Specific features for attributes that allow a list of space-separated values
486 if ( isset( $spaceSeparatedListAttributes[$key] ) ) {
487 // Apply some normalization and remove duplicates
488
489 // Convert into correct array. Array can contain space-separated
490 // values. Implode/explode to get those into the main array as well.
491 if ( is_array( $value ) ) {
492 // If input wasn't an array, we can skip this step
493 $arrayValue = [];
494 foreach ( $value as $k => $v ) {
495 if ( is_string( $v ) ) {
496 // String values should be normal `[ 'foo' ]`
497 // Just append them
498 if ( !isset( $value[$v] ) ) {
499 // As a special case don't set 'foo' if a
500 // separate 'foo' => true/false exists in the array
501 // keys should be authoritative
502 foreach ( explode( ' ', $v ) as $part ) {
503 // Normalize spacing by fixing up cases where people used
504 // more than 1 space and/or a trailing/leading space
505 if ( $part !== '' && $part !== ' ' ) {
506 $arrayValue[] = $part;
507 }
508 }
509 }
510 } elseif ( $v ) {
511 // If the value is truthy but not a string this is likely
512 // an [ 'foo' => true ], falsy values don't add strings
513 $arrayValue[] = $k;
514 }
515 }
516 } else {
517 $arrayValue = explode( ' ', $value );
518 // Normalize spacing by fixing up cases where people used
519 // more than 1 space and/or a trailing/leading space
520 $arrayValue = array_diff( $arrayValue, [ '', ' ' ] );
521 }
522
523 // Remove duplicates and create the string
524 $value = implode( ' ', array_unique( $arrayValue ) );
525
526 // Optimization: Skip below boolAttribs check and jump straight
527 // to its `else` block. The current $spaceSeparatedListAttributes
528 // block is mutually exclusive with $boolAttribs.
529 // phpcs:ignore Generic.PHP.DiscourageGoto
530 goto not_bool; // NOSONAR
531 } elseif ( is_array( $value ) ) {
532 throw new UnexpectedValueException( "HTML attribute $key can not contain a list of values" );
533 }
534
535 if ( isset( self::$boolAttribs[$key] ) ) {
536 $ret .= " $key=\"\"";
537 } else {
538 // phpcs:ignore Generic.PHP.DiscourageGoto
539 not_bool:
540 // Inlined from Sanitizer::encodeAttribute() for improved performance
541 $encValue = htmlspecialchars( $value, ENT_QUOTES );
542 // Whitespace is normalized during attribute decoding,
543 // so if we've been passed non-spaces we must encode them
544 // ahead of time or they won't be preserved.
545 $encValue = strtr( $encValue, [
546 "\n" => '&#10;',
547 "\r" => '&#13;',
548 "\t" => '&#9;',
549 ] );
550 $ret .= " $key=\"$encValue\"";
551 }
552 }
553 return $ret;
554 }
555
569 public static function inlineScript( $contents, $nonce = null ) {
570 if ( preg_match( '/<\/?script/i', $contents ) ) {
571 wfLogWarning( __METHOD__ . ': Illegal character sequence found in inline script.' );
572 $contents = '/* ERROR: Invalid script */';
573 }
574
575 return self::rawElement( 'script', [], $contents );
576 }
577
586 public static function linkedScript( $url, $nonce = null ) {
587 $attrs = [ 'src' => $url ];
588 if ( $nonce !== null ) {
589 $attrs['nonce'] = $nonce;
590 } elseif ( ContentSecurityPolicy::isNonceRequired( MediaWikiServices::getInstance()->getMainConfig() ) ) {
591 wfWarn( "no nonce set on script. CSP will break it" );
592 }
593
594 return self::element( 'script', $attrs );
595 }
596
609 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
610 // Don't escape '>' since that is used
611 // as direct child selector.
612 // Remember, in css, there is no "x" for hexadecimal escapes, and
613 // the space immediately after an escape sequence is swallowed.
614 $contents = strtr( $contents, [
615 '<' => '\3C ',
616 // CDATA end tag for good measure, but the main security
617 // is from escaping the '<'.
618 ']]>' => '\5D\5D\3E '
619 ] );
620
621 if ( preg_match( '/[<&]/', $contents ) ) {
622 $contents = "/*<![CDATA[*/$contents/*]]>*/";
623 }
624
625 return self::rawElement( 'style', [
626 'media' => $media,
627 ] + $attribs, $contents );
628 }
629
638 public static function linkedStyle( $url, $media = 'all' ) {
639 return self::element( 'link', [
640 'rel' => 'stylesheet',
641 'href' => $url,
642 'media' => $media,
643 ] );
644 }
645
657 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
658 $attribs['type'] = $type;
659 $attribs['value'] = $value;
660 $attribs['name'] = $name;
661 return self::element( 'input', $attribs );
662 }
663
672 public static function check( $name, $checked = false, array $attribs = [] ) {
673 if ( isset( $attribs['value'] ) ) {
674 $value = $attribs['value'];
675 unset( $attribs['value'] );
676 } else {
677 $value = 1;
678 }
679
680 if ( $checked ) {
681 $attribs[] = 'checked';
682 }
683
684 return self::input( $name, $value, 'checkbox', $attribs );
685 }
686
697 private static function messageBox( $html, $className, $heading = '', $iconClassName = '' ) {
698 if ( $heading !== '' ) {
699 $html = self::element( 'h2', [], $heading ) . $html;
700 }
701 $coreClasses = [
702 'cdx-message',
703 'cdx-message--block'
704 ];
705 if ( is_array( $className ) ) {
706 $className = array_merge(
707 $coreClasses,
708 $className
709 );
710 } else {
711 $className .= ' ' . implode( ' ', $coreClasses );
712 }
713 return self::rawElement( 'div', [ 'class' => $className ],
714 self::element( 'span', [ 'class' => [
715 'cdx-message__icon',
716 $iconClassName
717 ] ] ) .
718 self::rawElement( 'div', [
719 'class' => 'cdx-message__content'
720 ], $html )
721 );
722 }
723
739 public static function noticeBox( $html, $className, $heading = '', $iconClassName = '' ) {
740 return self::messageBox( $html, [
741 'cdx-message--notice',
742 $className
743 ], $heading, $iconClassName );
744 }
745
760 public static function warningBox( $html, $className = '' ) {
761 return self::messageBox( $html, [
762 'cdx-message--warning', $className ] );
763 }
764
780 public static function errorBox( $html, $heading = '', $className = '' ) {
781 return self::messageBox( $html, [
782 'cdx-message--error', $className ], $heading );
783 }
784
799 public static function successBox( $html, $className = '' ) {
800 return self::messageBox( $html, [
801 'cdx-message--success', $className ] );
802 }
803
812 public static function radio( $name, $checked = false, array $attribs = [] ) {
813 if ( isset( $attribs['value'] ) ) {
814 $value = $attribs['value'];
815 unset( $attribs['value'] );
816 } else {
817 $value = 1;
818 }
819
820 if ( $checked ) {
821 $attribs[] = 'checked';
822 }
823
824 return self::input( $name, $value, 'radio', $attribs );
825 }
826
835 public static function label( $label, $id, array $attribs = [] ) {
836 $attribs += [
837 'for' => $id,
838 ];
839 return self::element( 'label', $attribs, $label );
840 }
841
851 public static function hidden( $name, $value, array $attribs = [] ) {
852 return self::input( $name, $value, 'hidden', $attribs );
853 }
854
867 public static function textarea( $name, $value = '', array $attribs = [] ) {
868 $attribs['name'] = $name;
869
870 if ( substr( $value, 0, 1 ) == "\n" ) {
871 // Workaround for T14130: browsers eat the initial newline
872 // assuming that it's just for show, but they do keep the later
873 // newlines, which we may want to preserve during editing.
874 // Prepending a single newline
875 $spacedValue = "\n" . $value;
876 } else {
877 $spacedValue = $value;
878 }
879 return self::element( 'textarea', $attribs, $spacedValue );
880 }
881
887 public static function namespaceSelectorOptions( array $params = [] ) {
888 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
889 $params['exclude'] = [];
890 }
891
892 if ( $params['in-user-lang'] ?? false ) {
893 global $wgLang;
894 $lang = $wgLang;
895 } else {
896 $lang = MediaWikiServices::getInstance()->getContentLanguage();
897 }
898
899 $optionsOut = [];
900 if ( isset( $params['all'] ) ) {
901 // add an option that would let the user select all namespaces.
902 // Value is provided by user, the name shown is localized for the user.
903 $optionsOut[$params['all']] = wfMessage( 'namespacesall' )->text();
904 }
905 // Add all namespaces as options
906 $options = $lang->getFormattedNamespaces();
907 // Filter out namespaces below 0 and massage labels
908 foreach ( $options as $nsId => $nsName ) {
909 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
910 continue;
911 }
912 if (
913 isset( $params['include'] ) &&
914 is_array( $params['include'] ) &&
915 !in_array( $nsId, $params['include'] )
916 ) {
917 continue;
918 }
919
920 if ( $nsId === NS_MAIN ) {
921 // For other namespaces use the namespace prefix as label, but for
922 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
923 $nsName = wfMessage( 'blanknamespace' )->text();
924 } elseif ( is_int( $nsId ) ) {
925 $converter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
926 ->getLanguageConverter( $lang );
927 $nsName = $converter->convertNamespace( $nsId );
928 }
929 $optionsOut[$nsId] = $nsName;
930 }
931
932 return $optionsOut;
933 }
934
951 public static function namespaceSelector(
952 array $params = [],
953 array $selectAttribs = []
954 ) {
955 ksort( $selectAttribs );
956
957 // Is a namespace selected?
958 if ( isset( $params['selected'] ) ) {
959 // If string only contains digits, convert to clean int. Selected could also
960 // be "all" or "" etc. which needs to be left untouched.
961 if ( !is_int( $params['selected'] ) && ctype_digit( (string)$params['selected'] ) ) {
962 $params['selected'] = (int)$params['selected'];
963 }
964 // else: leaves it untouched for later processing
965 } else {
966 $params['selected'] = '';
967 }
968
969 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
970 $params['disable'] = [];
971 }
972
973 // Associative array between option-values and option-labels
975
976 // Convert $options to HTML
977 $optionsHtml = [];
978 foreach ( $options as $nsId => $nsName ) {
979 $optionsHtml[] = self::element(
980 'option',
981 [
982 'disabled' => in_array( $nsId, $params['disable'] ),
983 'value' => $nsId,
984 'selected' => $nsId === $params['selected'],
985 ],
986 $nsName
987 );
988 }
989
990 $selectAttribs['id'] ??= 'namespace';
991 $selectAttribs['name'] ??= 'namespace';
992
993 $ret = '';
994 if ( isset( $params['label'] ) ) {
995 $ret .= self::element(
996 'label', [
997 'for' => $selectAttribs['id'],
998 ], $params['label']
999 ) . "\u{00A0}";
1000 }
1001
1002 // Wrap options in a <select>
1003 $ret .= self::openElement( 'select', $selectAttribs )
1004 . "\n"
1005 . implode( "\n", $optionsHtml )
1006 . "\n"
1007 . self::closeElement( 'select' );
1008
1009 return $ret;
1010 }
1011
1020 public static function htmlHeader( array $attribs = [] ) {
1021 $ret = '';
1022 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1023 $html5Version = $mainConfig->get( MainConfigNames::Html5Version );
1024 $mimeType = $mainConfig->get( MainConfigNames::MimeType );
1025 $xhtmlNamespaces = $mainConfig->get( MainConfigNames::XhtmlNamespaces );
1026
1027 $isXHTML = self::isXmlMimeType( $mimeType );
1028
1029 if ( $isXHTML ) { // XHTML5
1030 // XML MIME-typed markup should have an xml header.
1031 // However a DOCTYPE is not needed.
1032 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
1033
1034 // Add the standard xmlns
1035 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
1036
1037 // And support custom namespaces
1038 foreach ( $xhtmlNamespaces as $tag => $ns ) {
1039 $attribs["xmlns:$tag"] = $ns;
1040 }
1041 } else { // HTML5
1042 $ret .= "<!DOCTYPE html>\n";
1043 }
1044
1045 if ( $html5Version ) {
1046 $attribs['version'] = $html5Version;
1047 }
1048
1049 $ret .= self::openElement( 'html', $attribs );
1050
1051 return $ret;
1052 }
1053
1060 public static function isXmlMimeType( $mimetype ) {
1061 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
1062 # * text/xml
1063 # * application/xml
1064 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1065 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1066 }
1067
1091 public static function srcSet( array $urls ) {
1092 $candidates = [];
1093 foreach ( $urls as $density => $url ) {
1094 // Cast density to float to strip 'x', then back to string to serve
1095 // as array index.
1096 $density = (string)(float)$density;
1097 $candidates[$density] = $url;
1098 }
1099
1100 // Remove duplicates that are the same as a smaller value
1101 ksort( $candidates, SORT_NUMERIC );
1102 $candidates = array_unique( $candidates );
1103
1104 // Append density info to the url
1105 foreach ( $candidates as $density => $url ) {
1106 $candidates[$density] = $url . ' ' . $density . 'x';
1107 }
1108
1109 return implode( ", ", $candidates );
1110 }
1111
1126 public static function encodeJsVar( $value, $pretty = false ) {
1127 if ( $value instanceof HtmlJsCode ) {
1128 return $value->value;
1129 }
1130 return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
1131 }
1132
1147 public static function encodeJsCall( $name, $args, $pretty = false ) {
1148 $encodedArgs = self::encodeJsList( $args, $pretty );
1149 if ( $encodedArgs === false ) {
1150 return false;
1151 }
1152 return "$name($encodedArgs);";
1153 }
1154
1164 public static function encodeJsList( $args, $pretty = false ) {
1165 foreach ( $args as &$arg ) {
1166 $arg = self::encodeJsVar( $arg, $pretty );
1167 if ( $arg === false ) {
1168 return false;
1169 }
1170 }
1171 if ( $pretty ) {
1172 return ' ' . implode( ', ', $args ) . ' ';
1173 } else {
1174 return implode( ',', $args );
1175 }
1176 }
1177
1191 public static function listDropdownOptions( $list, $params = [] ) {
1192 $options = [];
1193
1194 if ( isset( $params['other'] ) ) {
1195 $options[ $params['other'] ] = 'other';
1196 }
1197
1198 $optgroup = false;
1199 foreach ( explode( "\n", $list ) as $option ) {
1200 $value = trim( $option );
1201 if ( $value == '' ) {
1202 continue;
1203 }
1204 if ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
1205 # A new group is starting...
1206 $value = trim( substr( $value, 1 ) );
1207 if ( $value !== '' &&
1208 // Do not use the value for 'other' as option group - T251351
1209 ( !isset( $params['other'] ) || $value !== $params['other'] )
1210 ) {
1211 $optgroup = $value;
1212 } else {
1213 $optgroup = false;
1214 }
1215 } elseif ( substr( $value, 0, 2 ) == '**' ) {
1216 # groupmember
1217 $opt = trim( substr( $value, 2 ) );
1218 if ( $optgroup === false ) {
1219 $options[$opt] = $opt;
1220 } else {
1221 $options[$optgroup][$opt] = $opt;
1222 }
1223 } else {
1224 # groupless reason list
1225 $optgroup = false;
1226 $options[$option] = $option;
1227 }
1228 }
1229
1230 return $options;
1231 }
1232
1241 public static function listDropdownOptionsOoui( $options ) {
1242 $optionsOoui = [];
1243
1244 foreach ( $options as $text => $value ) {
1245 if ( is_array( $value ) ) {
1246 $optionsOoui[] = [ 'optgroup' => (string)$text ];
1247 foreach ( $value as $text2 => $value2 ) {
1248 $optionsOoui[] = [ 'data' => (string)$value2, 'label' => (string)$text2 ];
1249 }
1250 } else {
1251 $optionsOoui[] = [ 'data' => (string)$value, 'label' => (string)$text ];
1252 }
1253 }
1254
1255 return $optionsOoui;
1256 }
1257
1266 public static function listDropdownOptionsCodex( $options ) {
1267 $optionsCodex = [];
1268
1269 foreach ( $options as $text => $value ) {
1270 if ( is_array( $value ) ) {
1271 // No support for optgroups in Codex yet (T367241)
1272 $optionsCodex[] = [ 'label' => (string)$text, 'value' => '', 'disabled' => true ];
1273 foreach ( $value as $text2 => $value2 ) {
1274 $optionsCodex[] = [ 'label' => (string)$text2, 'value' => (string)$value2 ];
1275 }
1276 } else {
1277 $optionsCodex[] = [ 'label' => (string)$text, 'value' => (string)$value ];
1278 }
1279 }
1280 return $optionsCodex;
1281 }
1282}
1283
1285class_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:572
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:56
static linkedScript( $url, $nonce=null)
Output a "<script>" tag linking to the given URL, e.g., "<script src=foo.js></script>".
Definition Html.php:586
static listDropdownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition Html.php:1241
static namespaceSelector(array $params=[], array $selectAttribs=[])
Build a drop-down box for selecting a namespace.
Definition Html.php:951
static warningBox( $html, $className='')
Return a warning box.
Definition Html.php:760
static check( $name, $checked=false, array $attribs=[])
Convenience function to produce a checkbox (input element with type=checkbox)
Definition Html.php:672
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition Html.php:1126
static listDropdownOptionsCodex( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition Html.php:1266
static label( $label, $id, array $attribs=[])
Convenience function for generating a label for inputs.
Definition Html.php:835
static expandAttributes(array $attribs)
Given an associative array of element attributes, generate a string to stick after the element name i...
Definition Html.php:456
static srcSet(array $urls)
Generate a srcset attribute value.
Definition Html.php:1091
static successBox( $html, $className='')
Return a success box.
Definition Html.php:799
static buttonAttributes(array $attrs, array $modifiers=[])
Modifies a set of attributes meant for button elements.
Definition Html.php:118
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition Html.php:1147
static htmlHeader(array $attribs=[])
Constructs the opening html-tag with necessary doctypes depending on global variables.
Definition Html.php:1020
static errorBox( $html, $heading='', $className='')
Return an error box.
Definition Html.php:780
static inlineScript( $contents, $nonce=null)
Output an HTML script tag with the given contents.
Definition Html.php:569
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition Html.php:240
static radio( $name, $checked=false, array $attribs=[])
Convenience function to produce a radio button (input element with type=radio)
Definition Html.php:812
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition Html.php:191
static isXmlMimeType( $mimetype)
Determines if the given MIME type is xml.
Definition Html.php:1060
static getTextInputAttributes(array $attrs)
Modifies a set of attributes meant for text input elements.
Definition Html.php:130
static input( $name, $value='', $type='text', array $attribs=[])
Convenience function to produce an <input> element.
Definition Html.php:657
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition Html.php:851
static textarea( $name, $value='', array $attribs=[])
Convenience function to produce a <textarea> element.
Definition Html.php:867
static namespaceSelectorOptions(array $params=[])
Helper for Html::namespaceSelector().
Definition Html.php:887
static inlineStyle( $contents, $media='all', $attribs=[])
Output a "<style>" tag with the given contents for the given media type (if any).
Definition Html.php:609
static closeElement( $element)
Returns "</$element>".
Definition Html.php:304
static linkButton( $text, array $attrs, array $modifiers=[])
Returns an HTML link element in a string.
Definition Html.php:145
static submitButton( $contents, array $attrs=[], array $modifiers=[])
Returns an HTML input element in a string.
Definition Html.php:163
static encodeJsList( $args, $pretty=false)
Encode a JavaScript comma-separated list.
Definition Html.php:1164
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition Html.php:216
static listDropdownOptions( $list, $params=[])
Build options for a drop-down box from a textual list.
Definition Html.php:1191
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:638
static noticeBox( $html, $className, $heading='', $iconClassName='')
Return the HTML for a notice message box.
Definition Html.php:739
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.
Handle sending Content-Security-Policy headers.