Merge "RevisionStoreDbTestBase, remove redundant needsDB override"
[lhc/web/wiklou.git] / includes / Html.php
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 use MediaWiki\MediaWikiServices;
26
27 /**
28 * This class is a collection of static functions that serve two purposes:
29 *
30 * 1) Implement any algorithms specified by HTML5, or other HTML
31 * specifications, in a convenient and self-contained way.
32 *
33 * 2) Allow HTML elements to be conveniently and safely generated, like the
34 * current Xml class but a) less confused (Xml supports HTML-specific things,
35 * but only sometimes!) and b) not necessarily confined to XML-compatible
36 * output.
37 *
38 * There are two important configuration options this class uses:
39 *
40 * $wgMimeType: If this is set to an xml MIME type then output should be
41 * valid XHTML5.
42 *
43 * This class is meant to be confined to utility functions that are called from
44 * trusted code paths. It does not do enforcement of policy like not allowing
45 * <a> elements.
46 *
47 * @since 1.16
48 */
49 class Html {
50 // List of void elements from HTML5, section 8.1.2 as of 2016-09-19
51 private static $voidElements = [
52 'area',
53 'base',
54 'br',
55 'col',
56 'embed',
57 'hr',
58 'img',
59 'input',
60 'keygen',
61 'link',
62 'meta',
63 'param',
64 'source',
65 'track',
66 'wbr',
67 ];
68
69 // Boolean attributes, which may have the value omitted entirely. Manually
70 // collected from the HTML5 spec as of 2011-08-12.
71 private static $boolAttribs = [
72 'async',
73 'autofocus',
74 'autoplay',
75 'checked',
76 'controls',
77 'default',
78 'defer',
79 'disabled',
80 'formnovalidate',
81 'hidden',
82 'ismap',
83 'itemscope',
84 'loop',
85 'multiple',
86 'muted',
87 'novalidate',
88 'open',
89 'pubdate',
90 'readonly',
91 'required',
92 'reversed',
93 'scoped',
94 'seamless',
95 'selected',
96 'truespeed',
97 'typemustmatch',
98 // HTML5 Microdata
99 'itemscope',
100 ];
101
102 /**
103 * Modifies a set of attributes meant for button elements
104 * and apply a set of default attributes when $wgUseMediaWikiUIEverywhere enabled.
105 * @param array $attrs HTML attributes in an associative array
106 * @param string[] $modifiers classes to add to the button
107 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
108 * @return array $attrs A modified attribute array
109 */
110 public static function buttonAttributes( array $attrs, array $modifiers = [] ) {
111 global $wgUseMediaWikiUIEverywhere;
112 if ( $wgUseMediaWikiUIEverywhere ) {
113 if ( isset( $attrs['class'] ) ) {
114 if ( is_array( $attrs['class'] ) ) {
115 $attrs['class'][] = 'mw-ui-button';
116 $attrs['class'] = array_merge( $attrs['class'], $modifiers );
117 // ensure compatibility with Xml
118 $attrs['class'] = implode( ' ', $attrs['class'] );
119 } else {
120 $attrs['class'] .= ' mw-ui-button ' . implode( ' ', $modifiers );
121 }
122 } else {
123 // ensure compatibility with Xml
124 $attrs['class'] = 'mw-ui-button ' . implode( ' ', $modifiers );
125 }
126 }
127 return $attrs;
128 }
129
130 /**
131 * Modifies a set of attributes meant for text input elements
132 * and apply a set of default attributes.
133 * Removes size attribute when $wgUseMediaWikiUIEverywhere enabled.
134 * @param array $attrs An attribute array.
135 * @return array $attrs A modified attribute array
136 */
137 public static function getTextInputAttributes( array $attrs ) {
138 global $wgUseMediaWikiUIEverywhere;
139 if ( $wgUseMediaWikiUIEverywhere ) {
140 if ( isset( $attrs['class'] ) ) {
141 if ( is_array( $attrs['class'] ) ) {
142 $attrs['class'][] = 'mw-ui-input';
143 } else {
144 $attrs['class'] .= ' mw-ui-input';
145 }
146 } else {
147 $attrs['class'] = 'mw-ui-input';
148 }
149 }
150 return $attrs;
151 }
152
153 /**
154 * Returns an HTML link element in a string styled as a button
155 * (when $wgUseMediaWikiUIEverywhere is enabled).
156 *
157 * @param string $contents The raw HTML contents of the element: *not*
158 * escaped!
159 * @param array $attrs Associative array of attributes, e.g., [
160 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
161 * further documentation.
162 * @param string[] $modifiers classes to add to the button
163 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
164 * @return string Raw HTML
165 */
166 public static function linkButton( $contents, array $attrs, array $modifiers = [] ) {
167 return self::element( 'a',
168 self::buttonAttributes( $attrs, $modifiers ),
169 $contents
170 );
171 }
172
173 /**
174 * Returns an HTML link element in a string styled as a button
175 * (when $wgUseMediaWikiUIEverywhere is enabled).
176 *
177 * @param string $contents The raw HTML contents of the element: *not*
178 * escaped!
179 * @param array $attrs Associative array of attributes, e.g., [
180 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
181 * further documentation.
182 * @param string[] $modifiers classes to add to the button
183 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
184 * @return string Raw HTML
185 */
186 public static function submitButton( $contents, array $attrs, array $modifiers = [] ) {
187 $attrs['type'] = 'submit';
188 $attrs['value'] = $contents;
189 return self::element( 'input', self::buttonAttributes( $attrs, $modifiers ) );
190 }
191
192 /**
193 * Returns an HTML element in a string. The major advantage here over
194 * manually typing out the HTML is that it will escape all attribute
195 * values.
196 *
197 * This is quite similar to Xml::tags(), but it implements some useful
198 * HTML-specific logic. For instance, there is no $allowShortTag
199 * parameter: the closing tag is magically omitted if $element has an empty
200 * content model.
201 *
202 * @param string $element The element's name, e.g., 'a'
203 * @param array $attribs Associative array of attributes, e.g., [
204 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
205 * further documentation.
206 * @param string $contents The raw HTML contents of the element: *not*
207 * escaped!
208 * @return string Raw HTML
209 */
210 public static function rawElement( $element, $attribs = [], $contents = '' ) {
211 $start = self::openElement( $element, $attribs );
212 if ( in_array( $element, self::$voidElements ) ) {
213 // Silly XML.
214 return substr( $start, 0, -1 ) . '/>';
215 } else {
216 return "$start$contents" . self::closeElement( $element );
217 }
218 }
219
220 /**
221 * Identical to rawElement(), but HTML-escapes $contents (like
222 * Xml::element()).
223 *
224 * @param string $element Name of the element, e.g., 'a'
225 * @param array $attribs Associative array of attributes, e.g., [
226 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
227 * further documentation.
228 * @param string $contents
229 *
230 * @return string
231 */
232 public static function element( $element, $attribs = [], $contents = '' ) {
233 return self::rawElement( $element, $attribs, strtr( $contents, [
234 // There's no point in escaping quotes, >, etc. in the contents of
235 // elements.
236 '&' => '&amp;',
237 '<' => '&lt;'
238 ] ) );
239 }
240
241 /**
242 * Identical to rawElement(), but has no third parameter and omits the end
243 * tag (and the self-closing '/' in XML mode for empty elements).
244 *
245 * @param string $element Name of the element, e.g., 'a'
246 * @param array $attribs Associative array of attributes, e.g., [
247 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
248 * further documentation.
249 *
250 * @return string
251 */
252 public static function openElement( $element, $attribs = [] ) {
253 $attribs = (array)$attribs;
254 // This is not required in HTML5, but let's do it anyway, for
255 // consistency and better compression.
256 $element = strtolower( $element );
257
258 // Remove invalid input types
259 if ( $element == 'input' ) {
260 $validTypes = [
261 'hidden',
262 'text',
263 'password',
264 'checkbox',
265 'radio',
266 'file',
267 'submit',
268 'image',
269 'reset',
270 'button',
271
272 // HTML input types
273 'datetime',
274 'datetime-local',
275 'date',
276 'month',
277 'time',
278 'week',
279 'number',
280 'range',
281 'email',
282 'url',
283 'search',
284 'tel',
285 'color',
286 ];
287 if ( isset( $attribs['type'] ) && !in_array( $attribs['type'], $validTypes ) ) {
288 unset( $attribs['type'] );
289 }
290 }
291
292 // According to standard the default type for <button> elements is "submit".
293 // Depending on compatibility mode IE might use "button", instead.
294 // We enforce the standard "submit".
295 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
296 $attribs['type'] = 'submit';
297 }
298
299 return "<$element" . self::expandAttributes(
300 self::dropDefaults( $element, $attribs ) ) . '>';
301 }
302
303 /**
304 * Returns "</$element>"
305 *
306 * @since 1.17
307 * @param string $element Name of the element, e.g., 'a'
308 * @return string A closing tag
309 */
310 public static function closeElement( $element ) {
311 $element = strtolower( $element );
312
313 return "</$element>";
314 }
315
316 /**
317 * Given an element name and an associative array of element attributes,
318 * return an array that is functionally identical to the input array, but
319 * possibly smaller. In particular, attributes might be stripped if they
320 * are given their default values.
321 *
322 * This method is not guaranteed to remove all redundant attributes, only
323 * some common ones and some others selected arbitrarily at random. It
324 * only guarantees that the output array should be functionally identical
325 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
326 *
327 * @param string $element Name of the element, e.g., 'a'
328 * @param array $attribs Associative array of attributes, e.g., [
329 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
330 * further documentation.
331 * @return array An array of attributes functionally identical to $attribs
332 */
333 private static function dropDefaults( $element, array $attribs ) {
334 // Whenever altering this array, please provide a covering test case
335 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
336 static $attribDefaults = [
337 'area' => [ 'shape' => 'rect' ],
338 'button' => [
339 'formaction' => 'GET',
340 'formenctype' => 'application/x-www-form-urlencoded',
341 ],
342 'canvas' => [
343 'height' => '150',
344 'width' => '300',
345 ],
346 'form' => [
347 'action' => 'GET',
348 'autocomplete' => 'on',
349 'enctype' => 'application/x-www-form-urlencoded',
350 ],
351 'input' => [
352 'formaction' => 'GET',
353 'type' => 'text',
354 ],
355 'keygen' => [ 'keytype' => 'rsa' ],
356 'link' => [ 'media' => 'all' ],
357 'menu' => [ 'type' => 'list' ],
358 'script' => [ 'type' => 'text/javascript' ],
359 'style' => [
360 'media' => 'all',
361 'type' => 'text/css',
362 ],
363 'textarea' => [ 'wrap' => 'soft' ],
364 ];
365
366 $element = strtolower( $element );
367
368 foreach ( $attribs as $attrib => $value ) {
369 $lcattrib = strtolower( $attrib );
370 if ( is_array( $value ) ) {
371 $value = implode( ' ', $value );
372 } else {
373 $value = strval( $value );
374 }
375
376 // Simple checks using $attribDefaults
377 if ( isset( $attribDefaults[$element][$lcattrib] )
378 && $attribDefaults[$element][$lcattrib] == $value
379 ) {
380 unset( $attribs[$attrib] );
381 }
382
383 if ( $lcattrib == 'class' && $value == '' ) {
384 unset( $attribs[$attrib] );
385 }
386 }
387
388 // More subtle checks
389 if ( $element === 'link'
390 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
391 ) {
392 unset( $attribs['type'] );
393 }
394 if ( $element === 'input' ) {
395 $type = $attribs['type'] ?? null;
396 $value = $attribs['value'] ?? null;
397 if ( $type === 'checkbox' || $type === 'radio' ) {
398 // The default value for checkboxes and radio buttons is 'on'
399 // not ''. By stripping value="" we break radio boxes that
400 // actually wants empty values.
401 if ( $value === 'on' ) {
402 unset( $attribs['value'] );
403 }
404 } elseif ( $type === 'submit' ) {
405 // The default value for submit appears to be "Submit" but
406 // let's not bother stripping out localized text that matches
407 // that.
408 } else {
409 // The default value for nearly every other field type is ''
410 // The 'range' and 'color' types use different defaults but
411 // stripping a value="" does not hurt them.
412 if ( $value === '' ) {
413 unset( $attribs['value'] );
414 }
415 }
416 }
417 if ( $element === 'select' && isset( $attribs['size'] ) ) {
418 if ( in_array( 'multiple', $attribs )
419 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
420 ) {
421 // A multi-select
422 if ( strval( $attribs['size'] ) == '4' ) {
423 unset( $attribs['size'] );
424 }
425 } else {
426 // Single select
427 if ( strval( $attribs['size'] ) == '1' ) {
428 unset( $attribs['size'] );
429 }
430 }
431 }
432
433 return $attribs;
434 }
435
436 /**
437 * Given an associative array of element attributes, generate a string
438 * to stick after the element name in HTML output. Like [ 'href' =>
439 * 'https://www.mediawiki.org/' ] becomes something like
440 * ' href="https://www.mediawiki.org"'. Again, this is like
441 * Xml::expandAttributes(), but it implements some HTML-specific logic.
442 *
443 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
444 * values are allowed as well, which will automagically be normalized
445 * and converted to a space-separated string. In addition to a numerical
446 * array, the attribute value may also be an associative array. See the
447 * example below for how that works.
448 *
449 * @par Numerical array
450 * @code
451 * Html::element( 'em', [
452 * 'class' => [ 'foo', 'bar' ]
453 * ] );
454 * // gives '<em class="foo bar"></em>'
455 * @endcode
456 *
457 * @par Associative array
458 * @code
459 * Html::element( 'em', [
460 * 'class' => [ 'foo', 'bar', 'foo' => false, 'quux' => true ]
461 * ] );
462 * // gives '<em class="bar quux"></em>'
463 * @endcode
464 *
465 * @param array $attribs Associative array of attributes, e.g., [
466 * 'href' => 'https://www.mediawiki.org/' ]. Values will be HTML-escaped.
467 * A value of false or null means to omit the attribute. For boolean attributes,
468 * you can omit the key, e.g., [ 'checked' ] instead of
469 * [ 'checked' => 'checked' ] or such.
470 *
471 * @throws MWException If an attribute that doesn't allow lists is set to an array
472 * @return string HTML fragment that goes between element name and '>'
473 * (starting with a space if at least one attribute is output)
474 */
475 public static function expandAttributes( array $attribs ) {
476 $ret = '';
477 foreach ( $attribs as $key => $value ) {
478 // Support intuitive [ 'checked' => true/false ] form
479 if ( $value === false || is_null( $value ) ) {
480 continue;
481 }
482
483 // For boolean attributes, support [ 'foo' ] instead of
484 // requiring [ 'foo' => 'meaningless' ].
485 if ( is_int( $key ) && in_array( strtolower( $value ), self::$boolAttribs ) ) {
486 $key = $value;
487 }
488
489 // Not technically required in HTML5 but we'd like consistency
490 // and better compression anyway.
491 $key = strtolower( $key );
492
493 // https://www.w3.org/TR/html401/index/attributes.html ("space-separated")
494 // https://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
495 $spaceSeparatedListAttributes = [
496 'class', // html4, html5
497 'accesskey', // as of html5, multiple space-separated values allowed
498 // html4-spec doesn't document rel= as space-separated
499 // but has been used like that and is now documented as such
500 // in the html5-spec.
501 'rel',
502 ];
503
504 // Specific features for attributes that allow a list of space-separated values
505 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
506 // Apply some normalization and remove duplicates
507
508 // Convert into correct array. Array can contain space-separated
509 // values. Implode/explode to get those into the main array as well.
510 if ( is_array( $value ) ) {
511 // If input wasn't an array, we can skip this step
512 $newValue = [];
513 foreach ( $value as $k => $v ) {
514 if ( is_string( $v ) ) {
515 // String values should be normal `array( 'foo' )`
516 // Just append them
517 if ( !isset( $value[$v] ) ) {
518 // As a special case don't set 'foo' if a
519 // separate 'foo' => true/false exists in the array
520 // keys should be authoritative
521 $newValue[] = $v;
522 }
523 } elseif ( $v ) {
524 // If the value is truthy but not a string this is likely
525 // an [ 'foo' => true ], falsy values don't add strings
526 $newValue[] = $k;
527 }
528 }
529 $value = implode( ' ', $newValue );
530 }
531 $value = explode( ' ', $value );
532
533 // Normalize spacing by fixing up cases where people used
534 // more than 1 space and/or a trailing/leading space
535 $value = array_diff( $value, [ '', ' ' ] );
536
537 // Remove duplicates and create the string
538 $value = implode( ' ', array_unique( $value ) );
539 } elseif ( is_array( $value ) ) {
540 throw new MWException( "HTML attribute $key can not contain a list of values" );
541 }
542
543 $quote = '"';
544
545 if ( in_array( $key, self::$boolAttribs ) ) {
546 $ret .= " $key=\"\"";
547 } else {
548 $ret .= " $key=$quote" . Sanitizer::encodeAttribute( $value ) . $quote;
549 }
550 }
551 return $ret;
552 }
553
554 /**
555 * Output an HTML script tag with the given contents.
556 *
557 * It is unsupported for the contents to contain the sequence `<script` or `</script`
558 * (case-insensitive). This ensures the script can be terminated easily and consistently.
559 * It is the responsibility of the caller to avoid such character sequence by escaping
560 * or avoiding it. If found at run-time, the contents are replaced with a comment, and
561 * a warning is logged server-side.
562 *
563 * @param string $contents JavaScript
564 * @param string|null $nonce Nonce for CSP header, from OutputPage::getCSPNonce()
565 * @return string Raw HTML
566 */
567 public static function inlineScript( $contents, $nonce = null ) {
568 $attrs = [];
569 if ( $nonce !== null ) {
570 $attrs['nonce'] = $nonce;
571 } else {
572 if ( ContentSecurityPolicy::isNonceRequired( RequestContext::getMain()->getConfig() ) ) {
573 wfWarn( "no nonce set on script. CSP will break it" );
574 }
575 }
576
577 if ( preg_match( '/<\/?script/i', $contents ) ) {
578 wfLogWarning( __METHOD__ . ': Illegal character sequence found in inline script.' );
579 $contents = '/* ERROR: Invalid script */';
580 }
581
582 return self::rawElement( 'script', $attrs, $contents );
583 }
584
585 /**
586 * Output a "<script>" tag linking to the given URL, e.g.,
587 * "<script src=foo.js></script>".
588 *
589 * @param string $url
590 * @param string|null $nonce Nonce for CSP header, from OutputPage::getCSPNonce()
591 * @return string Raw HTML
592 */
593 public static function linkedScript( $url, $nonce = null ) {
594 $attrs = [ 'src' => $url ];
595 if ( $nonce !== null ) {
596 $attrs['nonce'] = $nonce;
597 } else {
598 if ( ContentSecurityPolicy::isNonceRequired( RequestContext::getMain()->getConfig() ) ) {
599 wfWarn( "no nonce set on script. CSP will break it" );
600 }
601 }
602
603 return self::element( 'script', $attrs );
604 }
605
606 /**
607 * Output a "<style>" tag with the given contents for the given media type
608 * (if any). TODO: do some useful escaping as well, like if $contents
609 * contains literal "</style>" (admittedly unlikely).
610 *
611 * @param string $contents CSS
612 * @param string $media A media type string, like 'screen'
613 * @param array $attribs (since 1.31) Associative array of attributes, e.g., [
614 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
615 * further documentation.
616 * @return string Raw HTML
617 */
618 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
619 // Don't escape '>' since that is used
620 // as direct child selector.
621 // Remember, in css, there is no "x" for hexadecimal escapes, and
622 // the space immediately after an escape sequence is swallowed.
623 $contents = strtr( $contents, [
624 '<' => '\3C ',
625 // CDATA end tag for good measure, but the main security
626 // is from escaping the '<'.
627 ']]>' => '\5D\5D\3E '
628 ] );
629
630 if ( preg_match( '/[<&]/', $contents ) ) {
631 $contents = "/*<![CDATA[*/$contents/*]]>*/";
632 }
633
634 return self::rawElement( 'style', [
635 'media' => $media,
636 ] + $attribs, $contents );
637 }
638
639 /**
640 * Output a "<link rel=stylesheet>" linking to the given URL for the given
641 * media type (if any).
642 *
643 * @param string $url
644 * @param string $media A media type string, like 'screen'
645 * @return string Raw HTML
646 */
647 public static function linkedStyle( $url, $media = 'all' ) {
648 return self::element( 'link', [
649 'rel' => 'stylesheet',
650 'href' => $url,
651 'media' => $media,
652 ] );
653 }
654
655 /**
656 * Convenience function to produce an "<input>" element. This supports the
657 * new HTML5 input types and attributes.
658 *
659 * @param string $name Name attribute
660 * @param string $value Value attribute
661 * @param string $type Type attribute
662 * @param array $attribs Associative array of miscellaneous extra
663 * attributes, passed to Html::element()
664 * @return string Raw HTML
665 */
666 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
667 $attribs['type'] = $type;
668 $attribs['value'] = $value;
669 $attribs['name'] = $name;
670 if ( in_array( $type, [ 'text', 'search', 'email', 'password', 'number' ] ) ) {
671 $attribs = self::getTextInputAttributes( $attribs );
672 }
673 if ( in_array( $type, [ 'button', 'reset', 'submit' ] ) ) {
674 $attribs = self::buttonAttributes( $attribs );
675 }
676 return self::element( 'input', $attribs );
677 }
678
679 /**
680 * Convenience function to produce a checkbox (input element with type=checkbox)
681 *
682 * @param string $name Name attribute
683 * @param bool $checked Whether the checkbox is checked or not
684 * @param array $attribs Array of additional attributes
685 * @return string Raw HTML
686 */
687 public static function check( $name, $checked = false, array $attribs = [] ) {
688 if ( isset( $attribs['value'] ) ) {
689 $value = $attribs['value'];
690 unset( $attribs['value'] );
691 } else {
692 $value = 1;
693 }
694
695 if ( $checked ) {
696 $attribs[] = 'checked';
697 }
698
699 return self::input( $name, $value, 'checkbox', $attribs );
700 }
701
702 /**
703 * Return the HTML for a message box.
704 * @since 1.31
705 * @param string $html of contents of box
706 * @param string $className corresponding to box
707 * @param string $heading (optional)
708 * @return string of HTML representing a box.
709 */
710 private static function messageBox( $html, $className, $heading = '' ) {
711 if ( $heading !== '' ) {
712 $html = self::element( 'h2', [], $heading ) . $html;
713 }
714 return self::rawElement( 'div', [ 'class' => $className ], $html );
715 }
716
717 /**
718 * Return a warning box.
719 * @since 1.31
720 * @param string $html of contents of box
721 * @return string of HTML representing a warning box.
722 */
723 public static function warningBox( $html ) {
724 return self::messageBox( $html, 'warningbox' );
725 }
726
727 /**
728 * Return an error box.
729 * @since 1.31
730 * @param string $html of contents of error box
731 * @param string $heading (optional)
732 * @return string of HTML representing an error box.
733 */
734 public static function errorBox( $html, $heading = '' ) {
735 return self::messageBox( $html, 'errorbox', $heading );
736 }
737
738 /**
739 * Return a success box.
740 * @since 1.31
741 * @param string $html of contents of box
742 * @return string of HTML representing a success box.
743 */
744 public static function successBox( $html ) {
745 return self::messageBox( $html, 'successbox' );
746 }
747
748 /**
749 * Convenience function to produce a radio button (input element with type=radio)
750 *
751 * @param string $name Name attribute
752 * @param bool $checked Whether the radio button is checked or not
753 * @param array $attribs Array of additional attributes
754 * @return string Raw HTML
755 */
756 public static function radio( $name, $checked = false, array $attribs = [] ) {
757 if ( isset( $attribs['value'] ) ) {
758 $value = $attribs['value'];
759 unset( $attribs['value'] );
760 } else {
761 $value = 1;
762 }
763
764 if ( $checked ) {
765 $attribs[] = 'checked';
766 }
767
768 return self::input( $name, $value, 'radio', $attribs );
769 }
770
771 /**
772 * Convenience function for generating a label for inputs.
773 *
774 * @param string $label Contents of the label
775 * @param string $id ID of the element being labeled
776 * @param array $attribs Additional attributes
777 * @return string Raw HTML
778 */
779 public static function label( $label, $id, array $attribs = [] ) {
780 $attribs += [
781 'for' => $id
782 ];
783 return self::element( 'label', $attribs, $label );
784 }
785
786 /**
787 * Convenience function to produce an input element with type=hidden
788 *
789 * @param string $name Name attribute
790 * @param string $value Value attribute
791 * @param array $attribs Associative array of miscellaneous extra
792 * attributes, passed to Html::element()
793 * @return string Raw HTML
794 */
795 public static function hidden( $name, $value, array $attribs = [] ) {
796 return self::input( $name, $value, 'hidden', $attribs );
797 }
798
799 /**
800 * Convenience function to produce a <textarea> element.
801 *
802 * This supports leaving out the cols= and rows= which Xml requires and are
803 * required by HTML4/XHTML but not required by HTML5.
804 *
805 * @param string $name Name attribute
806 * @param string $value Value attribute
807 * @param array $attribs Associative array of miscellaneous extra
808 * attributes, passed to Html::element()
809 * @return string Raw HTML
810 */
811 public static function textarea( $name, $value = '', array $attribs = [] ) {
812 $attribs['name'] = $name;
813
814 if ( substr( $value, 0, 1 ) == "\n" ) {
815 // Workaround for T14130: browsers eat the initial newline
816 // assuming that it's just for show, but they do keep the later
817 // newlines, which we may want to preserve during editing.
818 // Prepending a single newline
819 $spacedValue = "\n" . $value;
820 } else {
821 $spacedValue = $value;
822 }
823 return self::element( 'textarea', self::getTextInputAttributes( $attribs ), $spacedValue );
824 }
825
826 /**
827 * Helper for Html::namespaceSelector().
828 * @param array $params See Html::namespaceSelector()
829 * @return array
830 */
831 public static function namespaceSelectorOptions( array $params = [] ) {
832 $options = [];
833
834 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
835 $params['exclude'] = [];
836 }
837
838 if ( isset( $params['all'] ) ) {
839 // add an option that would let the user select all namespaces.
840 // Value is provided by user, the name shown is localized for the user.
841 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
842 }
843 // Add all namespaces as options (in the content language)
844 $options +=
845 MediaWikiServices::getInstance()->getContentLanguage()->getFormattedNamespaces();
846
847 $optionsOut = [];
848 // Filter out namespaces below 0 and massage labels
849 foreach ( $options as $nsId => $nsName ) {
850 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
851 continue;
852 }
853 if ( $nsId === NS_MAIN ) {
854 // For other namespaces use the namespace prefix as label, but for
855 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
856 $nsName = wfMessage( 'blanknamespace' )->text();
857 } elseif ( is_int( $nsId ) ) {
858 $nsName = MediaWikiServices::getInstance()->getContentLanguage()->
859 convertNamespace( $nsId );
860 }
861 $optionsOut[$nsId] = $nsName;
862 }
863
864 return $optionsOut;
865 }
866
867 /**
868 * Build a drop-down box for selecting a namespace
869 *
870 * @param array $params Params to set.
871 * - selected: [optional] Id of namespace which should be pre-selected
872 * - all: [optional] Value of item for "all namespaces". If null or unset,
873 * no "<option>" is generated to select all namespaces.
874 * - label: text for label to add before the field.
875 * - exclude: [optional] Array of namespace ids to exclude.
876 * - disable: [optional] Array of namespace ids for which the option should
877 * be disabled in the selector.
878 * @param array $selectAttribs HTML attributes for the generated select element.
879 * - id: [optional], default: 'namespace'.
880 * - name: [optional], default: 'namespace'.
881 * @return string HTML code to select a namespace.
882 */
883 public static function namespaceSelector( array $params = [],
884 array $selectAttribs = []
885 ) {
886 ksort( $selectAttribs );
887
888 // Is a namespace selected?
889 if ( isset( $params['selected'] ) ) {
890 // If string only contains digits, convert to clean int. Selected could also
891 // be "all" or "" etc. which needs to be left untouched.
892 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
893 // and returns false for already clean ints. Use regex instead..
894 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
895 $params['selected'] = intval( $params['selected'] );
896 }
897 // else: leaves it untouched for later processing
898 } else {
899 $params['selected'] = '';
900 }
901
902 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
903 $params['disable'] = [];
904 }
905
906 // Associative array between option-values and option-labels
907 $options = self::namespaceSelectorOptions( $params );
908
909 // Convert $options to HTML
910 $optionsHtml = [];
911 foreach ( $options as $nsId => $nsName ) {
912 $optionsHtml[] = self::element(
913 'option', [
914 'disabled' => in_array( $nsId, $params['disable'] ),
915 'value' => $nsId,
916 'selected' => $nsId === $params['selected'],
917 ], $nsName
918 );
919 }
920
921 if ( !array_key_exists( 'id', $selectAttribs ) ) {
922 $selectAttribs['id'] = 'namespace';
923 }
924
925 if ( !array_key_exists( 'name', $selectAttribs ) ) {
926 $selectAttribs['name'] = 'namespace';
927 }
928
929 $ret = '';
930 if ( isset( $params['label'] ) ) {
931 $ret .= self::element(
932 'label', [
933 'for' => $selectAttribs['id'] ?? null,
934 ], $params['label']
935 ) . "\u{00A0}";
936 }
937
938 // Wrap options in a <select>
939 $ret .= self::openElement( 'select', $selectAttribs )
940 . "\n"
941 . implode( "\n", $optionsHtml )
942 . "\n"
943 . self::closeElement( 'select' );
944
945 return $ret;
946 }
947
948 /**
949 * Constructs the opening html-tag with necessary doctypes depending on
950 * global variables.
951 *
952 * @param array $attribs Associative array of miscellaneous extra
953 * attributes, passed to Html::element() of html tag.
954 * @return string Raw HTML
955 */
956 public static function htmlHeader( array $attribs = [] ) {
957 $ret = '';
958
959 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
960
961 $isXHTML = self::isXmlMimeType( $wgMimeType );
962
963 if ( $isXHTML ) { // XHTML5
964 // XML MIME-typed markup should have an xml header.
965 // However a DOCTYPE is not needed.
966 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
967
968 // Add the standard xmlns
969 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
970
971 // And support custom namespaces
972 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
973 $attribs["xmlns:$tag"] = $ns;
974 }
975 } else { // HTML5
976 // DOCTYPE
977 $ret .= "<!DOCTYPE html>\n";
978 }
979
980 if ( $wgHtml5Version ) {
981 $attribs['version'] = $wgHtml5Version;
982 }
983
984 $ret .= self::openElement( 'html', $attribs );
985
986 return $ret;
987 }
988
989 /**
990 * Determines if the given MIME type is xml.
991 *
992 * @param string $mimetype MIME type
993 * @return bool
994 */
995 public static function isXmlMimeType( $mimetype ) {
996 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
997 # * text/xml
998 # * application/xml
999 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1000 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1001 }
1002
1003 /**
1004 * Get HTML for an info box with an icon.
1005 *
1006 * @param string $text Wikitext, get this with wfMessage()->plain()
1007 * @param string $icon Path to icon file (used as 'src' attribute)
1008 * @param string $alt Alternate text for the icon
1009 * @param string $class Additional class name to add to the wrapper div
1010 *
1011 * @return string
1012 */
1013 static function infoBox( $text, $icon, $alt, $class = '' ) {
1014 $s = self::openElement( 'div', [ 'class' => "mw-infobox $class" ] );
1015
1016 $s .= self::openElement( 'div', [ 'class' => 'mw-infobox-left' ] ) .
1017 self::element( 'img',
1018 [
1019 'src' => $icon,
1020 'alt' => $alt,
1021 ]
1022 ) .
1023 self::closeElement( 'div' );
1024
1025 $s .= self::openElement( 'div', [ 'class' => 'mw-infobox-right' ] ) .
1026 $text .
1027 self::closeElement( 'div' );
1028 $s .= self::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
1029
1030 $s .= self::closeElement( 'div' );
1031
1032 $s .= self::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
1033
1034 return $s;
1035 }
1036
1037 /**
1038 * Generate a srcset attribute value.
1039 *
1040 * Generates a srcset attribute value from an array mapping pixel densities
1041 * to URLs. A trailing 'x' in pixel density values is optional.
1042 *
1043 * @note srcset width and height values are not supported.
1044 *
1045 * @see https://html.spec.whatwg.org/#attr-img-srcset
1046 *
1047 * @par Example:
1048 * @code
1049 * Html::srcSet( [
1050 * '1x' => 'standard.jpeg',
1051 * '1.5x' => 'large.jpeg',
1052 * '3x' => 'extra-large.jpeg',
1053 * ] );
1054 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1055 * @endcode
1056 *
1057 * @param string[] $urls
1058 * @return string
1059 */
1060 static function srcSet( array $urls ) {
1061 $candidates = [];
1062 foreach ( $urls as $density => $url ) {
1063 // Cast density to float to strip 'x', then back to string to serve
1064 // as array index.
1065 $density = (string)(float)$density;
1066 $candidates[$density] = $url;
1067 }
1068
1069 // Remove duplicates that are the same as a smaller value
1070 ksort( $candidates, SORT_NUMERIC );
1071 $candidates = array_unique( $candidates );
1072
1073 // Append density info to the url
1074 foreach ( $candidates as $density => $url ) {
1075 $candidates[$density] = $url . ' ' . $density . 'x';
1076 }
1077
1078 return implode( ", ", $candidates );
1079 }
1080 }