MediaWiki 1.41.2
Html.php
Go to the documentation of this file.
1<?php
26namespace MediaWiki\Html;
27
28use FormatJson;
29use InvalidArgumentException;
33use MWException;
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 $useMediaWikiUIEverywhere =
122 if ( $useMediaWikiUIEverywhere ) {
123 if ( isset( $attrs['class'] ) ) {
124 if ( is_array( $attrs['class'] ) ) {
125 $attrs['class'][] = 'mw-ui-button';
126 $attrs['class'] = array_merge( $attrs['class'], $modifiers );
127 // ensure compatibility with Xml
128 $attrs['class'] = implode( ' ', $attrs['class'] );
129 } else {
130 $attrs['class'] .= ' mw-ui-button ' . implode( ' ', $modifiers );
131 }
132 } else {
133 // ensure compatibility with Xml
134 $attrs['class'] = 'mw-ui-button ' . implode( ' ', $modifiers );
135 }
136 }
137 return $attrs;
138 }
139
147 public static function getTextInputAttributes( array $attrs ) {
148 $useMediaWikiUIEverywhere = MediaWikiServices::getInstance()
149 ->getMainConfig()->get( MainConfigNames::UseMediaWikiUIEverywhere );
150 if ( $useMediaWikiUIEverywhere ) {
151 $cdxInputClass = 'cdx-text-input__input';
152 // This will only apply if the input is not using official Codex classes.
153 // In future this should trigger a deprecation warning.
154 if ( isset( $attrs['class'] ) ) { // see expandAttributes() for supported attr formats
155 if ( is_array( $attrs['class'] ) ) {
156 if (
157 !in_array( $cdxInputClass, $attrs['class'], true ) &&
158 !( $attrs['class'][$cdxInputClass] ?? false )
159 ) {
160 $attrs['class']['mw-ui-input'] = true;
161 }
162 } elseif ( is_string( $attrs['class'] ) ) {
163 if ( !preg_match( "/(^| )$cdxInputClass($| )/", $attrs['class'] ) ) {
164 $attrs['class'] .= ' mw-ui-input';
165 }
166 } else {
167 throw new InvalidArgumentException(
168 'Unexpected class attr of type ' . gettype( $attrs['class'] )
169 );
170 }
171 } else {
172 $attrs['class'] = 'mw-ui-input';
173 }
174 }
175 return $attrs;
176 }
177
190 public static function linkButton( $text, array $attrs, array $modifiers = [] ) {
191 return self::element(
192 'a',
193 self::buttonAttributes( $attrs, $modifiers ),
194 $text
195 );
196 }
197
211 public static function submitButton( $contents, array $attrs, array $modifiers = [] ) {
212 $attrs['type'] = 'submit';
213 $attrs['value'] = $contents;
214 return self::element( 'input', self::buttonAttributes( $attrs, $modifiers ) );
215 }
216
239 public static function rawElement( $element, $attribs = [], $contents = '' ) {
240 $start = self::openElement( $element, $attribs );
241 if ( isset( self::$voidElements[$element] ) ) {
242 return $start;
243 } else {
244 return $start . $contents . self::closeElement( $element );
245 }
246 }
247
264 public static function element( $element, $attribs = [], $contents = '' ) {
265 return self::rawElement(
266 $element,
267 $attribs,
268 strtr( $contents ?? '', [
269 // There's no point in escaping quotes, >, etc. in the contents of
270 // elements.
271 '&' => '&amp;',
272 '<' => '&lt;',
273 ] )
274 );
275 }
276
288 public static function openElement( $element, $attribs = [] ) {
289 $attribs = (array)$attribs;
290 // This is not required in HTML5, but let's do it anyway, for
291 // consistency and better compression.
292 $element = strtolower( $element );
293
294 // Some people were abusing this by passing things like
295 // 'h1 id="foo" to $element, which we don't want.
296 if ( str_contains( $element, ' ' ) ) {
297 wfWarn( __METHOD__ . " given element name with space '$element'" );
298 }
299
300 // Remove invalid input types
301 if ( $element == 'input' ) {
302 $validTypes = [
303 'hidden' => true,
304 'text' => true,
305 'password' => true,
306 'checkbox' => true,
307 'radio' => true,
308 'file' => true,
309 'submit' => true,
310 'image' => true,
311 'reset' => true,
312 'button' => true,
313
314 // HTML input types
315 'datetime' => true,
316 'datetime-local' => true,
317 'date' => true,
318 'month' => true,
319 'time' => true,
320 'week' => true,
321 'number' => true,
322 'range' => true,
323 'email' => true,
324 'url' => true,
325 'search' => true,
326 'tel' => true,
327 'color' => true,
328 ];
329 if ( isset( $attribs['type'] ) && !isset( $validTypes[$attribs['type']] ) ) {
330 unset( $attribs['type'] );
331 }
332 }
333
334 // According to standard the default type for <button> elements is "submit".
335 // Depending on compatibility mode IE might use "button", instead.
336 // We enforce the standard "submit".
337 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
338 $attribs['type'] = 'submit';
339 }
340
341 return "<$element" . self::expandAttributes(
342 self::dropDefaults( $element, $attribs ) ) . '>';
343 }
344
352 public static function closeElement( $element ) {
353 $element = strtolower( $element );
354
355 return "</$element>";
356 }
357
375 private static function dropDefaults( $element, array $attribs ) {
376 // Whenever altering this array, please provide a covering test case
377 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
378 static $attribDefaults = [
379 'area' => [ 'shape' => 'rect' ],
380 'button' => [
381 'formaction' => 'GET',
382 'formenctype' => 'application/x-www-form-urlencoded',
383 ],
384 'canvas' => [
385 'height' => '150',
386 'width' => '300',
387 ],
388 'form' => [
389 'action' => 'GET',
390 'autocomplete' => 'on',
391 'enctype' => 'application/x-www-form-urlencoded',
392 ],
393 'input' => [
394 'formaction' => 'GET',
395 'type' => 'text',
396 ],
397 'keygen' => [ 'keytype' => 'rsa' ],
398 'link' => [ 'media' => 'all' ],
399 'menu' => [ 'type' => 'list' ],
400 'script' => [ 'type' => 'text/javascript' ],
401 'style' => [
402 'media' => 'all',
403 'type' => 'text/css',
404 ],
405 'textarea' => [ 'wrap' => 'soft' ],
406 ];
407
408 foreach ( $attribs as $attrib => $value ) {
409 if ( $attrib === 'class' ) {
410 if ( $value === '' || $value === [] || $value === [ '' ] ) {
411 unset( $attribs[$attrib] );
412 }
413 } elseif ( isset( $attribDefaults[$element][$attrib] ) ) {
414 if ( is_array( $value ) ) {
415 $value = implode( ' ', $value );
416 } else {
417 $value = strval( $value );
418 }
419 if ( $attribDefaults[$element][$attrib] == $value ) {
420 unset( $attribs[$attrib] );
421 }
422 }
423 }
424
425 // More subtle checks
426 if ( $element === 'link'
427 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
428 ) {
429 unset( $attribs['type'] );
430 }
431 if ( $element === 'input' ) {
432 $type = $attribs['type'] ?? null;
433 $value = $attribs['value'] ?? null;
434 if ( $type === 'checkbox' || $type === 'radio' ) {
435 // The default value for checkboxes and radio buttons is 'on'
436 // not ''. By stripping value="" we break radio boxes that
437 // actually wants empty values.
438 if ( $value === 'on' ) {
439 unset( $attribs['value'] );
440 }
441 } elseif ( $type === 'submit' ) {
442 // The default value for submit appears to be "Submit" but
443 // let's not bother stripping out localized text that matches
444 // that.
445 } else {
446 // The default value for nearly every other field type is ''
447 // The 'range' and 'color' types use different defaults but
448 // stripping a value="" does not hurt them.
449 if ( $value === '' ) {
450 unset( $attribs['value'] );
451 }
452 }
453 }
454 if ( $element === 'select' && isset( $attribs['size'] ) ) {
455 if ( in_array( 'multiple', $attribs )
456 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
457 ) {
458 // A multi-select
459 if ( strval( $attribs['size'] ) == '4' ) {
460 unset( $attribs['size'] );
461 }
462 } else {
463 // Single select
464 if ( strval( $attribs['size'] ) == '1' ) {
465 unset( $attribs['size'] );
466 }
467 }
468 }
469
470 return $attribs;
471 }
472
512 public static function expandAttributes( array $attribs ) {
513 $ret = '';
514 foreach ( $attribs as $key => $value ) {
515 // Support intuitive [ 'checked' => true/false ] form
516 if ( $value === false || $value === null ) {
517 continue;
518 }
519
520 // For boolean attributes, support [ 'foo' ] instead of
521 // requiring [ 'foo' => 'meaningless' ].
522 if ( is_int( $key ) && isset( self::$boolAttribs[strtolower( $value )] ) ) {
523 $key = $value;
524 }
525
526 // Not technically required in HTML5 but we'd like consistency
527 // and better compression anyway.
528 $key = strtolower( $key );
529
530 // https://www.w3.org/TR/html401/index/attributes.html ("space-separated")
531 // https://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
532 $spaceSeparatedListAttributes = [
533 'class' => true, // html4, html5
534 'accesskey' => true, // as of html5, multiple space-separated values allowed
535 // html4-spec doesn't document rel= as space-separated
536 // but has been used like that and is now documented as such
537 // in the html5-spec.
538 'rel' => true,
539 ];
540
541 // Specific features for attributes that allow a list of space-separated values
542 if ( isset( $spaceSeparatedListAttributes[$key] ) ) {
543 // Apply some normalization and remove duplicates
544
545 // Convert into correct array. Array can contain space-separated
546 // values. Implode/explode to get those into the main array as well.
547 if ( is_array( $value ) ) {
548 // If input wasn't an array, we can skip this step
549 $arrayValue = [];
550 foreach ( $value as $k => $v ) {
551 if ( is_string( $v ) ) {
552 // String values should be normal `[ 'foo' ]`
553 // Just append them
554 if ( !isset( $value[$v] ) ) {
555 // As a special case don't set 'foo' if a
556 // separate 'foo' => true/false exists in the array
557 // keys should be authoritative
558 foreach ( explode( ' ', $v ) as $part ) {
559 // Normalize spacing by fixing up cases where people used
560 // more than 1 space and/or a trailing/leading space
561 if ( $part !== '' && $part !== ' ' ) {
562 $arrayValue[] = $part;
563 }
564 }
565 }
566 } elseif ( $v ) {
567 // If the value is truthy but not a string this is likely
568 // an [ 'foo' => true ], falsy values don't add strings
569 $arrayValue[] = $k;
570 }
571 }
572 } else {
573 $arrayValue = explode( ' ', $value );
574 // Normalize spacing by fixing up cases where people used
575 // more than 1 space and/or a trailing/leading space
576 $arrayValue = array_diff( $arrayValue, [ '', ' ' ] );
577 }
578
579 // Remove duplicates and create the string
580 $value = implode( ' ', array_unique( $arrayValue ) );
581
582 // Optimization: Skip below boolAttribs check and jump straight
583 // to its `else` block. The current $spaceSeparatedListAttributes
584 // block is mutually exclusive with $boolAttribs.
585 // phpcs:ignore Generic.PHP.DiscourageGoto
586 goto not_bool; // NOSONAR
587 } elseif ( is_array( $value ) ) {
588 throw new MWException( "HTML attribute $key can not contain a list of values" );
589 }
590
591 if ( isset( self::$boolAttribs[$key] ) ) {
592 $ret .= " $key=\"\"";
593 } else {
594 // phpcs:ignore Generic.PHP.DiscourageGoto
595 not_bool:
596 // Inlined from Sanitizer::encodeAttribute() for improved performance
597 $encValue = htmlspecialchars( $value, ENT_QUOTES );
598 // Whitespace is normalized during attribute decoding,
599 // so if we've been passed non-spaces we must encode them
600 // ahead of time or they won't be preserved.
601 $encValue = strtr( $encValue, [
602 "\n" => '&#10;',
603 "\r" => '&#13;',
604 "\t" => '&#9;',
605 ] );
606 $ret .= " $key=\"$encValue\"";
607 }
608 }
609 return $ret;
610 }
611
625 public static function inlineScript( $contents, $nonce = null ) {
626 if ( preg_match( '/<\/?script/i', $contents ) ) {
627 wfLogWarning( __METHOD__ . ': Illegal character sequence found in inline script.' );
628 $contents = '/* ERROR: Invalid script */';
629 }
630
631 return self::rawElement( 'script', [], $contents );
632 }
633
642 public static function linkedScript( $url, $nonce = null ) {
643 $attrs = [ 'src' => $url ];
644 if ( $nonce !== null ) {
645 $attrs['nonce'] = $nonce;
646 } elseif ( ContentSecurityPolicy::isNonceRequired( MediaWikiServices::getInstance()->getMainConfig() ) ) {
647 wfWarn( "no nonce set on script. CSP will break it" );
648 }
649
650 return self::element( 'script', $attrs );
651 }
652
665 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
666 // Don't escape '>' since that is used
667 // as direct child selector.
668 // Remember, in css, there is no "x" for hexadecimal escapes, and
669 // the space immediately after an escape sequence is swallowed.
670 $contents = strtr( $contents, [
671 '<' => '\3C ',
672 // CDATA end tag for good measure, but the main security
673 // is from escaping the '<'.
674 ']]>' => '\5D\5D\3E '
675 ] );
676
677 if ( preg_match( '/[<&]/', $contents ) ) {
678 $contents = "/*<![CDATA[*/$contents/*]]>*/";
679 }
680
681 return self::rawElement( 'style', [
682 'media' => $media,
683 ] + $attribs, $contents );
684 }
685
694 public static function linkedStyle( $url, $media = 'all' ) {
695 return self::element( 'link', [
696 'rel' => 'stylesheet',
697 'href' => $url,
698 'media' => $media,
699 ] );
700 }
701
713 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
714 $attribs['type'] = $type;
715 $attribs['value'] = $value;
716 $attribs['name'] = $name;
717 $textInputAttributes = [
718 'text' => true,
719 'search' => true,
720 'email' => true,
721 'password' => true,
722 'number' => true,
723 ];
724 if ( isset( $textInputAttributes[$type] ) ) {
725 $attribs = self::getTextInputAttributes( $attribs );
726 }
727 $buttonAttributes = [
728 'button' => true,
729 'reset' => true,
730 'submit' => true,
731 ];
732 if ( isset( $buttonAttributes[$type] ) ) {
733 $attribs = self::buttonAttributes( $attribs );
734 }
735 return self::element( 'input', $attribs );
736 }
737
746 public static function check( $name, $checked = false, array $attribs = [] ) {
747 if ( isset( $attribs['value'] ) ) {
748 $value = $attribs['value'];
749 unset( $attribs['value'] );
750 } else {
751 $value = 1;
752 }
753
754 if ( $checked ) {
755 $attribs[] = 'checked';
756 }
757
758 return self::input( $name, $value, 'checkbox', $attribs );
759 }
760
770 private static function messageBox( $html, $className, $heading = '', $iconClassName = '' ) {
771 if ( $heading !== '' ) {
772 $html = self::element( 'h2', [], $heading ) . $html;
773 }
774 $coreClasses = [
775 'mw-message-box',
776 'cdx-message',
777 'cdx-message--block'
778 ];
779 if ( is_array( $className ) ) {
780 $className = array_merge(
781 $coreClasses,
782 $className
783 );
784 } else {
785 $className .= ' ' . implode( ' ', $coreClasses );
786 }
787 return self::rawElement( 'div', [ 'class' => $className ],
788 self::element( 'span', [ 'class' => [
789 'cdx-message__icon',
790 $iconClassName
791 ] ] ) .
792 self::rawElement( 'div', [
793 'class' => 'cdx-message__content'
794 ], $html )
795 );
796 }
797
807 public static function noticeBox( $html, $className, $heading = '', $iconClassName = '' ) {
808 return self::messageBox( $html, [
809 'mw-message-box-notice',
810 'cdx-message--notice',
811 $className
812 ], $heading, $iconClassName );
813 }
814
823 public static function warningBox( $html, $className = '' ) {
824 return self::messageBox( $html, [
825 'mw-message-box-warning',
826 'cdx-message--warning', $className ] );
827 }
828
838 public static function errorBox( $html, $heading = '', $className = '' ) {
839 return self::messageBox( $html, [
840 'mw-message-box-error',
841 'cdx-message--error', $className ], $heading );
842 }
843
852 public static function successBox( $html, $className = '' ) {
853 return self::messageBox( $html, [
854 'mw-message-box-success',
855 'cdx-message--success', $className ] );
856 }
857
866 public static function radio( $name, $checked = false, array $attribs = [] ) {
867 if ( isset( $attribs['value'] ) ) {
868 $value = $attribs['value'];
869 unset( $attribs['value'] );
870 } else {
871 $value = 1;
872 }
873
874 if ( $checked ) {
875 $attribs[] = 'checked';
876 }
877
878 return self::input( $name, $value, 'radio', $attribs );
879 }
880
889 public static function label( $label, $id, array $attribs = [] ) {
890 $attribs += [
891 'for' => $id,
892 ];
893 return self::element( 'label', $attribs, $label );
894 }
895
905 public static function hidden( $name, $value, array $attribs = [] ) {
906 return self::input( $name, $value, 'hidden', $attribs );
907 }
908
921 public static function textarea( $name, $value = '', array $attribs = [] ) {
922 $attribs['name'] = $name;
923
924 if ( substr( $value, 0, 1 ) == "\n" ) {
925 // Workaround for T14130: browsers eat the initial newline
926 // assuming that it's just for show, but they do keep the later
927 // newlines, which we may want to preserve during editing.
928 // Prepending a single newline
929 $spacedValue = "\n" . $value;
930 } else {
931 $spacedValue = $value;
932 }
933 return self::element( 'textarea', self::getTextInputAttributes( $attribs ), $spacedValue );
934 }
935
941 public static function namespaceSelectorOptions( array $params = [] ) {
942 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
943 $params['exclude'] = [];
944 }
945
946 if ( $params['in-user-lang'] ?? false ) {
947 global $wgLang;
948 $lang = $wgLang;
949 } else {
950 $lang = MediaWikiServices::getInstance()->getContentLanguage();
951 }
952
953 $optionsOut = [];
954 if ( isset( $params['all'] ) ) {
955 // add an option that would let the user select all namespaces.
956 // Value is provided by user, the name shown is localized for the user.
957 $optionsOut[$params['all']] = wfMessage( 'namespacesall' )->text();
958 }
959 // Add all namespaces as options
960 $options = $lang->getFormattedNamespaces();
961 // Filter out namespaces below 0 and massage labels
962 foreach ( $options as $nsId => $nsName ) {
963 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
964 continue;
965 }
966 if ( $nsId === NS_MAIN ) {
967 // For other namespaces use the namespace prefix as label, but for
968 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
969 $nsName = wfMessage( 'blanknamespace' )->text();
970 } elseif ( is_int( $nsId ) ) {
971 $converter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
972 ->getLanguageConverter( $lang );
973 $nsName = $converter->convertNamespace( $nsId );
974 }
975 $optionsOut[$nsId] = $nsName;
976 }
977
978 return $optionsOut;
979 }
980
997 public static function namespaceSelector(
998 array $params = [],
999 array $selectAttribs = []
1000 ) {
1001 ksort( $selectAttribs );
1002
1003 // Is a namespace selected?
1004 if ( isset( $params['selected'] ) ) {
1005 // If string only contains digits, convert to clean int. Selected could also
1006 // be "all" or "" etc. which needs to be left untouched.
1007 if ( !is_int( $params['selected'] ) && ctype_digit( (string)$params['selected'] ) ) {
1008 $params['selected'] = (int)$params['selected'];
1009 }
1010 // else: leaves it untouched for later processing
1011 } else {
1012 $params['selected'] = '';
1013 }
1014
1015 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
1016 $params['disable'] = [];
1017 }
1018
1019 // Associative array between option-values and option-labels
1020 $options = self::namespaceSelectorOptions( $params );
1021
1022 // Convert $options to HTML
1023 $optionsHtml = [];
1024 foreach ( $options as $nsId => $nsName ) {
1025 $optionsHtml[] = self::element(
1026 'option',
1027 [
1028 'disabled' => in_array( $nsId, $params['disable'] ),
1029 'value' => $nsId,
1030 'selected' => $nsId === $params['selected'],
1031 ],
1032 $nsName
1033 );
1034 }
1035
1036 if ( !array_key_exists( 'id', $selectAttribs ) ) {
1037 $selectAttribs['id'] = 'namespace';
1038 }
1039
1040 if ( !array_key_exists( 'name', $selectAttribs ) ) {
1041 $selectAttribs['name'] = 'namespace';
1042 }
1043
1044 $ret = '';
1045 if ( isset( $params['label'] ) ) {
1046 $ret .= self::element(
1047 'label', [
1048 'for' => $selectAttribs['id'] ?? null,
1049 ], $params['label']
1050 ) . "\u{00A0}";
1051 }
1052
1053 // Wrap options in a <select>
1054 $ret .= self::openElement( 'select', $selectAttribs )
1055 . "\n"
1056 . implode( "\n", $optionsHtml )
1057 . "\n"
1058 . self::closeElement( 'select' );
1059
1060 return $ret;
1061 }
1062
1071 public static function htmlHeader( array $attribs = [] ) {
1072 $ret = '';
1073 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1074 $html5Version = $mainConfig->get( MainConfigNames::Html5Version );
1075 $mimeType = $mainConfig->get( MainConfigNames::MimeType );
1076 $xhtmlNamespaces = $mainConfig->get( MainConfigNames::XhtmlNamespaces );
1077
1078 $isXHTML = self::isXmlMimeType( $mimeType );
1079
1080 if ( $isXHTML ) { // XHTML5
1081 // XML MIME-typed markup should have an xml header.
1082 // However a DOCTYPE is not needed.
1083 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
1084
1085 // Add the standard xmlns
1086 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
1087
1088 // And support custom namespaces
1089 foreach ( $xhtmlNamespaces as $tag => $ns ) {
1090 $attribs["xmlns:$tag"] = $ns;
1091 }
1092 } else { // HTML5
1093 $ret .= "<!DOCTYPE html>\n";
1094 }
1095
1096 if ( $html5Version ) {
1097 $attribs['version'] = $html5Version;
1098 }
1099
1100 $ret .= self::openElement( 'html', $attribs );
1101
1102 return $ret;
1103 }
1104
1111 public static function isXmlMimeType( $mimetype ) {
1112 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
1113 # * text/xml
1114 # * application/xml
1115 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1116 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1117 }
1118
1142 public static function srcSet( array $urls ) {
1143 $candidates = [];
1144 foreach ( $urls as $density => $url ) {
1145 // Cast density to float to strip 'x', then back to string to serve
1146 // as array index.
1147 $density = (string)(float)$density;
1148 $candidates[$density] = $url;
1149 }
1150
1151 // Remove duplicates that are the same as a smaller value
1152 ksort( $candidates, SORT_NUMERIC );
1153 $candidates = array_unique( $candidates );
1154
1155 // Append density info to the url
1156 foreach ( $candidates as $density => $url ) {
1157 $candidates[$density] = $url . ' ' . $density . 'x';
1158 }
1159
1160 return implode( ", ", $candidates );
1161 }
1162
1177 public static function encodeJsVar( $value, $pretty = false ) {
1178 if ( $value instanceof HtmlJsCode ) {
1179 return $value->value;
1180 }
1181 return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
1182 }
1183
1198 public static function encodeJsCall( $name, $args, $pretty = false ) {
1199 $encodedArgs = self::encodeJsList( $args, $pretty );
1200 if ( $encodedArgs === false ) {
1201 return false;
1202 }
1203 return "$name($encodedArgs);";
1204 }
1205
1215 public static function encodeJsList( $args, $pretty = false ) {
1216 foreach ( $args as &$arg ) {
1217 $arg = self::encodeJsVar( $arg, $pretty );
1218 if ( $arg === false ) {
1219 return false;
1220 }
1221 }
1222 if ( $pretty ) {
1223 return ' ' . implode( ', ', $args ) . ' ';
1224 } else {
1225 return implode( ',', $args );
1226 }
1227 }
1228}
1229
1233class_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.
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode $wgLang
Definition Setup.php:535
JSON formatter wrapper class.
MediaWiki exception.
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:642
static namespaceSelector(array $params=[], array $selectAttribs=[])
Build a drop-down box for selecting a namespace.
Definition Html.php:997
static warningBox( $html, $className='')
Return a warning box.
Definition Html.php:823
static check( $name, $checked=false, array $attribs=[])
Convenience function to produce a checkbox (input element with type=checkbox)
Definition Html.php:746
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition Html.php:1177
static label( $label, $id, array $attribs=[])
Convenience function for generating a label for inputs.
Definition Html.php:889
static expandAttributes(array $attribs)
Given an associative array of element attributes, generate a string to stick after the element name i...
Definition Html.php:512
static srcSet(array $urls)
Generate a srcset attribute value.
Definition Html.php:1142
static successBox( $html, $className='')
Return a success box.
Definition Html.php:852
static buttonAttributes(array $attrs, array $modifiers=[])
Modifies a set of attributes meant for button elements and apply a set of default attributes when $wg...
Definition Html.php:119
static submitButton( $contents, array $attrs, array $modifiers=[])
Returns an HTML link element in a string styled as a button (when $wgUseMediaWikiUIEverywhere is enab...
Definition Html.php:211
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition Html.php:1198
static htmlHeader(array $attribs=[])
Constructs the opening html-tag with necessary doctypes depending on global variables.
Definition Html.php:1071
static errorBox( $html, $heading='', $className='')
Return an error box.
Definition Html.php:838
static inlineScript( $contents, $nonce=null)
Output an HTML script tag with the given contents.
Definition Html.php:625
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition Html.php:288
static radio( $name, $checked=false, array $attribs=[])
Convenience function to produce a radio button (input element with type=radio)
Definition Html.php:866
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition Html.php:239
static isXmlMimeType( $mimetype)
Determines if the given MIME type is xml.
Definition Html.php:1111
static getTextInputAttributes(array $attrs)
Modifies a set of attributes meant for text input elements and apply a set of default attributes.
Definition Html.php:147
static input( $name, $value='', $type='text', array $attribs=[])
Convenience function to produce an "<input>" element.
Definition Html.php:713
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition Html.php:905
static textarea( $name, $value='', array $attribs=[])
Convenience function to produce a <textarea> element.
Definition Html.php:921
static namespaceSelectorOptions(array $params=[])
Helper for Html::namespaceSelector().
Definition Html.php:941
static inlineStyle( $contents, $media='all', $attribs=[])
Output a "<style>" tag with the given contents for the given media type (if any).
Definition Html.php:665
static closeElement( $element)
Returns "</$element>".
Definition Html.php:352
static linkButton( $text, array $attrs, array $modifiers=[])
Returns an HTML link element in a string styled as a button (when $wgUseMediaWikiUIEverywhere is enab...
Definition Html.php:190
static encodeJsList( $args, $pretty=false)
Encode a JavaScript comma-separated list.
Definition Html.php:1215
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition Html.php:264
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:694
static noticeBox( $html, $className, $heading='', $iconClassName='')
Return the HTML for a notice message box.
Definition Html.php:807
A class containing constants representing the names of configuration variables.
const MimeType
Name constant for the MimeType setting, for use with Config::get()
const UseMediaWikiUIEverywhere
Name constant for the UseMediaWikiUIEverywhere 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.