Debian Codegraph @

includes/Html/Html.php

raw symbols SCIP
1 <?php
2 /**
3 * Collection of methods to generate HTML content
4 *
5 * Copyright © 2009 Aryeh Gregor
6 * https://www.mediawiki.org/
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 */
25
26 namespace MediaWiki\Html;
27
28 use MediaWiki\Json\FormatJson;
29 use MediaWiki\MainConfigNames;
30 use MediaWiki\MediaWikiServices;
31 use MediaWiki\Parser\Sanitizer;
32 use MediaWiki\Request\ContentSecurityPolicy;
33 use UnexpectedValueException;
34
35 /**
36 * This class is a collection of static functions that serve two purposes:
37 *
38 * 1) Implement any algorithms specified by HTML5, or other HTML
39 * specifications, in a convenient and self-contained way.
40 *
41 * 2) Allow HTML elements to be conveniently and safely generated, like the
42 * current Xml class but a) less confused (Xml supports HTML-specific things,
43 * but only sometimes!) and b) not necessarily confined to XML-compatible
44 * output.
45 *
46 * There are two important configuration options this class uses:
47 *
48 * $wgMimeType: If this is set to an xml MIME type then output should be
49 * valid XHTML5.
50 *
51 * This class is meant to be confined to utility functions that are called from
52 * trusted code paths. It does not do enforcement of policy like not allowing
53 * <a> elements.
54 *
55 * @since 1.16
56 */
57 class Html {
58 /** @var bool[] List of void elements from HTML5, section 8.1.2 as of 2016-09-19 */
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
77 /**
78 * Boolean attributes, which may have the value omitted entirely. Manually
79 * collected from the HTML5 spec as of 2011-08-12.
80 * @var bool[]
81 */
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
111 /**
112 * Modifies a set of attributes meant for button elements.
113 *
114 * @param array $attrs HTML attributes in an associative array
115 * @param string[] $modifiers Unused
116 * @return array Modified attributes array
117 * @deprecated since 1.42 No-op
118 */
119 public static function buttonAttributes( array $attrs, array $modifiers = [] ) {
120 wfDeprecated( __METHOD__, '1.42' );
121 return $attrs;
122 }
123
124 /**
125 * Modifies a set of attributes meant for text input elements.
126 *
127 * @param array $attrs An attribute array.
128 * @return array Modified attributes array
129 * @deprecated since 1.42 No-op
130 */
131 public static function getTextInputAttributes( array $attrs ) {
132 wfDeprecated( __METHOD__, '1.42' );
133 return $attrs;
134 }
135
136 /**
137 * Returns an HTML link element in a string.
138 *
139 * @param string $text The text of the element. Will be escaped (not raw HTML)
140 * @param array $attrs Associative array of attributes, e.g., [
141 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
142 * further documentation.
143 * @param string[] $modifiers Unused
144 * @return string Raw HTML
145 */
146 public static function linkButton( $text, array $attrs, array $modifiers = [] ) {
147 return self::element(
148 'a',
149 $attrs,
150 $text
151 );
152 }
153
154 /**
155 * Returns an HTML input element in a string.
156 *
157 * @param string $contents Plain text label for the button value
158 * @param array $attrs Associative array of attributes, e.g., [
159 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
160 * further documentation.
161 * @param string[] $modifiers Unused
162 * @return string Raw HTML
163 */
164 public static function submitButton( $contents, array $attrs = [], array $modifiers = [] ) {
165 $attrs['type'] = 'submit';
166 $attrs['value'] = $contents;
167 return self::element( 'input', $attrs );
168 }
169
170 /**
171 * Returns an HTML element in a string. The major advantage here over
172 * manually typing out the HTML is that it will escape all attribute
173 * values.
174 *
175 * This is quite similar to Xml::tags(), but it implements some useful
176 * HTML-specific logic. For instance, there is no $allowShortTag
177 * parameter: the closing tag is magically omitted if $element has an empty
178 * content model.
179 *
180 * @param string $element The element's name, e.g., 'a'
181 * @param-taint $element tainted
182 * @param array $attribs Associative array of attributes, e.g., [
183 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
184 * further documentation.
185 * @param-taint $attribs escapes_html
186 * @param string $contents The raw HTML contents of the element: *not*
187 * escaped!
188 * @param-taint $contents tainted
189 * @return string Raw HTML
190 * @return-taint escaped
191 */
192 public static function rawElement( $element, $attribs = [], $contents = '' ) {
193 $start = self::openElement( $element, $attribs );
194 if ( isset( self::$voidElements[$element] ) ) {
195 return $start;
196 } else {
197 $contents = Sanitizer::escapeCombiningChar( $contents ?? '' );
198 return $start . $contents . self::closeElement( $element );
199 }
200 }
201
202 /**
203 * Identical to rawElement(), but HTML-escapes $contents (like
204 * Xml::element()).
205 *
206 * @param string $element Name of the element, e.g., 'a'
207 * @param-taint $element tainted
208 * @param array $attribs Associative array of attributes, e.g., [
209 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
210 * further documentation.
211 * @param-taint $attribs escapes_html
212 * @param string $contents
213 * @param-taint $contents escapes_html
214 *
215 * @return string
216 * @return-taint escaped
217 */
218 public static function element( $element, $attribs = [], $contents = '' ) {
219 return self::rawElement(
220 $element,
221 $attribs,
222 strtr( $contents ?? '', [
223 // There's no point in escaping quotes, >, etc. in the contents of
224 // elements.
225 '&' => '&amp;',
226 '<' => '&lt;',
227 ] )
228 );
229 }
230
231 /**
232 * Identical to rawElement(), but has no third parameter and omits the end
233 * tag (and the self-closing '/' in XML mode for empty elements).
234 *
235 * @param string $element Name of the element, e.g., 'a'
236 * @param array $attribs Associative array of attributes, e.g., [
237 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
238 * further documentation.
239 *
240 * @return string
241 */
242 public static function openElement( $element, $attribs = [] ) {
243 $attribs = (array)$attribs;
244 // This is not required in HTML5, but let's do it anyway, for
245 // consistency and better compression.
246 $element = strtolower( $element );
247
248 // Some people were abusing this by passing things like
249 // 'h1 id="foo" to $element, which we don't want.
250 if ( str_contains( $element, ' ' ) ) {
251 wfWarn( __METHOD__ . " given element name with space '$element'" );
252 }
253
254 // Remove invalid input types
255 if ( $element == 'input' ) {
256 $validTypes = [
257 'hidden' => true,
258 'text' => true,
259 'password' => true,
260 'checkbox' => true,
261 'radio' => true,
262 'file' => true,
263 'submit' => true,
264 'image' => true,
265 'reset' => true,
266 'button' => true,
267
268 // HTML input types
269 'datetime' => true,
270 'datetime-local' => true,
271 'date' => true,
272 'month' => true,
273 'time' => true,
274 'week' => true,
275 'number' => true,
276 'range' => true,
277 'email' => true,
278 'url' => true,
279 'search' => true,
280 'tel' => true,
281 'color' => true,
282 ];
283 if ( isset( $attribs['type'] ) && !isset( $validTypes[$attribs['type']] ) ) {
284 unset( $attribs['type'] );
285 }
286 }
287
288 // According to standard the default type for <button> elements is "submit".
289 // Depending on compatibility mode IE might use "button", instead.
290 // We enforce the standard "submit".
291 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
292 $attribs['type'] = 'submit';
293 }
294
295 return "<$element" . self::expandAttributes(
296 self::dropDefaults( $element, $attribs ) ) . '>';
297 }
298
299 /**
300 * Returns "</$element>"
301 *
302 * @since 1.17
303 * @param string $element Name of the element, e.g., 'a'
304 * @return string A closing tag
305 */
306 public static function closeElement( $element ) {
307 $element = strtolower( $element );
308
309 return "</$element>";
310 }
311
312 /**
313 * Given an element name and an associative array of element attributes,
314 * return an array that is functionally identical to the input array, but
315 * possibly smaller. In particular, attributes might be stripped if they
316 * are given their default values.
317 *
318 * This method is not guaranteed to remove all redundant attributes, only
319 * some common ones and some others selected arbitrarily at random. It
320 * only guarantees that the output array should be functionally identical
321 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
322 *
323 * @param string $element Name of the element, e.g., 'a'
324 * @param array $attribs Associative array of attributes, e.g., [
325 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
326 * further documentation.
327 * @return array An array of attributes functionally identical to $attribs
328 */
329 private static function dropDefaults( $element, array $attribs ) {
330 // Whenever altering this array, please provide a covering test case
331 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
332 static $attribDefaults = [
333 'area' => [ 'shape' => 'rect' ],
334 'button' => [
335 'formaction' => 'GET',
336 'formenctype' => 'application/x-www-form-urlencoded',
337 ],
338 'canvas' => [
339 'height' => '150',
340 'width' => '300',
341 ],
342 'form' => [
343 'action' => 'GET',
344 'autocomplete' => 'on',
345 'enctype' => 'application/x-www-form-urlencoded',
346 ],
347 'input' => [
348 'formaction' => 'GET',
349 'type' => 'text',
350 ],
351 'keygen' => [ 'keytype' => 'rsa' ],
352 'link' => [ 'media' => 'all' ],
353 'menu' => [ 'type' => 'list' ],
354 'script' => [ 'type' => 'text/javascript' ],
355 'style' => [
356 'media' => 'all',
357 'type' => 'text/css',
358 ],
359 'textarea' => [ 'wrap' => 'soft' ],
360 ];
361
362 foreach ( $attribs as $attrib => $value ) {
363 if ( $attrib === 'class' ) {
364 if ( $value === '' || $value === [] || $value === [ '' ] ) {
365 unset( $attribs[$attrib] );
366 }
367 } elseif ( isset( $attribDefaults[$element][$attrib] ) ) {
368 if ( is_array( $value ) ) {
369 $value = implode( ' ', $value );
370 } else {
371 $value = strval( $value );
372 }
373 if ( $attribDefaults[$element][$attrib] == $value ) {
374 unset( $attribs[$attrib] );
375 }
376 }
377 }
378
379 // More subtle checks
380 if ( $element === 'link'
381 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
382 ) {
383 unset( $attribs['type'] );
384 }
385 if ( $element === 'input' ) {
386 $type = $attribs['type'] ?? null;
387 $value = $attribs['value'] ?? null;
388 if ( $type === 'checkbox' || $type === 'radio' ) {
389 // The default value for checkboxes and radio buttons is 'on'
390 // not ''. By stripping value="" we break radio boxes that
391 // actually wants empty values.
392 if ( $value === 'on' ) {
393 unset( $attribs['value'] );
394 }
395 } elseif ( $type === 'submit' ) {
396 // The default value for submit appears to be "Submit" but
397 // let's not bother stripping out localized text that matches
398 // that.
399 } else {
400 // The default value for nearly every other field type is ''
401 // The 'range' and 'color' types use different defaults but
402 // stripping a value="" does not hurt them.
403 if ( $value === '' ) {
404 unset( $attribs['value'] );
405 }
406 }
407 }
408 if ( $element === 'select' && isset( $attribs['size'] ) ) {
409 $multiple = ( $attribs['multiple'] ?? false ) !== false ||
410 in_array( 'multiple', $attribs );
411 $default = $multiple ? 4 : 1;
412 if ( (int)$attribs['size'] === $default ) {
413 unset( $attribs['size'] );
414 }
415 }
416
417 return $attribs;
418 }
419
420 /**
421 * Given an associative array of element attributes, generate a string
422 * to stick after the element name in HTML output. Like [ 'href' =>
423 * 'https://www.mediawiki.org/' ] becomes something like
424 * ' href="https://www.mediawiki.org"'. Again, this is like
425 * Xml::expandAttributes(), but it implements some HTML-specific logic.
426 *
427 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
428 * values are allowed as well, which will automagically be normalized
429 * and converted to a space-separated string. In addition to a numerical
430 * array, the attribute value may also be an associative array. See the
431 * example below for how that works.
432 *
433 * @par Numerical array
434 * @code
435 * Html::element( 'em', [
436 * 'class' => [ 'foo', 'bar' ]
437 * ] );
438 * // gives '<em class="foo bar"></em>'
439 * @endcode
440 *
441 * @par Associative array
442 * @code
443 * Html::element( 'em', [
444 * 'class' => [ 'foo', 'bar', 'foo' => false, 'quux' => true ]
445 * ] );
446 * // gives '<em class="bar quux"></em>'
447 * @endcode
448 *
449 * @param array $attribs Associative array of attributes, e.g., [
450 * 'href' => 'https://www.mediawiki.org/' ]. Values will be HTML-escaped.
451 * A value of false or null means to omit the attribute. For boolean attributes,
452 * you can omit the key, e.g., [ 'checked' ] instead of
453 * [ 'checked' => 'checked' ] or such.
454 *
455 * @return string HTML fragment that goes between element name and '>'
456 * (starting with a space if at least one attribute is output)
457 */
458 public static function expandAttributes( array $attribs ) {
459 $ret = '';
460 foreach ( $attribs as $key => $value ) {
461 // Support intuitive [ 'checked' => true/false ] form
462 if ( $value === false || $value === null ) {
463 continue;
464 }
465
466 // For boolean attributes, support [ 'foo' ] instead of
467 // requiring [ 'foo' => 'meaningless' ].
468 if ( is_int( $key ) && isset( self::$boolAttribs[strtolower( $value )] ) ) {
469 $key = $value;
470 }
471
472 // Not technically required in HTML5 but we'd like consistency
473 // and better compression anyway.
474 $key = strtolower( $key );
475
476 // https://www.w3.org/TR/html401/index/attributes.html ("space-separated")
477 // https://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
478 $spaceSeparatedListAttributes = [
479 'class' => true, // html4, html5
480 'accesskey' => true, // as of html5, multiple space-separated values allowed
481 // html4-spec doesn't document rel= as space-separated
482 // but has been used like that and is now documented as such
483 // in the html5-spec.
484 'rel' => true,
485 ];
486
487 // Specific features for attributes that allow a list of space-separated values
488 if ( isset( $spaceSeparatedListAttributes[$key] ) ) {
489 // Apply some normalization and remove duplicates
490
491 // Convert into correct array. Array can contain space-separated
492 // values. Implode/explode to get those into the main array as well.
493 if ( is_array( $value ) ) {
494 // If input wasn't an array, we can skip this step
495 $arrayValue = [];
496 foreach ( $value as $k => $v ) {
497 if ( is_string( $v ) ) {
498 // String values should be normal `[ 'foo' ]`
499 // Just append them
500 if ( !isset( $value[$v] ) ) {
501 // As a special case don't set 'foo' if a
502 // separate 'foo' => true/false exists in the array
503 // keys should be authoritative
504 foreach ( explode( ' ', $v ) as $part ) {
505 // Normalize spacing by fixing up cases where people used
506 // more than 1 space and/or a trailing/leading space
507 if ( $part !== '' && $part !== ' ' ) {
508 $arrayValue[] = $part;
509 }
510 }
511 }
512 } elseif ( $v ) {
513 // If the value is truthy but not a string this is likely
514 // an [ 'foo' => true ], falsy values don't add strings
515 $arrayValue[] = $k;
516 }
517 }
518 } else {
519 $arrayValue = explode( ' ', $value );
520 // Normalize spacing by fixing up cases where people used
521 // more than 1 space and/or a trailing/leading space
522 $arrayValue = array_diff( $arrayValue, [ '', ' ' ] );
523 }
524
525 // Remove duplicates and create the string
526 $value = implode( ' ', array_unique( $arrayValue ) );
527
528 // Optimization: Skip below boolAttribs check and jump straight
529 // to its `else` block. The current $spaceSeparatedListAttributes
530 // block is mutually exclusive with $boolAttribs.
531 // phpcs:ignore Generic.PHP.DiscourageGoto
532 goto not_bool; // NOSONAR
533 } elseif ( is_array( $value ) ) {
534 throw new UnexpectedValueException( "HTML attribute $key can not contain a list of values" );
535 }
536
537 if ( isset( self::$boolAttribs[$key] ) ) {
538 $ret .= " $key=\"\"";
539 } else {
540 // phpcs:ignore Generic.PHP.DiscourageGoto
541 not_bool:
542 // Inlined from Sanitizer::encodeAttribute() for improved performance
543 $encValue = htmlspecialchars( $value, ENT_QUOTES );
544 // Whitespace is normalized during attribute decoding,
545 // so if we've been passed non-spaces we must encode them
546 // ahead of time or they won't be preserved.
547 $encValue = strtr( $encValue, [
548 "\n" => '&#10;',
549 "\r" => '&#13;',
550 "\t" => '&#9;',
551 ] );
552 $ret .= " $key=\"$encValue\"";
553 }
554 }
555 return $ret;
556 }
557
558 /**
559 * Output an HTML script tag with the given contents.
560 *
561 * It is unsupported for the contents to contain the sequence `<script` or `</script`
562 * (case-insensitive). This ensures the script can be terminated easily and consistently.
563 * It is the responsibility of the caller to avoid such character sequence by escaping
564 * or avoiding it. If found at run-time, the contents are replaced with a comment, and
565 * a warning is logged server-side.
566 *
567 * @param string $contents JavaScript
568 * @param string|null $nonce Unused
569 * @return string Raw HTML
570 */
571 public static function inlineScript( $contents, $nonce = null ) {
572 if ( preg_match( '/<\/?script/i', $contents ) ) {
573 wfLogWarning( __METHOD__ . ': Illegal character sequence found in inline script.' );
574 $contents = '/* ERROR: Invalid script */';
575 }
576
577 return self::rawElement( 'script', [], $contents );
578 }
579
580 /**
581 * Output a "<script>" tag linking to the given URL, e.g.,
582 * "<script src=foo.js></script>".
583 *
584 * @param string $url
585 * @param string|null $nonce Nonce for CSP header, from OutputPage->getCSP()->getNonce()
586 * @return string Raw HTML
587 */
588 public static function linkedScript( $url, $nonce = null ) {
589 $attrs = [ 'src' => $url ];
590 if ( $nonce !== null ) {
591 $attrs['nonce'] = $nonce;
592 } elseif ( ContentSecurityPolicy::isNonceRequired( MediaWikiServices::getInstance()->getMainConfig() ) ) {
593 wfWarn( "no nonce set on script. CSP will break it" );
594 }
595
596 return self::element( 'script', $attrs );
597 }
598
599 /**
600 * Output a "<style>" tag with the given contents for the given media type
601 * (if any). TODO: do some useful escaping as well, like if $contents
602 * contains literal "</style>" (admittedly unlikely).
603 *
604 * @param string $contents CSS
605 * @param string $media A media type string, like 'screen'
606 * @param array $attribs (since 1.31) Associative array of attributes, e.g., [
607 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
608 * further documentation.
609 * @return string Raw HTML
610 */
611 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
612 // Don't escape '>' since that is used
613 // as direct child selector.
614 // Remember, in css, there is no "x" for hexadecimal escapes, and
615 // the space immediately after an escape sequence is swallowed.
616 $contents = strtr( $contents, [
617 '<' => '\3C ',
618 // CDATA end tag for good measure, but the main security
619 // is from escaping the '<'.
620 ']]>' => '\5D\5D\3E '
621 ] );
622
623 if ( preg_match( '/[<&]/', $contents ) ) {
624 $contents = "/*<![CDATA[*/$contents/*]]>*/";
625 }
626
627 return self::rawElement( 'style', [
628 'media' => $media,
629 ] + $attribs, $contents );
630 }
631
632 /**
633 * Output a "<link rel=stylesheet>" linking to the given URL for the given
634 * media type (if any).
635 *
636 * @param string $url
637 * @param string $media A media type string, like 'screen'
638 * @return string Raw HTML
639 */
640 public static function linkedStyle( $url, $media = 'all' ) {
641 return self::element( 'link', [
642 'rel' => 'stylesheet',
643 'href' => $url,
644 'media' => $media,
645 ] );
646 }
647
648 /**
649 * Convenience function to produce an `<input>` element. This supports the
650 * new HTML5 input types and attributes.
651 *
652 * @param string $name Name attribute
653 * @param string $value Value attribute
654 * @param string $type Type attribute
655 * @param array $attribs Associative array of miscellaneous extra
656 * attributes, passed to Html::element()
657 * @return string Raw HTML
658 */
659 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
660 $attribs['type'] = $type;
661 $attribs['value'] = $value;
662 $attribs['name'] = $name;
663 return self::element( 'input', $attribs );
664 }
665
666 /**
667 * Convenience function to produce a checkbox (input element with type=checkbox)
668 *
669 * @param string $name Name attribute
670 * @param bool $checked Whether the checkbox is checked or not
671 * @param array $attribs Array of additional attributes
672 * @return string Raw HTML
673 */
674 public static function check( $name, $checked = false, array $attribs = [] ) {
675 if ( isset( $attribs['value'] ) ) {
676 $value = $attribs['value'];
677 unset( $attribs['value'] );
678 } else {
679 $value = 1;
680 }
681
682 if ( $checked ) {
683 $attribs[] = 'checked';
684 }
685
686 return self::input( $name, $value, 'checkbox', $attribs );
687 }
688
689 /**
690 * Return the HTML for a message box.
691 * @since 1.31
692 * @param string $html of contents of box
693 * @param-taint $html tainted
694 * @param string|array $className corresponding to box
695 * @param string $heading (optional)
696 * @param string $iconClassName (optional) corresponding to box icon
697 * @return string of HTML representing a box.
698 */
699 private static function messageBox( $html, $className, $heading = '', $iconClassName = '' ) {
700 if ( $heading !== '' ) {
701 $html = self::element( 'h2', [], $heading ) . $html;
702 }
703 $coreClasses = [
704 'cdx-message',
705 'cdx-message--block'
706 ];
707 if ( is_array( $className ) ) {
708 $className = array_merge(
709 $coreClasses,
710 $className
711 );
712 } else {
713 $className .= ' ' . implode( ' ', $coreClasses );
714 }
715 return self::rawElement( 'div', [ 'class' => $className ],
716 self::element( 'span', [ 'class' => [
717 'cdx-message__icon',
718 $iconClassName
719 ] ] ) .
720 self::rawElement( 'div', [
721 'class' => 'cdx-message__content'
722 ], $html )
723 );
724 }
725
726 /**
727 * Return the HTML for a notice message box.
728 * @since 1.38
729 * @param string $html of contents of notice
730 * @param-taint $html tainted
731 * @param string|array $className corresponding to notice
732 * @param string $heading (optional)
733 * @param string|array $iconClassName (optional) corresponding to notice icon
734 * @return string of HTML representing the notice
735 */
736 public static function noticeBox( $html, $className, $heading = '', $iconClassName = '' ) {
737 return self::messageBox( $html, [
738 'cdx-message--notice',
739 $className
740 ], $heading, $iconClassName );
741 }
742
743 /**
744 * Return a warning box.
745 * @since 1.31
746 * @since 1.34 $className optional parameter added
747 * @param string $html of contents of box
748 * @param-taint $html tainted
749 * @param string $className (optional) corresponding to box
750 * @return string of HTML representing a warning box.
751 */
752 public static function warningBox( $html, $className = '' ) {
753 return self::messageBox( $html, [
754 'cdx-message--warning', $className ] );
755 }
756
757 /**
758 * Return an error box.
759 * @since 1.31
760 * @since 1.34 $className optional parameter added
761 * @param string $html of contents of error box
762 * @param-taint $html tainted
763 * @param string $heading (optional)
764 * @param string $className (optional) corresponding to box
765 * @return string of HTML representing an error box.
766 */
767 public static function errorBox( $html, $heading = '', $className = '' ) {
768 return self::messageBox( $html, [
769 'cdx-message--error', $className ], $heading );
770 }
771
772 /**
773 * Return a success box.
774 * @since 1.31
775 * @since 1.34 $className optional parameter added
776 * @param string $html of contents of box
777 * @param-taint $html tainted
778 * @param string $className (optional) corresponding to box
779 * @return string of HTML representing a success box.
780 */
781 public static function successBox( $html, $className = '' ) {
782 return self::messageBox( $html, [
783 'cdx-message--success', $className ] );
784 }
785
786 /**
787 * Convenience function to produce a radio button (input element with type=radio)
788 *
789 * @param string $name Name attribute
790 * @param bool $checked Whether the radio button is checked or not
791 * @param array $attribs Array of additional attributes
792 * @return string Raw HTML
793 */
794 public static function radio( $name, $checked = false, array $attribs = [] ) {
795 if ( isset( $attribs['value'] ) ) {
796 $value = $attribs['value'];
797 unset( $attribs['value'] );
798 } else {
799 $value = 1;
800 }
801
802 if ( $checked ) {
803 $attribs[] = 'checked';
804 }
805
806 return self::input( $name, $value, 'radio', $attribs );
807 }
808
809 /**
810 * Convenience function for generating a label for inputs.
811 *
812 * @param string $label Contents of the label
813 * @param string $id ID of the element being labeled
814 * @param array $attribs Additional attributes
815 * @return string Raw HTML
816 */
817 public static function label( $label, $id, array $attribs = [] ) {
818 $attribs += [
819 'for' => $id,
820 ];
821 return self::element( 'label', $attribs, $label );
822 }
823
824 /**
825 * Convenience function to produce an input element with type=hidden
826 *
827 * @param string $name Name attribute
828 * @param mixed $value Value attribute
829 * @param array $attribs Associative array of miscellaneous extra
830 * attributes, passed to Html::element()
831 * @return string Raw HTML
832 */
833 public static function hidden( $name, $value, array $attribs = [] ) {
834 return self::input( $name, $value, 'hidden', $attribs );
835 }
836
837 /**
838 * Convenience function to produce a <textarea> element.
839 *
840 * This supports leaving out the cols= and rows= which Xml requires and are
841 * required by HTML4/XHTML but not required by HTML5.
842 *
843 * @param string $name Name attribute
844 * @param string $value Value attribute
845 * @param array $attribs Associative array of miscellaneous extra
846 * attributes, passed to Html::element()
847 * @return string Raw HTML
848 */
849 public static function textarea( $name, $value = '', array $attribs = [] ) {
850 $attribs['name'] = $name;
851
852 if ( substr( $value ?? '', 0, 1 ) == "\n" ) {
853 // Workaround for T14130: browsers eat the initial newline
854 // assuming that it's just for show, but they do keep the later
855 // newlines, which we may want to preserve during editing.
856 // Prepending a single newline
857 $spacedValue = "\n" . $value;
858 } else {
859 $spacedValue = $value;
860 }
861 return self::element( 'textarea', $attribs, $spacedValue );
862 }
863
864 /**
865 * Helper for Html::namespaceSelector().
866 * @param array $params See Html::namespaceSelector()
867 * @return array
868 */
869 public static function namespaceSelectorOptions( array $params = [] ) {
870 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
871 $params['exclude'] = [];
872 }
873
874 if ( $params['in-user-lang'] ?? false ) {
875 global $wgLang;
876 $lang = $wgLang;
877 } else {
878 $lang = MediaWikiServices::getInstance()->getContentLanguage();
879 }
880
881 $optionsOut = [];
882 if ( isset( $params['all'] ) ) {
883 // add an option that would let the user select all namespaces.
884 // Value is provided by user, the name shown is localized for the user.
885 $optionsOut[$params['all']] = wfMessage( 'namespacesall' )->text();
886 }
887 // Add all namespaces as options
888 $options = $lang->getFormattedNamespaces();
889 // Filter out namespaces below 0 and massage labels
890 foreach ( $options as $nsId => $nsName ) {
891 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
892 continue;
893 }
894 if ( $nsId === NS_MAIN ) {
895 // For other namespaces use the namespace prefix as label, but for
896 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
897 $nsName = wfMessage( 'blanknamespace' )->text();
898 } elseif ( is_int( $nsId ) ) {
899 $converter = MediaWikiServices::getInstance()->getLanguageConverterFactory()
900 ->getLanguageConverter( $lang );
901 $nsName = $converter->convertNamespace( $nsId );
902 }
903 $optionsOut[$nsId] = $nsName;
904 }
905
906 return $optionsOut;
907 }
908
909 /**
910 * Build a drop-down box for selecting a namespace
911 *
912 * @param array $params Params to set.
913 * - selected: [optional] Id of namespace which should be pre-selected
914 * - all: [optional] Value of item for "all namespaces". If null or unset,
915 * no "<option>" is generated to select all namespaces.
916 * - label: text for label to add before the field.
917 * - exclude: [optional] Array of namespace ids to exclude.
918 * - disable: [optional] Array of namespace ids for which the option should
919 * be disabled in the selector.
920 * @param array $selectAttribs HTML attributes for the generated select element.
921 * - id: [optional], default: 'namespace'.
922 * - name: [optional], default: 'namespace'.
923 * @return string HTML code to select a namespace.
924 */
925 public static function namespaceSelector(
926 array $params = [],
927 array $selectAttribs = []
928 ) {
929 ksort( $selectAttribs );
930
931 // Is a namespace selected?
932 if ( isset( $params['selected'] ) ) {
933 // If string only contains digits, convert to clean int. Selected could also
934 // be "all" or "" etc. which needs to be left untouched.
935 if ( !is_int( $params['selected'] ) && ctype_digit( (string)$params['selected'] ) ) {
936 $params['selected'] = (int)$params['selected'];
937 }
938 // else: leaves it untouched for later processing
939 } else {
940 $params['selected'] = '';
941 }
942
943 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
944 $params['disable'] = [];
945 }
946
947 // Associative array between option-values and option-labels
948 $options = self::namespaceSelectorOptions( $params );
949
950 // Convert $options to HTML
951 $optionsHtml = [];
952 foreach ( $options as $nsId => $nsName ) {
953 $optionsHtml[] = self::element(
954 'option',
955 [
956 'disabled' => in_array( $nsId, $params['disable'] ),
957 'value' => $nsId,
958 'selected' => $nsId === $params['selected'],
959 ],
960 $nsName
961 );
962 }
963
964 $selectAttribs['id'] ??= 'namespace';
965 $selectAttribs['name'] ??= 'namespace';
966
967 $ret = '';
968 if ( isset( $params['label'] ) ) {
969 $ret .= self::element(
970 'label', [
971 'for' => $selectAttribs['id'],
972 ], $params['label']
973 ) . "\u{00A0}";
974 }
975
976 // Wrap options in a <select>
977 $ret .= self::openElement( 'select', $selectAttribs )
978 . "\n"
979 . implode( "\n", $optionsHtml )
980 . "\n"
981 . self::closeElement( 'select' );
982
983 return $ret;
984 }
985
986 /**
987 * Constructs the opening html-tag with necessary doctypes depending on
988 * global variables.
989 *
990 * @param array $attribs Associative array of miscellaneous extra
991 * attributes, passed to Html::element() of html tag.
992 * @return string Raw HTML
993 */
994 public static function htmlHeader( array $attribs = [] ) {
995 $ret = '';
996 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
997 $html5Version = $mainConfig->get( MainConfigNames::Html5Version );
998 $mimeType = $mainConfig->get( MainConfigNames::MimeType );
999 $xhtmlNamespaces = $mainConfig->get( MainConfigNames::XhtmlNamespaces );
1000
1001 $isXHTML = self::isXmlMimeType( $mimeType );
1002
1003 if ( $isXHTML ) { // XHTML5
1004 // XML MIME-typed markup should have an xml header.
1005 // However a DOCTYPE is not needed.
1006 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
1007
1008 // Add the standard xmlns
1009 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
1010
1011 // And support custom namespaces
1012 foreach ( $xhtmlNamespaces as $tag => $ns ) {
1013 $attribs["xmlns:$tag"] = $ns;
1014 }
1015 } else { // HTML5
1016 $ret .= "<!DOCTYPE html>\n";
1017 }
1018
1019 if ( $html5Version ) {
1020 $attribs['version'] = $html5Version;
1021 }
1022
1023 $ret .= self::openElement( 'html', $attribs );
1024
1025 return $ret;
1026 }
1027
1028 /**
1029 * Determines if the given MIME type is xml.
1030 *
1031 * @param string $mimetype
1032 * @return bool
1033 */
1034 public static function isXmlMimeType( $mimetype ) {
1035 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
1036 # * text/xml
1037 # * application/xml
1038 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1039 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1040 }
1041
1042 /**
1043 * Generate a srcset attribute value.
1044 *
1045 * Generates a srcset attribute value from an array mapping pixel densities
1046 * to URLs. A trailing 'x' in pixel density values is optional.
1047 *
1048 * @note srcset width and height values are not supported.
1049 *
1050 * @see https://html.spec.whatwg.org/#attr-img-srcset
1051 *
1052 * @par Example:
1053 * @code
1054 * Html::srcSet( [
1055 * '1x' => 'standard.jpeg',
1056 * '1.5x' => 'large.jpeg',
1057 * '3x' => 'extra-large.jpeg',
1058 * ] );
1059 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1060 * @endcode
1061 *
1062 * @param string[] $urls
1063 * @return string
1064 */
1065 public static function srcSet( array $urls ) {
1066 $candidates = [];
1067 foreach ( $urls as $density => $url ) {
1068 // Cast density to float to strip 'x', then back to string to serve
1069 // as array index.
1070 $density = (string)(float)$density;
1071 $candidates[$density] = $url;
1072 }
1073
1074 // Remove duplicates that are the same as a smaller value
1075 ksort( $candidates, SORT_NUMERIC );
1076 $candidates = array_unique( $candidates );
1077
1078 // Append density info to the url
1079 foreach ( $candidates as $density => $url ) {
1080 $candidates[$density] = $url . ' ' . $density . 'x';
1081 }
1082
1083 return implode( ", ", $candidates );
1084 }
1085
1086 /**
1087 * Encode a variable of arbitrary type to JavaScript.
1088 * If the value is an HtmlJsCode object, pass through the object's value verbatim.
1089 *
1090 * @note Only use this function for generating JavaScript code. If generating output
1091 * for a proper JSON parser, just call FormatJson::encode() directly.
1092 *
1093 * @since 1.41 (previously on {@link Xml})
1094 * @param mixed $value The value being encoded. Can be any type except a resource.
1095 * @param-taint $value escapes_html
1096 * @param bool $pretty If true, add non-significant whitespace to improve readability.
1097 * @return string|false String if successful; false upon failure
1098 * @return-taint none
1099 */
1100 public static function encodeJsVar( $value, $pretty = false ) {
1101 if ( $value instanceof HtmlJsCode ) {
1102 return $value->value;
1103 }
1104 return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
1105 }
1106
1107 /**
1108 * Create a call to a JavaScript function. The supplied arguments will be
1109 * encoded using Html::encodeJsVar().
1110 *
1111 * @since 1.41 (previously on {@link Xml} since 1.17)
1112 * @param string $name The name of the function to call, or a JavaScript expression
1113 * which evaluates to a function object which is called.
1114 * @param-taint $name tainted
1115 * @param array $args The arguments to pass to the function.
1116 * @param-taint $args escapes_html
1117 * @param bool $pretty If true, add non-significant whitespace to improve readability.
1118 * @return string|false String if successful; false upon failure
1119 * @return-taint none
1120 */
1121 public static function encodeJsCall( $name, $args, $pretty = false ) {
1122 $encodedArgs = self::encodeJsList( $args, $pretty );
1123 if ( $encodedArgs === false ) {
1124 return false;
1125 }
1126 return "$name($encodedArgs);";
1127 }
1128
1129 /**
1130 * Encode a JavaScript comma-separated list. The supplied items will be encoded using
1131 * Html::encodeJsVar().
1132 *
1133 * @since 1.41.
1134 * @param array $args The elements of the list.
1135 * @param bool $pretty If true, add non-significant whitespace to improve readability.
1136 * @return false|string String if successful; false upon failure
1137 */
1138 public static function encodeJsList( $args, $pretty = false ) {
1139 foreach ( $args as &$arg ) {
1140 $arg = self::encodeJsVar( $arg, $pretty );
1141 if ( $arg === false ) {
1142 return false;
1143 }
1144 }
1145 if ( $pretty ) {
1146 return ' ' . implode( ', ', $args ) . ' ';
1147 } else {
1148 return implode( ',', $args );
1149 }
1150 }
1151
1152 /**
1153 * Build options for a drop-down box from a textual list.
1154 *
1155 * The result of this function can be passed to XmlSelect::addOptions()
1156 * (to render a plain `<select>` dropdown box) or to Html::listDropdownOptionsOoui()
1157 * and then OOUI\DropdownInputWidget() (to render a pretty one).
1158 *
1159 * @param string $list Correctly formatted text (newline delimited) to be
1160 * used to generate the options.
1161 * @param array $params Extra parameters:
1162 * - string $params['other'] If set, add an option with this as text and a value of 'other'
1163 * @return array Array keys are textual labels, values are internal values
1164 */
1165 public static function listDropdownOptions( $list, $params = [] ) {
1166 $options = [];
1167
1168 if ( isset( $params['other'] ) ) {
1169 $options[ $params['other'] ] = 'other';
1170 }
1171
1172 $optgroup = false;
1173 foreach ( explode( "\n", $list ) as $option ) {
1174 $value = trim( $option );
1175 if ( $value == '' ) {
1176 continue;
1177 }
1178 if ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
1179 # A new group is starting...
1180 $value = trim( substr( $value, 1 ) );
1181 if ( $value !== '' &&
1182 // Do not use the value for 'other' as option group - T251351
1183 ( !isset( $params['other'] ) || $value !== $params['other'] )
1184 ) {
1185 $optgroup = $value;
1186 } else {
1187 $optgroup = false;
1188 }
1189 } elseif ( substr( $value, 0, 2 ) == '**' ) {
1190 # groupmember
1191 $opt = trim( substr( $value, 2 ) );
1192 if ( $optgroup === false ) {
1193 $options[$opt] = $opt;
1194 } else {
1195 $options[$optgroup][$opt] = $opt;
1196 }
1197 } else {
1198 # groupless reason list
1199 $optgroup = false;
1200 $options[$option] = $option;
1201 }
1202 }
1203
1204 return $options;
1205 }
1206
1207 /**
1208 * Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
1209 *
1210 * TODO Find a better home for this function.
1211 *
1212 * @param array $options Options, as returned e.g. by Html::listDropdownOptions()
1213 * @return array
1214 */
1215 public static function listDropdownOptionsOoui( $options ) {
1216 $optionsOoui = [];
1217
1218 foreach ( $options as $text => $value ) {
1219 if ( is_array( $value ) ) {
1220 $optionsOoui[] = [ 'optgroup' => (string)$text ];
1221 foreach ( $value as $text2 => $value2 ) {
1222 $optionsOoui[] = [ 'data' => (string)$value2, 'label' => (string)$text2 ];
1223 }
1224 } else {
1225 $optionsOoui[] = [ 'data' => (string)$value, 'label' => (string)$text ];
1226 }
1227 }
1228
1229 return $optionsOoui;
1230 }
1231
1232 /**
1233 * Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
1234 *
1235 * TODO Find a better home for this function.
1236 *
1237 * @param array $options Options, as returned e.g. by Html::listDropdownOptions()
1238 * @return array
1239 */
1240 public static function listDropdownOptionsCodex( $options ) {
1241 $optionsCodex = [];
1242
1243 foreach ( $options as $text => $value ) {
1244 if ( is_array( $value ) ) {
1245 // No support for optgroups in Codex yet (T367241)
1246 $optionsCodex[] = [ 'label' => (string)$text, 'value' => '', 'disabled' => true ];
1247 foreach ( $value as $text2 => $value2 ) {
1248 $optionsCodex[] = [ 'label' => (string)$text2, 'value' => (string)$value2 ];
1249 }
1250 } else {
1251 $optionsCodex[] = [ 'label' => (string)$text, 'value' => (string)$value ];
1252 }
1253 }
1254 return $optionsCodex;
1255 }
1256 }
1257
1258 /** @deprecated class alias since 1.40 */
1259 class_alias( Html::class, 'Html' );