MediaWiki  master
Html.php
Go to the documentation of this file.
1 <?php
26 namespace MediaWiki\Html;
27 
28 use FormatJson;
29 use InvalidArgumentException;
33 use MWException;
34 
57 class 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 ( strpos( $element, ' ' ) !== false ) {
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;
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 
769  private static function messageBox( $html, $className, $heading = '' ) {
770  if ( $heading !== '' ) {
771  $html = self::element( 'h2', [], $heading ) . $html;
772  }
773  $coreClasses = [
774  'mw-message-box',
775  'cdx-message',
776  'cdx-message--block'
777  ];
778  if ( is_array( $className ) ) {
779  $className = array_merge(
780  $coreClasses,
781  $className
782  );
783  } else {
784  $className .= ' ' . implode( ' ', $coreClasses );
785  }
786  return self::rawElement( 'div', [ 'class' => $className ],
787  self::element( 'span', [ 'class' => 'cdx-message__icon' ] ) .
788  self::rawElement( 'div', [
789  'class' => 'cdx-message__content'
790  ], $html )
791  );
792  }
793 
801  public static function noticeBox( $html, $className ) {
802  return self::messageBox( $html, [
803  'mw-message-box-notice',
804  'cdx-message--notice', $className ] );
805  }
806 
815  public static function warningBox( $html, $className = '' ) {
816  return self::messageBox( $html, [
817  'mw-message-box-warning',
818  'cdx-message--warning', $className ] );
819  }
820 
830  public static function errorBox( $html, $heading = '', $className = '' ) {
831  return self::messageBox( $html, [
832  'mw-message-box-error',
833  'cdx-message--error', $className ], $heading );
834  }
835 
844  public static function successBox( $html, $className = '' ) {
845  return self::messageBox( $html, [
846  'mw-message-box-success',
847  'cdx-message--success', $className ] );
848  }
849 
858  public static function radio( $name, $checked = false, array $attribs = [] ) {
859  if ( isset( $attribs['value'] ) ) {
860  $value = $attribs['value'];
861  unset( $attribs['value'] );
862  } else {
863  $value = 1;
864  }
865 
866  if ( $checked ) {
867  $attribs[] = 'checked';
868  }
869 
870  return self::input( $name, $value, 'radio', $attribs );
871  }
872 
881  public static function label( $label, $id, array $attribs = [] ) {
882  $attribs += [
883  'for' => $id,
884  ];
885  return self::element( 'label', $attribs, $label );
886  }
887 
897  public static function hidden( $name, $value, array $attribs = [] ) {
898  return self::input( $name, $value, 'hidden', $attribs );
899  }
900 
913  public static function textarea( $name, $value = '', array $attribs = [] ) {
914  $attribs['name'] = $name;
915 
916  if ( substr( $value, 0, 1 ) == "\n" ) {
917  // Workaround for T14130: browsers eat the initial newline
918  // assuming that it's just for show, but they do keep the later
919  // newlines, which we may want to preserve during editing.
920  // Prepending a single newline
921  $spacedValue = "\n" . $value;
922  } else {
923  $spacedValue = $value;
924  }
925  return self::element( 'textarea', self::getTextInputAttributes( $attribs ), $spacedValue );
926  }
927 
933  public static function namespaceSelectorOptions( array $params = [] ) {
934  if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
935  $params['exclude'] = [];
936  }
937 
938  if ( $params['in-user-lang'] ?? false ) {
939  global $wgLang;
940  $lang = $wgLang;
941  } else {
942  $lang = MediaWikiServices::getInstance()->getContentLanguage();
943  }
944 
945  $optionsOut = [];
946  if ( isset( $params['all'] ) ) {
947  // add an option that would let the user select all namespaces.
948  // Value is provided by user, the name shown is localized for the user.
949  $optionsOut[$params['all']] = wfMessage( 'namespacesall' )->text();
950  }
951  // Add all namespaces as options
952  $options = $lang->getFormattedNamespaces();
953  // Filter out namespaces below 0 and massage labels
954  foreach ( $options as $nsId => $nsName ) {
955  if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
956  continue;
957  }
958  if ( $nsId === NS_MAIN ) {
959  // For other namespaces use the namespace prefix as label, but for
960  // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
961  $nsName = wfMessage( 'blanknamespace' )->text();
962  } elseif ( is_int( $nsId ) ) {
963  $converter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
964  ->getLanguageConverter( $lang );
965  $nsName = $converter->convertNamespace( $nsId );
966  }
967  $optionsOut[$nsId] = $nsName;
968  }
969 
970  return $optionsOut;
971  }
972 
989  public static function namespaceSelector(
990  array $params = [],
991  array $selectAttribs = []
992  ) {
993  ksort( $selectAttribs );
994 
995  // Is a namespace selected?
996  if ( isset( $params['selected'] ) ) {
997  // If string only contains digits, convert to clean int. Selected could also
998  // be "all" or "" etc. which needs to be left untouched.
999  if ( !is_int( $params['selected'] ) && ctype_digit( (string)$params['selected'] ) ) {
1000  $params['selected'] = (int)$params['selected'];
1001  }
1002  // else: leaves it untouched for later processing
1003  } else {
1004  $params['selected'] = '';
1005  }
1006 
1007  if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
1008  $params['disable'] = [];
1009  }
1010 
1011  // Associative array between option-values and option-labels
1012  $options = self::namespaceSelectorOptions( $params );
1013 
1014  // Convert $options to HTML
1015  $optionsHtml = [];
1016  foreach ( $options as $nsId => $nsName ) {
1017  $optionsHtml[] = self::element(
1018  'option',
1019  [
1020  'disabled' => in_array( $nsId, $params['disable'] ),
1021  'value' => $nsId,
1022  'selected' => $nsId === $params['selected'],
1023  ],
1024  $nsName
1025  );
1026  }
1027 
1028  if ( !array_key_exists( 'id', $selectAttribs ) ) {
1029  $selectAttribs['id'] = 'namespace';
1030  }
1031 
1032  if ( !array_key_exists( 'name', $selectAttribs ) ) {
1033  $selectAttribs['name'] = 'namespace';
1034  }
1035 
1036  $ret = '';
1037  if ( isset( $params['label'] ) ) {
1038  $ret .= self::element(
1039  'label', [
1040  'for' => $selectAttribs['id'] ?? null,
1041  ], $params['label']
1042  ) . "\u{00A0}";
1043  }
1044 
1045  // Wrap options in a <select>
1046  $ret .= self::openElement( 'select', $selectAttribs )
1047  . "\n"
1048  . implode( "\n", $optionsHtml )
1049  . "\n"
1050  . self::closeElement( 'select' );
1051 
1052  return $ret;
1053  }
1054 
1063  public static function htmlHeader( array $attribs = [] ) {
1064  $ret = '';
1065  $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1066  $html5Version = $mainConfig->get( MainConfigNames::Html5Version );
1067  $mimeType = $mainConfig->get( MainConfigNames::MimeType );
1068  $xhtmlNamespaces = $mainConfig->get( MainConfigNames::XhtmlNamespaces );
1069 
1070  $isXHTML = self::isXmlMimeType( $mimeType );
1071 
1072  if ( $isXHTML ) { // XHTML5
1073  // XML MIME-typed markup should have an xml header.
1074  // However a DOCTYPE is not needed.
1075  $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
1076 
1077  // Add the standard xmlns
1078  $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
1079 
1080  // And support custom namespaces
1081  foreach ( $xhtmlNamespaces as $tag => $ns ) {
1082  $attribs["xmlns:$tag"] = $ns;
1083  }
1084  } else { // HTML5
1085  $ret .= "<!DOCTYPE html>\n";
1086  }
1087 
1088  if ( $html5Version ) {
1089  $attribs['version'] = $html5Version;
1090  }
1091 
1092  $ret .= self::openElement( 'html', $attribs );
1093 
1094  return $ret;
1095  }
1096 
1103  public static function isXmlMimeType( $mimetype ) {
1104  # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
1105  # * text/xml
1106  # * application/xml
1107  # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1108  return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1109  }
1110 
1134  public static function srcSet( array $urls ) {
1135  $candidates = [];
1136  foreach ( $urls as $density => $url ) {
1137  // Cast density to float to strip 'x', then back to string to serve
1138  // as array index.
1139  $density = (string)(float)$density;
1140  $candidates[$density] = $url;
1141  }
1142 
1143  // Remove duplicates that are the same as a smaller value
1144  ksort( $candidates, SORT_NUMERIC );
1145  $candidates = array_unique( $candidates );
1146 
1147  // Append density info to the url
1148  foreach ( $candidates as $density => $url ) {
1149  $candidates[$density] = $url . ' ' . $density . 'x';
1150  }
1151 
1152  return implode( ", ", $candidates );
1153  }
1154 
1169  public static function encodeJsVar( $value, $pretty = false ) {
1170  if ( $value instanceof HtmlJsCode ) {
1171  return $value->value;
1172  }
1173  return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
1174  }
1175 
1190  public static function encodeJsCall( $name, $args, $pretty = false ) {
1191  $encodedArgs = self::encodeJsList( $args, $pretty );
1192  if ( $encodedArgs === false ) {
1193  return false;
1194  }
1195  return "$name($encodedArgs);";
1196  }
1197 
1207  public static function encodeJsList( $args, $pretty = false ) {
1208  foreach ( $args as &$arg ) {
1209  $arg = self::encodeJsVar( $arg, $pretty );
1210  if ( $arg === false ) {
1211  return false;
1212  }
1213  }
1214  if ( $pretty ) {
1215  return ' ' . implode( ', ', $args ) . ' ';
1216  } else {
1217  return implode( ',', $args );
1218  }
1219  }
1220 }
1221 
1225 class_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.
Definition: FormatJson.php:28
const UTF8_OK
Skip escaping most characters above U+007F for readability and compactness.
Definition: FormatJson.php:36
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:98
MediaWiki exception.
Definition: MWException.php:33
A wrapper class which causes Html::encodeJsVar() and Html::encodeJsCall() (as well as their Xml::* co...
Definition: HtmlJsCode.php:42
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:989
static warningBox( $html, $className='')
Return a warning box.
Definition: Html.php:815
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:1169
static label( $label, $id, array $attribs=[])
Convenience function for generating a label for inputs.
Definition: Html.php:881
static noticeBox( $html, $className)
Return the HTML for a notice message box.
Definition: Html.php:801
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:1134
static successBox( $html, $className='')
Return a success box.
Definition: Html.php:844
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:1190
static htmlHeader(array $attribs=[])
Constructs the opening html-tag with necessary doctypes depending on global variables.
Definition: Html.php:1063
static errorBox( $html, $heading='', $className='')
Return an error box.
Definition: Html.php:830
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:858
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:1103
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:897
static textarea( $name, $value='', array $attribs=[])
Convenience function to produce a <textarea> element.
Definition: Html.php:913
static namespaceSelectorOptions(array $params=[])
Helper for Html::namespaceSelector().
Definition: Html.php:933
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:1207
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
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.
static isNonceRequired(Config $config)
Should we set nonce attribute.