MediaWiki master
Html.php
Go to the documentation of this file.
1<?php
26namespace MediaWiki\Html;
27
28use FormatJson;
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 if ( in_array( 'multiple', $attribs )
408 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
409 ) {
410 // A multi-select
411 if ( strval( $attribs['size'] ) == '4' ) {
412 unset( $attribs['size'] );
413 }
414 } else {
415 // Single select
416 if ( strval( $attribs['size'] ) == '1' ) {
417 unset( $attribs['size'] );
418 }
419 }
420 }
421
422 return $attribs;
423 }
424
463 public static function expandAttributes( array $attribs ) {
464 $ret = '';
465 foreach ( $attribs as $key => $value ) {
466 // Support intuitive [ 'checked' => true/false ] form
467 if ( $value === false || $value === null ) {
468 continue;
469 }
470
471 // For boolean attributes, support [ 'foo' ] instead of
472 // requiring [ 'foo' => 'meaningless' ].
473 if ( is_int( $key ) && isset( self::$boolAttribs[strtolower( $value )] ) ) {
474 $key = $value;
475 }
476
477 // Not technically required in HTML5 but we'd like consistency
478 // and better compression anyway.
479 $key = strtolower( $key );
480
481 // https://www.w3.org/TR/html401/index/attributes.html ("space-separated")
482 // https://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
483 $spaceSeparatedListAttributes = [
484 'class' => true, // html4, html5
485 'accesskey' => true, // as of html5, multiple space-separated values allowed
486 // html4-spec doesn't document rel= as space-separated
487 // but has been used like that and is now documented as such
488 // in the html5-spec.
489 'rel' => true,
490 ];
491
492 // Specific features for attributes that allow a list of space-separated values
493 if ( isset( $spaceSeparatedListAttributes[$key] ) ) {
494 // Apply some normalization and remove duplicates
495
496 // Convert into correct array. Array can contain space-separated
497 // values. Implode/explode to get those into the main array as well.
498 if ( is_array( $value ) ) {
499 // If input wasn't an array, we can skip this step
500 $arrayValue = [];
501 foreach ( $value as $k => $v ) {
502 if ( is_string( $v ) ) {
503 // String values should be normal `[ 'foo' ]`
504 // Just append them
505 if ( !isset( $value[$v] ) ) {
506 // As a special case don't set 'foo' if a
507 // separate 'foo' => true/false exists in the array
508 // keys should be authoritative
509 foreach ( explode( ' ', $v ) as $part ) {
510 // Normalize spacing by fixing up cases where people used
511 // more than 1 space and/or a trailing/leading space
512 if ( $part !== '' && $part !== ' ' ) {
513 $arrayValue[] = $part;
514 }
515 }
516 }
517 } elseif ( $v ) {
518 // If the value is truthy but not a string this is likely
519 // an [ 'foo' => true ], falsy values don't add strings
520 $arrayValue[] = $k;
521 }
522 }
523 } else {
524 $arrayValue = explode( ' ', $value );
525 // Normalize spacing by fixing up cases where people used
526 // more than 1 space and/or a trailing/leading space
527 $arrayValue = array_diff( $arrayValue, [ '', ' ' ] );
528 }
529
530 // Remove duplicates and create the string
531 $value = implode( ' ', array_unique( $arrayValue ) );
532
533 // Optimization: Skip below boolAttribs check and jump straight
534 // to its `else` block. The current $spaceSeparatedListAttributes
535 // block is mutually exclusive with $boolAttribs.
536 // phpcs:ignore Generic.PHP.DiscourageGoto
537 goto not_bool; // NOSONAR
538 } elseif ( is_array( $value ) ) {
539 throw new UnexpectedValueException( "HTML attribute $key can not contain a list of values" );
540 }
541
542 if ( isset( self::$boolAttribs[$key] ) ) {
543 $ret .= " $key=\"\"";
544 } else {
545 // phpcs:ignore Generic.PHP.DiscourageGoto
546 not_bool:
547 // Inlined from Sanitizer::encodeAttribute() for improved performance
548 $encValue = htmlspecialchars( $value, ENT_QUOTES );
549 // Whitespace is normalized during attribute decoding,
550 // so if we've been passed non-spaces we must encode them
551 // ahead of time or they won't be preserved.
552 $encValue = strtr( $encValue, [
553 "\n" => '&#10;',
554 "\r" => '&#13;',
555 "\t" => '&#9;',
556 ] );
557 $ret .= " $key=\"$encValue\"";
558 }
559 }
560 return $ret;
561 }
562
576 public static function inlineScript( $contents, $nonce = null ) {
577 if ( preg_match( '/<\/?script/i', $contents ) ) {
578 wfLogWarning( __METHOD__ . ': Illegal character sequence found in inline script.' );
579 $contents = '/* ERROR: Invalid script */';
580 }
581
582 return self::rawElement( 'script', [], $contents );
583 }
584
593 public static function linkedScript( $url, $nonce = null ) {
594 $attrs = [ 'src' => $url ];
595 if ( $nonce !== null ) {
596 $attrs['nonce'] = $nonce;
597 } elseif ( ContentSecurityPolicy::isNonceRequired( MediaWikiServices::getInstance()->getMainConfig() ) ) {
598 wfWarn( "no nonce set on script. CSP will break it" );
599 }
600
601 return self::element( 'script', $attrs );
602 }
603
616 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
617 // Don't escape '>' since that is used
618 // as direct child selector.
619 // Remember, in css, there is no "x" for hexadecimal escapes, and
620 // the space immediately after an escape sequence is swallowed.
621 $contents = strtr( $contents, [
622 '<' => '\3C ',
623 // CDATA end tag for good measure, but the main security
624 // is from escaping the '<'.
625 ']]>' => '\5D\5D\3E '
626 ] );
627
628 if ( preg_match( '/[<&]/', $contents ) ) {
629 $contents = "/*<![CDATA[*/$contents/*]]>*/";
630 }
631
632 return self::rawElement( 'style', [
633 'media' => $media,
634 ] + $attribs, $contents );
635 }
636
645 public static function linkedStyle( $url, $media = 'all' ) {
646 return self::element( 'link', [
647 'rel' => 'stylesheet',
648 'href' => $url,
649 'media' => $media,
650 ] );
651 }
652
664 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
665 $attribs['type'] = $type;
666 $attribs['value'] = $value;
667 $attribs['name'] = $name;
668 return self::element( 'input', $attribs );
669 }
670
679 public static function check( $name, $checked = false, array $attribs = [] ) {
680 if ( isset( $attribs['value'] ) ) {
681 $value = $attribs['value'];
682 unset( $attribs['value'] );
683 } else {
684 $value = 1;
685 }
686
687 if ( $checked ) {
688 $attribs[] = 'checked';
689 }
690
691 return self::input( $name, $value, 'checkbox', $attribs );
692 }
693
703 private static function messageBox( $html, $className, $heading = '', $iconClassName = '' ) {
704 if ( $heading !== '' ) {
705 $html = self::element( 'h2', [], $heading ) . $html;
706 }
707 $coreClasses = [
708 'mw-message-box',
709 'cdx-message',
710 'cdx-message--block'
711 ];
712 if ( is_array( $className ) ) {
713 $className = array_merge(
714 $coreClasses,
715 $className
716 );
717 } else {
718 $className .= ' ' . implode( ' ', $coreClasses );
719 }
720 return self::rawElement( 'div', [ 'class' => $className ],
721 self::element( 'span', [ 'class' => [
722 'cdx-message__icon',
723 $iconClassName
724 ] ] ) .
725 self::rawElement( 'div', [
726 'class' => 'cdx-message__content'
727 ], $html )
728 );
729 }
730
740 public static function noticeBox( $html, $className, $heading = '', $iconClassName = '' ) {
741 return self::messageBox( $html, [
742 'mw-message-box-notice',
743 'cdx-message--notice',
744 $className
745 ], $heading, $iconClassName );
746 }
747
756 public static function warningBox( $html, $className = '' ) {
757 return self::messageBox( $html, [
758 'mw-message-box-warning',
759 'cdx-message--warning', $className ] );
760 }
761
771 public static function errorBox( $html, $heading = '', $className = '' ) {
772 return self::messageBox( $html, [
773 'mw-message-box-error',
774 'cdx-message--error', $className ], $heading );
775 }
776
785 public static function successBox( $html, $className = '' ) {
786 return self::messageBox( $html, [
787 'mw-message-box-success',
788 'cdx-message--success', $className ] );
789 }
790
799 public static function radio( $name, $checked = false, array $attribs = [] ) {
800 if ( isset( $attribs['value'] ) ) {
801 $value = $attribs['value'];
802 unset( $attribs['value'] );
803 } else {
804 $value = 1;
805 }
806
807 if ( $checked ) {
808 $attribs[] = 'checked';
809 }
810
811 return self::input( $name, $value, 'radio', $attribs );
812 }
813
822 public static function label( $label, $id, array $attribs = [] ) {
823 $attribs += [
824 'for' => $id,
825 ];
826 return self::element( 'label', $attribs, $label );
827 }
828
838 public static function hidden( $name, $value, array $attribs = [] ) {
839 return self::input( $name, $value, 'hidden', $attribs );
840 }
841
854 public static function textarea( $name, $value = '', array $attribs = [] ) {
855 $attribs['name'] = $name;
856
857 if ( substr( $value, 0, 1 ) == "\n" ) {
858 // Workaround for T14130: browsers eat the initial newline
859 // assuming that it's just for show, but they do keep the later
860 // newlines, which we may want to preserve during editing.
861 // Prepending a single newline
862 $spacedValue = "\n" . $value;
863 } else {
864 $spacedValue = $value;
865 }
866 return self::element( 'textarea', $attribs, $spacedValue );
867 }
868
874 public static function namespaceSelectorOptions( array $params = [] ) {
875 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
876 $params['exclude'] = [];
877 }
878
879 if ( $params['in-user-lang'] ?? false ) {
880 global $wgLang;
881 $lang = $wgLang;
882 } else {
883 $lang = MediaWikiServices::getInstance()->getContentLanguage();
884 }
885
886 $optionsOut = [];
887 if ( isset( $params['all'] ) ) {
888 // add an option that would let the user select all namespaces.
889 // Value is provided by user, the name shown is localized for the user.
890 $optionsOut[$params['all']] = wfMessage( 'namespacesall' )->text();
891 }
892 // Add all namespaces as options
893 $options = $lang->getFormattedNamespaces();
894 // Filter out namespaces below 0 and massage labels
895 foreach ( $options as $nsId => $nsName ) {
896 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
897 continue;
898 }
899 if ( $nsId === NS_MAIN ) {
900 // For other namespaces use the namespace prefix as label, but for
901 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
902 $nsName = wfMessage( 'blanknamespace' )->text();
903 } elseif ( is_int( $nsId ) ) {
904 $converter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
905 ->getLanguageConverter( $lang );
906 $nsName = $converter->convertNamespace( $nsId );
907 }
908 $optionsOut[$nsId] = $nsName;
909 }
910
911 return $optionsOut;
912 }
913
930 public static function namespaceSelector(
931 array $params = [],
932 array $selectAttribs = []
933 ) {
934 ksort( $selectAttribs );
935
936 // Is a namespace selected?
937 if ( isset( $params['selected'] ) ) {
938 // If string only contains digits, convert to clean int. Selected could also
939 // be "all" or "" etc. which needs to be left untouched.
940 if ( !is_int( $params['selected'] ) && ctype_digit( (string)$params['selected'] ) ) {
941 $params['selected'] = (int)$params['selected'];
942 }
943 // else: leaves it untouched for later processing
944 } else {
945 $params['selected'] = '';
946 }
947
948 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
949 $params['disable'] = [];
950 }
951
952 // Associative array between option-values and option-labels
954
955 // Convert $options to HTML
956 $optionsHtml = [];
957 foreach ( $options as $nsId => $nsName ) {
958 $optionsHtml[] = self::element(
959 'option',
960 [
961 'disabled' => in_array( $nsId, $params['disable'] ),
962 'value' => $nsId,
963 'selected' => $nsId === $params['selected'],
964 ],
965 $nsName
966 );
967 }
968
969 $selectAttribs['id'] ??= 'namespace';
970 $selectAttribs['name'] ??= 'namespace';
971
972 $ret = '';
973 if ( isset( $params['label'] ) ) {
974 $ret .= self::element(
975 'label', [
976 'for' => $selectAttribs['id'],
977 ], $params['label']
978 ) . "\u{00A0}";
979 }
980
981 // Wrap options in a <select>
982 $ret .= self::openElement( 'select', $selectAttribs )
983 . "\n"
984 . implode( "\n", $optionsHtml )
985 . "\n"
986 . self::closeElement( 'select' );
987
988 return $ret;
989 }
990
999 public static function htmlHeader( array $attribs = [] ) {
1000 $ret = '';
1001 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1002 $html5Version = $mainConfig->get( MainConfigNames::Html5Version );
1003 $mimeType = $mainConfig->get( MainConfigNames::MimeType );
1004 $xhtmlNamespaces = $mainConfig->get( MainConfigNames::XhtmlNamespaces );
1005
1006 $isXHTML = self::isXmlMimeType( $mimeType );
1007
1008 if ( $isXHTML ) { // XHTML5
1009 // XML MIME-typed markup should have an xml header.
1010 // However a DOCTYPE is not needed.
1011 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
1012
1013 // Add the standard xmlns
1014 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
1015
1016 // And support custom namespaces
1017 foreach ( $xhtmlNamespaces as $tag => $ns ) {
1018 $attribs["xmlns:$tag"] = $ns;
1019 }
1020 } else { // HTML5
1021 $ret .= "<!DOCTYPE html>\n";
1022 }
1023
1024 if ( $html5Version ) {
1025 $attribs['version'] = $html5Version;
1026 }
1027
1028 $ret .= self::openElement( 'html', $attribs );
1029
1030 return $ret;
1031 }
1032
1039 public static function isXmlMimeType( $mimetype ) {
1040 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
1041 # * text/xml
1042 # * application/xml
1043 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1044 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1045 }
1046
1070 public static function srcSet( array $urls ) {
1071 $candidates = [];
1072 foreach ( $urls as $density => $url ) {
1073 // Cast density to float to strip 'x', then back to string to serve
1074 // as array index.
1075 $density = (string)(float)$density;
1076 $candidates[$density] = $url;
1077 }
1078
1079 // Remove duplicates that are the same as a smaller value
1080 ksort( $candidates, SORT_NUMERIC );
1081 $candidates = array_unique( $candidates );
1082
1083 // Append density info to the url
1084 foreach ( $candidates as $density => $url ) {
1085 $candidates[$density] = $url . ' ' . $density . 'x';
1086 }
1087
1088 return implode( ", ", $candidates );
1089 }
1090
1105 public static function encodeJsVar( $value, $pretty = false ) {
1106 if ( $value instanceof HtmlJsCode ) {
1107 return $value->value;
1108 }
1109 return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
1110 }
1111
1126 public static function encodeJsCall( $name, $args, $pretty = false ) {
1127 $encodedArgs = self::encodeJsList( $args, $pretty );
1128 if ( $encodedArgs === false ) {
1129 return false;
1130 }
1131 return "$name($encodedArgs);";
1132 }
1133
1143 public static function encodeJsList( $args, $pretty = false ) {
1144 foreach ( $args as &$arg ) {
1145 $arg = self::encodeJsVar( $arg, $pretty );
1146 if ( $arg === false ) {
1147 return false;
1148 }
1149 }
1150 if ( $pretty ) {
1151 return ' ' . implode( ', ', $args ) . ' ';
1152 } else {
1153 return implode( ',', $args );
1154 }
1155 }
1156
1170 public static function listDropdownOptions( $list, $params = [] ) {
1171 $options = [];
1172
1173 if ( isset( $params['other'] ) ) {
1174 $options[ $params['other'] ] = 'other';
1175 }
1176
1177 $optgroup = false;
1178 foreach ( explode( "\n", $list ) as $option ) {
1179 $value = trim( $option );
1180 if ( $value == '' ) {
1181 continue;
1182 }
1183 if ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
1184 # A new group is starting...
1185 $value = trim( substr( $value, 1 ) );
1186 if ( $value !== '' &&
1187 // Do not use the value for 'other' as option group - T251351
1188 ( !isset( $params['other'] ) || $value !== $params['other'] )
1189 ) {
1190 $optgroup = $value;
1191 } else {
1192 $optgroup = false;
1193 }
1194 } elseif ( substr( $value, 0, 2 ) == '**' ) {
1195 # groupmember
1196 $opt = trim( substr( $value, 2 ) );
1197 if ( $optgroup === false ) {
1198 $options[$opt] = $opt;
1199 } else {
1200 $options[$optgroup][$opt] = $opt;
1201 }
1202 } else {
1203 # groupless reason list
1204 $optgroup = false;
1205 $options[$option] = $option;
1206 }
1207 }
1208
1209 return $options;
1210 }
1211
1220 public static function listDropdownOptionsOoui( $options ) {
1221 $optionsOoui = [];
1222
1223 foreach ( $options as $text => $value ) {
1224 if ( is_array( $value ) ) {
1225 $optionsOoui[] = [ 'optgroup' => (string)$text ];
1226 foreach ( $value as $text2 => $value2 ) {
1227 $optionsOoui[] = [ 'data' => (string)$value2, 'label' => (string)$text2 ];
1228 }
1229 } else {
1230 $optionsOoui[] = [ 'data' => (string)$value, 'label' => (string)$text ];
1231 }
1232 }
1233
1234 return $optionsOoui;
1235 }
1236}
1237
1239class_alias( Html::class, 'Html' );
const NS_MAIN
Definition Defines.php:64
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:536
array $params
The job parameters.
JSON formatter wrapper class.
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:593
static listDropdownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition Html.php:1220
static namespaceSelector(array $params=[], array $selectAttribs=[])
Build a drop-down box for selecting a namespace.
Definition Html.php:930
static warningBox( $html, $className='')
Return a warning box.
Definition Html.php:756
static check( $name, $checked=false, array $attribs=[])
Convenience function to produce a checkbox (input element with type=checkbox)
Definition Html.php:679
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition Html.php:1105
static label( $label, $id, array $attribs=[])
Convenience function for generating a label for inputs.
Definition Html.php:822
static expandAttributes(array $attribs)
Given an associative array of element attributes, generate a string to stick after the element name i...
Definition Html.php:463
static srcSet(array $urls)
Generate a srcset attribute value.
Definition Html.php:1070
static successBox( $html, $className='')
Return a success box.
Definition Html.php:785
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:1126
static htmlHeader(array $attribs=[])
Constructs the opening html-tag with necessary doctypes depending on global variables.
Definition Html.php:999
static errorBox( $html, $heading='', $className='')
Return an error box.
Definition Html.php:771
static inlineScript( $contents, $nonce=null)
Output an HTML script tag with the given contents.
Definition Html.php:576
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:799
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:1039
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:664
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition Html.php:838
static textarea( $name, $value='', array $attribs=[])
Convenience function to produce a <textarea> element.
Definition Html.php:854
static namespaceSelectorOptions(array $params=[])
Helper for Html::namespaceSelector().
Definition Html.php:874
static inlineStyle( $contents, $media='all', $attribs=[])
Output a "<style>" tag with the given contents for the given media type (if any).
Definition Html.php:616
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:1143
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:1170
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:645
static noticeBox( $html, $className, $heading='', $iconClassName='')
Return the HTML for a notice message box.
Definition Html.php:740
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.