19use UnexpectedValueException;
45privatestatic $voidElements = [
68privatestatic $boolAttribs = [
77'formnovalidate' =>
true,
94'typemustmatch' =>
true,
132publicstaticfunctionaddClass( &$classes,
string $class ): void {
133 $classes = (array)$classes;
134// Detect mistakes where $attrs is passed as $classes instead of $attrs['class'] 135foreach ( $classes as $key => $val ) {
137 ( is_int( $key ) && is_string( $val ) ) ||
138 ( is_string( $key ) && is_bool( $val ) )
140// Valid formats for class array entries 143wfWarn( __METHOD__ .
": Argument doesn't look like a class array: " . var_export( $classes,
true ) );
159publicstaticfunctionlinkButton( $text, array $attrs, array $modifiers = [] ) {
177publicstaticfunctionsubmitButton( $contents, array $attrs = [], array $modifiers = [] ) {
178 $attrs[
'type'] =
'submit';
179 $attrs[
'value'] = $contents;
205publicstaticfunctionrawElement( $element, $attribs = [], $contents =
'' ) {
206 $start = self::openElement( $element, $attribs );
207if ( isset( self::$voidElements[$element] ) ) {
210 $contents = Sanitizer::escapeCombiningChar( $contents ??
'' );
211return $start . $contents . self::closeElement( $element );
231publicstaticfunctionelement( $element, $attribs = [], $contents =
'' ) {
232return self::rawElement(
235 strtr( $contents ??
'', [
236// There's no point in escaping quotes, >, etc. in the contents of 256 $attribs = (array)$attribs;
257// This is not required in HTML5, but let's do it anyway, for 258// consistency and better compression. 259 $element = strtolower( $element );
261// Some people were abusing this by passing things like 262// 'h1 id="foo" to $element, which we don't want. 263if ( str_contains( $element,
' ' ) ) {
264wfWarn( __METHOD__ .
" given element name with space '$element'" );
267// Remove invalid input types 268if ( $element ==
'input' ) {
283'datetime-local' =>
true,
296if ( isset( $attribs[
'type'] ) && !isset( $validTypes[$attribs[
'type']] ) ) {
297 unset( $attribs[
'type'] );
301// According to standard the default type for <button> elements is "submit". 302// Depending on compatibility mode IE might use "button", instead. 303// We enforce the standard "submit". 304if ( $element ==
'button' && !isset( $attribs[
'type'] ) ) {
305 $attribs[
'type'] =
'submit';
308return"<$element" . self::expandAttributes(
309 self::dropDefaults( $element, $attribs ) ) .
'>';
320 $element = strtolower( $element );
342privatestaticfunction dropDefaults( $element, array $attribs ) {
343// Whenever altering this array, please provide a covering test case 344// in HtmlTest::provideElementsWithAttributesHavingDefaultValues 345static $attribDefaults = [
346'area' => [
'shape' =>
'rect' ],
349'formenctype' =>
'application/x-www-form-urlencoded',
357'autocomplete' =>
'on',
358'enctype' =>
'application/x-www-form-urlencoded',
364'keygen' => [
'keytype' =>
'rsa' ],
365'link' => [
'media' =>
'all' ],
366'menu' => [
'type' =>
'list' ],
367'script' => [
'type' =>
'text/javascript' ],
372'textarea' => [
'wrap' =>
'soft' ],
375foreach ( $attribs as $attrib => $value ) {
376if ( $attrib ===
'class' ) {
377if ( $value ===
'' || $value === [] || $value === [
'' ] ) {
378 unset( $attribs[$attrib] );
380 } elseif ( isset( $attribDefaults[$element][$attrib] ) ) {
381if ( is_array( $value ) ) {
382 $value = implode(
' ', $value );
384 $value = strval( $value );
386if ( $attribDefaults[$element][$attrib] == $value ) {
387 unset( $attribs[$attrib] );
393if ( $element ===
'link' 394 && isset( $attribs[
'type'] ) && strval( $attribs[
'type'] ) ==
'text/css' 396 unset( $attribs[
'type'] );
398if ( $element ===
'input' ) {
399 $type = $attribs[
'type'] ??
null;
400 $value = $attribs[
'value'] ??
null;
401if ( $type ===
'checkbox' || $type ===
'radio' ) {
402// The default value for checkboxes and radio buttons is 'on' 403// not ''. By stripping value="" we break radio boxes that 404// actually wants empty values. 405if ( $value ===
'on' ) {
406 unset( $attribs[
'value'] );
408 } elseif ( $type ===
'submit' ) {
409// The default value for submit appears to be "Submit" but 410// let's not bother stripping out localized text that matches 413// The default value for nearly every other field type is '' 414// The 'range' and 'color' types use different defaults but 415// stripping a value="" does not hurt them. 417 unset( $attribs[
'value'] );
421if ( $element ===
'select' && isset( $attribs[
'size'] ) ) {
422 $multiple = ( $attribs[
'multiple'] ?? false ) !==
false ||
423 in_array(
'multiple', $attribs );
424 $default = $multiple ? 4 : 1;
425if ( (
int)$attribs[
'size'] === $default ) {
426 unset( $attribs[
'size'] );
444// Convert into correct array. Array can contain space-separated 445// values. Implode/explode to get those into the main array as well. 446if ( is_array( $classes ) ) {
447// If input wasn't an array, we can skip this step 449foreach ( $classes as $k => $v ) {
450if ( is_string( $v ) ) {
451// String values should be normal `[ 'foo' ]` 453if ( !isset( $classes[$v] ) ) {
454// As a special case don't set 'foo' if a 455// separate 'foo' => true/false exists in the array 456// keys should be authoritative 457foreach ( explode(
' ', $v ) as $part ) {
458// Normalize spacing by fixing up cases where people used 459// more than 1 space and/or a trailing/leading space 460if ( $part !==
'' && $part !==
' ' ) {
461 $arrayValue[] = $part;
466// If the value is truthy but not a string this is likely 467// an [ 'foo' => true ], falsy values don't add strings 472 $arrayValue = explode(
' ', $classes );
473// Normalize spacing by fixing up cases where people used 474// more than 1 space and/or a trailing/leading space 475 $arrayValue = array_diff( $arrayValue, [
'',
' ' ] );
478// Remove duplicates and create the string 479return implode(
' ', array_unique( $arrayValue ) );
522foreach ( $attribs as $key => $value ) {
523// Support intuitive [ 'checked' => true/false ] form 524if ( $value ===
false || $value ===
null ) {
528// For boolean attributes, support [ 'foo' ] instead of 529// requiring [ 'foo' => 'meaningless' ]. 530if ( is_int( $key ) && isset( self::$boolAttribs[strtolower( $value )] ) ) {
534// Not technically required in HTML5 but we'd like consistency 535// and better compression anyway. 536 $key = strtolower( $key );
538// https://www.w3.org/TR/html401/index/attributes.html ("space-separated") 539// https://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated") 540 $spaceSeparatedListAttributes = [
541'class' =>
true,
// html4, html5 542'accesskey' =>
true,
// as of html5, multiple space-separated values allowed 543// html4-spec doesn't document rel= as space-separated 544// but has been used like that and is now documented as such 549// Specific features for attributes that allow a list of space-separated values 550if ( isset( $spaceSeparatedListAttributes[$key] ) ) {
551// Apply some normalization and remove duplicates 552 $value = self::expandClassList( $value );
554// Optimization: Skip below boolAttribs check and jump straight 555// to its `else` block. The current $spaceSeparatedListAttributes 556// block is mutually exclusive with $boolAttribs. 557// phpcs:ignore Generic.PHP.DiscourageGoto 558goto not_bool;
// NOSONAR 559 } elseif ( is_array( $value ) ) {
560thrownew UnexpectedValueException(
"HTML attribute $key can not contain a list of values" );
563if ( isset( self::$boolAttribs[$key] ) ) {
566// phpcs:ignore Generic.PHP.DiscourageGoto 568// Inlined from Sanitizer::encodeAttribute() for improved performance 569 $encValue = htmlspecialchars( $value, ENT_QUOTES );
570// Whitespace is normalized during attribute decoding, 571// so if we've been passed non-spaces we must encode them 572// ahead of time or they won't be preserved. 573 $encValue = strtr( $encValue, [
578 $ret .=
" $key=\"$encValue\"";
598if ( preg_match(
'/<\/?script/i', $contents ) ) {
599wfLogWarning( __METHOD__ .
': Illegal character sequence found in inline script.' );
600 $contents =
'/* ERROR: Invalid script */';
603return self::rawElement(
'script', [], $contents );
615 $attrs = [
'src' =>
$url ];
616if ( $nonce !==
null ) {
617 $attrs[
'nonce'] = $nonce;
618 } elseif ( ContentSecurityPolicy::isNonceRequired( MediaWikiServices::getInstance()->getMainConfig() ) ) {
619wfWarn(
"no nonce set on script. CSP will break it" );
622return self::element(
'script', $attrs );
637publicstaticfunctioninlineStyle( $contents, $media =
'all', $attribs = [] ) {
638// Don't escape '>' since that is used 639// as direct child selector. 640// Remember, in css, there is no "x" for hexadecimal escapes, and 641// the space immediately after an escape sequence is swallowed. 642 $contents = strtr( $contents, [
644// CDATA end tag for good measure, but the main security 645// is from escaping the '<'. 649if ( preg_match(
'/[<&]/', $contents ) ) {
650 $contents =
"/*<![CDATA[*/$contents/*]]>*/";
653return self::rawElement(
'style', [
655 ] + $attribs, $contents );
667return self::element(
'link', [
685publicstaticfunctioninput( $name, $value =
'', $type =
'text', array $attribs = [] ) {
686 $attribs[
'type'] = $type;
687 $attribs[
'value'] = $value;
688 $attribs[
'name'] = $name;
689return self::element(
'input', $attribs );
700publicstaticfunctioncheck( $name, $checked =
false, array $attribs = [] ) {
701 $value = $attribs[
'value'] ?? 1;
702 unset( $attribs[
'value'] );
703return self::element(
'input', [
705'checked' => (
bool)$checked,
722privatestaticfunction messageBox( $html, $className, $heading =
'', $iconClassName =
'' ) {
723if ( $heading !==
'' ) {
724 $html = self::element(
'h2', [], $heading ) . $html;
726 self::addClass( $className,
'cdx-message' );
727 self::addClass( $className,
'cdx-message--block' );
728return self::rawElement(
'div', [
'class' => $className ],
729 self::element(
'span', [
'class' => [
733 self::rawElement(
'div', [
734'class' =>
'cdx-message__content' 754publicstaticfunctionnoticeBox( $html, $className =
'', $heading =
'', $iconClassName =
'' ) {
755return self::messageBox( $html, [
756'cdx-message--notice',
758 ], $heading, $iconClassName );
776return self::messageBox( $html, [
777'cdx-message--warning', $className ] );
795publicstaticfunctionerrorBox( $html, $heading =
'', $className =
'' ) {
796return self::messageBox( $html, [
797'cdx-message--error', $className ], $heading );
815return self::messageBox( $html, [
816'cdx-message--success', $className ] );
827publicstaticfunctionradio( $name, $checked =
false, array $attribs = [] ) {
828 $value = $attribs[
'value'] ?? 1;
829 unset( $attribs[
'value'] );
830return self::element(
'input', [
832'checked' => (
bool)$checked,
847publicstaticfunctionlabel( $label, $id, array $attribs = [] ) {
851return self::element(
'label', $attribs, $label );
863publicstaticfunctionhidden( $name, $value, array $attribs = [] ) {
864return self::element(
'input', [
884publicstaticfunctiontextarea( $name, $value =
'', array $attribs = [] ) {
885 $attribs[
'name'] = $name;
887if ( str_starts_with( $value ??
'',
"\n" ) ) {
888// Workaround for T14130: browsers eat the initial newline 889// assuming that it's just for show, but they do keep the later 890// newlines, which we may want to preserve during editing. 891// Prepending a single newline 892 $spacedValue =
"\n" . $value;
894 $spacedValue = $value;
896return self::element(
'textarea', $attribs, $spacedValue );
905if ( !isset( $params[
'exclude'] ) || !is_array( $params[
'exclude'] ) ) {
906 $params[
'exclude'] = [];
909if ( $params[
'in-user-lang'] ??
false ) {
913 $lang = MediaWikiServices::getInstance()->getContentLanguage();
917if ( isset( $params[
'all'] ) ) {
918// add an option that would let the user select all namespaces. 919// Value is provided by user, the name shown is localized for the user. 920 $optionsOut[$params[
'all']] =
wfMessage(
'namespacesall' )->text();
922// Add all namespaces as options 923 $options = $lang->getFormattedNamespaces();
924// Filter out namespaces below 0 and massage labels 925foreach ( $options as $nsId => $nsName ) {
926if ( $nsId <
NS_MAIN || in_array( $nsId, $params[
'exclude'] ) ) {
930 isset( $params[
'include'] ) &&
931 is_array( $params[
'include'] ) &&
932 !in_array( $nsId, $params[
'include'] )
938// For other namespaces use the namespace prefix as label, but for 939// main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)") 940 $nsName =
wfMessage(
'blanknamespace' )->text();
941 } elseif ( is_int( $nsId ) ) {
942 $converter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
943 ->getLanguageConverter( $lang );
944 $nsName = $converter->convertNamespace( $nsId );
946 $optionsOut[$nsId] = $nsName;
970 array $selectAttribs = []
972 ksort( $selectAttribs );
974// Is a namespace selected? 975if ( isset( $params[
'selected'] ) ) {
976// If string only contains digits, convert to clean int. Selected could also 977// be "all" or "" etc. which needs to be left untouched. 978if ( !is_int( $params[
'selected'] ) && ctype_digit( (
string)$params[
'selected'] ) ) {
979 $params[
'selected'] = (int)$params[
'selected'];
981// else: leaves it untouched for later processing 983 $params[
'selected'] =
'';
986if ( !isset( $params[
'disable'] ) || !is_array( $params[
'disable'] ) ) {
987 $params[
'disable'] = [];
990// Associative array between option-values and option-labels 991 $options = self::namespaceSelectorOptions( $params );
993// Convert $options to HTML 995foreach ( $options as $nsId => $nsName ) {
996 $optionsHtml[] = self::element(
999'disabled' => in_array( $nsId, $params[
'disable'] ),
1001'selected' => $nsId === $params[
'selected'],
1007 $selectAttribs[
'id'] ??=
'namespace';
1008 $selectAttribs[
'name'] ??=
'namespace';
1011if ( isset( $params[
'label'] ) ) {
1012 $ret .= self::element(
1014'for' => $selectAttribs[
'id'],
1019// Wrap options in a <select> 1020 $ret .= self::openElement(
'select', $selectAttribs )
1022 . implode(
"\n", $optionsHtml )
1024 . self::closeElement(
'select' );
1039 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1040 $html5Version = $mainConfig->get( MainConfigNames::Html5Version );
1041 $mimeType = $mainConfig->get( MainConfigNames::MimeType );
1042 $xhtmlNamespaces = $mainConfig->get( MainConfigNames::XhtmlNamespaces );
1044 $isXHTML = self::isXmlMimeType( $mimeType );
1046if ( $isXHTML ) {
// XHTML5 1047// XML MIME-typed markup should have an xml header. 1048// However a DOCTYPE is not needed. 1049 $ret .=
"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
1051// Add the standard xmlns 1052 $attribs[
'xmlns'] =
'http://www.w3.org/1999/xhtml';
1054// And support custom namespaces 1055foreach ( $xhtmlNamespaces as $tag => $ns ) {
1056 $attribs[
"xmlns:$tag"] = $ns;
1059 $ret .=
"<!DOCTYPE html>\n";
1062if ( $html5Version ) {
1063 $attribs[
'version'] = $html5Version;
1066 $ret .= self::openElement(
'html', $attribs );
1078 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type 1081 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml) 1082return (
bool)preg_match(
'!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1110foreach ( $urls as $density =>
$url ) {
1111// Cast density to float to strip 'x', then back to string to serve 1113 $density = (string)(
float)$density;
1114 $candidates[$density] =
$url;
1117// Remove duplicates that are the same as a smaller value 1118 ksort( $candidates, SORT_NUMERIC );
1119 $candidates = array_unique( $candidates );
1121// Append density info to the url 1122foreach ( $candidates as $density =>
$url ) {
1123 $candidates[$density] =
$url .
' ' . $density .
'x';
1126return implode(
", ", $candidates );
1145return $value->value;
1147return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
1165 $encodedArgs = self::encodeJsList( $args, $pretty );
1166if ( $encodedArgs ===
false ) {
1169return"$name($encodedArgs);";
1182foreach ( $args as &$arg ) {
1183 $arg = self::encodeJsVar( $arg, $pretty );
1184if ( $arg ===
false ) {
1189return' ' . implode(
', ', $args ) .
' ';
1191return implode(
',', $args );
1211if ( isset( $params[
'other'] ) ) {
1212 $options[ $params[
'other'] ] =
'other';
1216foreach ( explode(
"\n", $list ) as $option ) {
1217 $value = trim( $option );
1221if ( str_starts_with( $value,
'*' ) && !str_starts_with( $value,
'**' ) ) {
1222 # A new group is starting... 1223 $value = trim( substr( $value, 1 ) );
1225// Do not use the value for 'other' as option group - T251351 1226 ( !isset( $params[
'other'] ) || $value !== $params[
'other'] )
1232 } elseif ( str_starts_with( $value,
'**' ) ) {
1234 $opt = trim( substr( $value, 2 ) );
1235if ( $optgroup ===
false ) {
1236 $options[$opt] = $opt;
1238 $options[$optgroup][$opt] = $opt;
1241 # groupless reason list 1243 $options[$option] = $option;
1261foreach ( $options as $text => $value ) {
1262if ( is_array( $value ) ) {
1263 $optionsOoui[] = [
'optgroup' => (string)$text ];
1264foreach ( $value as $text2 => $value2 ) {
1265 $optionsOoui[] = [
'data' => (string)$value2,
'label' => (
string)$text2 ];
1268 $optionsOoui[] = [
'data' => (string)$value,
'label' => (
string)$text ];
1286foreach ( $options as $text => $value ) {
1287if ( is_array( $value ) ) {
1289'label' => (string)$text,
1290'items' => array_map(
staticfunction ( $text2, $value2 ) {
1291return [
'label' => (string)$text2,
'value' => (
string)$value2 ];
1292 }, array_keys( $value ), $value )
1295 $optionsCodex[] = [
'label' => (string)$text,
'value' => (
string)$value ];
1298return $optionsCodex;
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(MW_ENTRY_POINT==='index') if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgLang
if(!defined('MW_SETUP_CALLBACK'))
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:
static linkedScript( $url, $nonce=null)
Output a "<script>" tag linking to the given URL, e.g., "<script src=foo.js></script>".
static listDropdownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
static namespaceSelector(array $params=[], array $selectAttribs=[])
Build a drop-down box for selecting a namespace.
static warningBox( $html, $className='')
Return a warning box.
static check( $name, $checked=false, array $attribs=[])
Convenience function to produce a checkbox (input element with type=checkbox)
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
static listDropdownOptionsCodex( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
static label( $label, $id, array $attribs=[])
Convenience function for generating a label for inputs.
static expandAttributes(array $attribs)
Given an associative array of element attributes, generate a string to stick after the element name i...
static srcSet(array $urls)
Generate a srcset attribute value.
static noticeBox( $html, $className='', $heading='', $iconClassName='')
Return the HTML for a notice message box.
static successBox( $html, $className='')
Return a success box.
static buttonAttributes(array $attrs, array $modifiers=[])
Modifies a set of attributes meant for button elements.
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
static htmlHeader(array $attribs=[])
Constructs the opening html-tag with necessary doctypes depending on global variables.
static errorBox( $html, $heading='', $className='')
Return an error box.
static inlineScript( $contents, $nonce=null)
Output an HTML script tag with the given contents.
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
static radio( $name, $checked=false, array $attribs=[])
Convenience function to produce a radio button (input element with type=radio)
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
static isXmlMimeType( $mimetype)
Determines if the given MIME type is xml.
static getTextInputAttributes(array $attrs)
Modifies a set of attributes meant for text input elements.
static expandClassList( $classes)
Convert a value for a 'class' attribute in a format accepted by Html::element() and similar methods t...
static input( $name, $value='', $type='text', array $attribs=[])
Convenience function to produce an <input> element.
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
static textarea( $name, $value='', array $attribs=[])
Convenience function to produce a <textarea> element.
static namespaceSelectorOptions(array $params=[])
Helper for Html::namespaceSelector().
static inlineStyle( $contents, $media='all', $attribs=[])
Output a "<style>" tag with the given contents for the given media type (if any).
static closeElement( $element)
Returns "</$element>".
static linkButton( $text, array $attrs, array $modifiers=[])
Returns an HTML link element in a string.
static submitButton( $contents, array $attrs=[], array $modifiers=[])
Returns an HTML input element in a string.
static encodeJsList( $args, $pretty=false)
Encode a JavaScript comma-separated list.
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
static listDropdownOptions( $list, $params=[])
Build options for a drop-down box from a textual list.
static linkedStyle( $url, $media='all')
Output a "<link rel=stylesheet>" linking to the given URL for the given media type (if any).
static addClass(&$classes, string $class)
Add a class to a 'class' attribute in a format accepted by Html::element().
JSON formatter wrapper class.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
HTML sanitizer for MediaWiki.
Handle sending Content-Security-Policy headers.
element(SerializerNode $parent, SerializerNode $node, $contents)