Support a heading of '0' in Html::messageBox()
[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 a "<script>" tag with the given contents.
556 *
557 * @todo do some useful escaping as well, like if $contents contains
558 * literal "</script>" or (for XML) literal "]]>".
559 *
560 * @param string $contents JavaScript
561 * @param string|null $nonce Nonce for CSP header, from OutputPage::getCSPNonce()
562 * @return string Raw HTML
563 */
564 public static function inlineScript( $contents, $nonce = null ) {
565 $attrs = [];
566 if ( $nonce !== null ) {
567 $attrs['nonce'] = $nonce;
568 } else {
569 if ( ContentSecurityPolicy::isNonceRequired( RequestContext::getMain()->getConfig() ) ) {
570 wfWarn( "no nonce set on script. CSP will break it" );
571 }
572 }
573
574 if ( preg_match( '/[<&]/', $contents ) ) {
575 $contents = "/*<![CDATA[*/$contents/*]]>*/";
576 }
577
578 return self::rawElement( 'script', $attrs, $contents );
579 }
580
581 /**
582 * Output a "<script>" tag linking to the given URL, e.g.,
583 * "<script src=foo.js></script>".
584 *
585 * @param string $url
586 * @param string|null $nonce Nonce for CSP header, from OutputPage::getCSPNonce()
587 * @return string Raw HTML
588 */
589 public static function linkedScript( $url, $nonce = null ) {
590 $attrs = [ 'src' => $url ];
591 if ( $nonce !== null ) {
592 $attrs['nonce'] = $nonce;
593 } else {
594 if ( ContentSecurityPolicy::isNonceRequired( RequestContext::getMain()->getConfig() ) ) {
595 wfWarn( "no nonce set on script. CSP will break it" );
596 }
597 }
598
599 return self::element( 'script', $attrs );
600 }
601
602 /**
603 * Output a "<style>" tag with the given contents for the given media type
604 * (if any). TODO: do some useful escaping as well, like if $contents
605 * contains literal "</style>" (admittedly unlikely).
606 *
607 * @param string $contents CSS
608 * @param string $media A media type string, like 'screen'
609 * @param array $attribs (since 1.31) Associative array of attributes, e.g., [
610 * 'href' => 'https://www.mediawiki.org/' ]. See expandAttributes() for
611 * further documentation.
612 * @return string Raw HTML
613 */
614 public static function inlineStyle( $contents, $media = 'all', $attribs = [] ) {
615 // Don't escape '>' since that is used
616 // as direct child selector.
617 // Remember, in css, there is no "x" for hexadecimal escapes, and
618 // the space immediately after an escape sequence is swallowed.
619 $contents = strtr( $contents, [
620 '<' => '\3C ',
621 // CDATA end tag for good measure, but the main security
622 // is from escaping the '<'.
623 ']]>' => '\5D\5D\3E '
624 ] );
625
626 if ( preg_match( '/[<&]/', $contents ) ) {
627 $contents = "/*<![CDATA[*/$contents/*]]>*/";
628 }
629
630 return self::rawElement( 'style', [
631 'media' => $media,
632 ] + $attribs, $contents );
633 }
634
635 /**
636 * Output a "<link rel=stylesheet>" linking to the given URL for the given
637 * media type (if any).
638 *
639 * @param string $url
640 * @param string $media A media type string, like 'screen'
641 * @return string Raw HTML
642 */
643 public static function linkedStyle( $url, $media = 'all' ) {
644 return self::element( 'link', [
645 'rel' => 'stylesheet',
646 'href' => $url,
647 'media' => $media,
648 ] );
649 }
650
651 /**
652 * Convenience function to produce an "<input>" element. This supports the
653 * new HTML5 input types and attributes.
654 *
655 * @param string $name Name attribute
656 * @param string $value Value attribute
657 * @param string $type Type attribute
658 * @param array $attribs Associative array of miscellaneous extra
659 * attributes, passed to Html::element()
660 * @return string Raw HTML
661 */
662 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
663 $attribs['type'] = $type;
664 $attribs['value'] = $value;
665 $attribs['name'] = $name;
666 if ( in_array( $type, [ 'text', 'search', 'email', 'password', 'number' ] ) ) {
667 $attribs = self::getTextInputAttributes( $attribs );
668 }
669 if ( in_array( $type, [ 'button', 'reset', 'submit' ] ) ) {
670 $attribs = self::buttonAttributes( $attribs );
671 }
672 return self::element( 'input', $attribs );
673 }
674
675 /**
676 * Convenience function to produce a checkbox (input element with type=checkbox)
677 *
678 * @param string $name Name attribute
679 * @param bool $checked Whether the checkbox is checked or not
680 * @param array $attribs Array of additional attributes
681 * @return string Raw HTML
682 */
683 public static function check( $name, $checked = false, array $attribs = [] ) {
684 if ( isset( $attribs['value'] ) ) {
685 $value = $attribs['value'];
686 unset( $attribs['value'] );
687 } else {
688 $value = 1;
689 }
690
691 if ( $checked ) {
692 $attribs[] = 'checked';
693 }
694
695 return self::input( $name, $value, 'checkbox', $attribs );
696 }
697
698 /**
699 * Return the HTML for a message box.
700 * @since 1.31
701 * @param string $html of contents of box
702 * @param string $className corresponding to box
703 * @param string $heading (optional)
704 * @return string of HTML representing a box.
705 */
706 private static function messageBox( $html, $className, $heading = '' ) {
707 if ( $heading !== '' ) {
708 $html = self::element( 'h2', [], $heading ) . $html;
709 }
710 return self::rawElement( 'div', [ 'class' => $className ], $html );
711 }
712
713 /**
714 * Return a warning box.
715 * @since 1.31
716 * @param string $html of contents of box
717 * @return string of HTML representing a warning box.
718 */
719 public static function warningBox( $html ) {
720 return self::messageBox( $html, 'warningbox' );
721 }
722
723 /**
724 * Return an error box.
725 * @since 1.31
726 * @param string $html of contents of error box
727 * @param string $heading (optional)
728 * @return string of HTML representing an error box.
729 */
730 public static function errorBox( $html, $heading = '' ) {
731 return self::messageBox( $html, 'errorbox', $heading );
732 }
733
734 /**
735 * Return a success box.
736 * @since 1.31
737 * @param string $html of contents of box
738 * @return string of HTML representing a success box.
739 */
740 public static function successBox( $html ) {
741 return self::messageBox( $html, 'successbox' );
742 }
743
744 /**
745 * Convenience function to produce a radio button (input element with type=radio)
746 *
747 * @param string $name Name attribute
748 * @param bool $checked Whether the radio button is checked or not
749 * @param array $attribs Array of additional attributes
750 * @return string Raw HTML
751 */
752 public static function radio( $name, $checked = false, array $attribs = [] ) {
753 if ( isset( $attribs['value'] ) ) {
754 $value = $attribs['value'];
755 unset( $attribs['value'] );
756 } else {
757 $value = 1;
758 }
759
760 if ( $checked ) {
761 $attribs[] = 'checked';
762 }
763
764 return self::input( $name, $value, 'radio', $attribs );
765 }
766
767 /**
768 * Convenience function for generating a label for inputs.
769 *
770 * @param string $label Contents of the label
771 * @param string $id ID of the element being labeled
772 * @param array $attribs Additional attributes
773 * @return string Raw HTML
774 */
775 public static function label( $label, $id, array $attribs = [] ) {
776 $attribs += [
777 'for' => $id
778 ];
779 return self::element( 'label', $attribs, $label );
780 }
781
782 /**
783 * Convenience function to produce an input element with type=hidden
784 *
785 * @param string $name Name attribute
786 * @param string $value Value attribute
787 * @param array $attribs Associative array of miscellaneous extra
788 * attributes, passed to Html::element()
789 * @return string Raw HTML
790 */
791 public static function hidden( $name, $value, array $attribs = [] ) {
792 return self::input( $name, $value, 'hidden', $attribs );
793 }
794
795 /**
796 * Convenience function to produce a <textarea> element.
797 *
798 * This supports leaving out the cols= and rows= which Xml requires and are
799 * required by HTML4/XHTML but not required by HTML5.
800 *
801 * @param string $name Name attribute
802 * @param string $value Value attribute
803 * @param array $attribs Associative array of miscellaneous extra
804 * attributes, passed to Html::element()
805 * @return string Raw HTML
806 */
807 public static function textarea( $name, $value = '', array $attribs = [] ) {
808 $attribs['name'] = $name;
809
810 if ( substr( $value, 0, 1 ) == "\n" ) {
811 // Workaround for T14130: browsers eat the initial newline
812 // assuming that it's just for show, but they do keep the later
813 // newlines, which we may want to preserve during editing.
814 // Prepending a single newline
815 $spacedValue = "\n" . $value;
816 } else {
817 $spacedValue = $value;
818 }
819 return self::element( 'textarea', self::getTextInputAttributes( $attribs ), $spacedValue );
820 }
821
822 /**
823 * Helper for Html::namespaceSelector().
824 * @param array $params See Html::namespaceSelector()
825 * @return array
826 */
827 public static function namespaceSelectorOptions( array $params = [] ) {
828 $options = [];
829
830 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
831 $params['exclude'] = [];
832 }
833
834 if ( isset( $params['all'] ) ) {
835 // add an option that would let the user select all namespaces.
836 // Value is provided by user, the name shown is localized for the user.
837 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
838 }
839 // Add all namespaces as options (in the content language)
840 $options +=
841 MediaWikiServices::getInstance()->getContentLanguage()->getFormattedNamespaces();
842
843 $optionsOut = [];
844 // Filter out namespaces below 0 and massage labels
845 foreach ( $options as $nsId => $nsName ) {
846 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
847 continue;
848 }
849 if ( $nsId === NS_MAIN ) {
850 // For other namespaces use the namespace prefix as label, but for
851 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
852 $nsName = wfMessage( 'blanknamespace' )->text();
853 } elseif ( is_int( $nsId ) ) {
854 $nsName = MediaWikiServices::getInstance()->getContentLanguage()->
855 convertNamespace( $nsId );
856 }
857 $optionsOut[$nsId] = $nsName;
858 }
859
860 return $optionsOut;
861 }
862
863 /**
864 * Build a drop-down box for selecting a namespace
865 *
866 * @param array $params Params to set.
867 * - selected: [optional] Id of namespace which should be pre-selected
868 * - all: [optional] Value of item for "all namespaces". If null or unset,
869 * no "<option>" is generated to select all namespaces.
870 * - label: text for label to add before the field.
871 * - exclude: [optional] Array of namespace ids to exclude.
872 * - disable: [optional] Array of namespace ids for which the option should
873 * be disabled in the selector.
874 * @param array $selectAttribs HTML attributes for the generated select element.
875 * - id: [optional], default: 'namespace'.
876 * - name: [optional], default: 'namespace'.
877 * @return string HTML code to select a namespace.
878 */
879 public static function namespaceSelector( array $params = [],
880 array $selectAttribs = []
881 ) {
882 ksort( $selectAttribs );
883
884 // Is a namespace selected?
885 if ( isset( $params['selected'] ) ) {
886 // If string only contains digits, convert to clean int. Selected could also
887 // be "all" or "" etc. which needs to be left untouched.
888 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
889 // and returns false for already clean ints. Use regex instead..
890 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
891 $params['selected'] = intval( $params['selected'] );
892 }
893 // else: leaves it untouched for later processing
894 } else {
895 $params['selected'] = '';
896 }
897
898 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
899 $params['disable'] = [];
900 }
901
902 // Associative array between option-values and option-labels
903 $options = self::namespaceSelectorOptions( $params );
904
905 // Convert $options to HTML
906 $optionsHtml = [];
907 foreach ( $options as $nsId => $nsName ) {
908 $optionsHtml[] = self::element(
909 'option', [
910 'disabled' => in_array( $nsId, $params['disable'] ),
911 'value' => $nsId,
912 'selected' => $nsId === $params['selected'],
913 ], $nsName
914 );
915 }
916
917 if ( !array_key_exists( 'id', $selectAttribs ) ) {
918 $selectAttribs['id'] = 'namespace';
919 }
920
921 if ( !array_key_exists( 'name', $selectAttribs ) ) {
922 $selectAttribs['name'] = 'namespace';
923 }
924
925 $ret = '';
926 if ( isset( $params['label'] ) ) {
927 $ret .= self::element(
928 'label', [
929 'for' => $selectAttribs['id'] ?? null,
930 ], $params['label']
931 ) . "\u{00A0}";
932 }
933
934 // Wrap options in a <select>
935 $ret .= self::openElement( 'select', $selectAttribs )
936 . "\n"
937 . implode( "\n", $optionsHtml )
938 . "\n"
939 . self::closeElement( 'select' );
940
941 return $ret;
942 }
943
944 /**
945 * Constructs the opening html-tag with necessary doctypes depending on
946 * global variables.
947 *
948 * @param array $attribs Associative array of miscellaneous extra
949 * attributes, passed to Html::element() of html tag.
950 * @return string Raw HTML
951 */
952 public static function htmlHeader( array $attribs = [] ) {
953 $ret = '';
954
955 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
956
957 $isXHTML = self::isXmlMimeType( $wgMimeType );
958
959 if ( $isXHTML ) { // XHTML5
960 // XML MIME-typed markup should have an xml header.
961 // However a DOCTYPE is not needed.
962 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
963
964 // Add the standard xmlns
965 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
966
967 // And support custom namespaces
968 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
969 $attribs["xmlns:$tag"] = $ns;
970 }
971 } else { // HTML5
972 // DOCTYPE
973 $ret .= "<!DOCTYPE html>\n";
974 }
975
976 if ( $wgHtml5Version ) {
977 $attribs['version'] = $wgHtml5Version;
978 }
979
980 $ret .= self::openElement( 'html', $attribs );
981
982 return $ret;
983 }
984
985 /**
986 * Determines if the given MIME type is xml.
987 *
988 * @param string $mimetype MIME type
989 * @return bool
990 */
991 public static function isXmlMimeType( $mimetype ) {
992 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
993 # * text/xml
994 # * application/xml
995 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
996 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
997 }
998
999 /**
1000 * Get HTML for an info box with an icon.
1001 *
1002 * @param string $text Wikitext, get this with wfMessage()->plain()
1003 * @param string $icon Path to icon file (used as 'src' attribute)
1004 * @param string $alt Alternate text for the icon
1005 * @param string $class Additional class name to add to the wrapper div
1006 *
1007 * @return string
1008 */
1009 static function infoBox( $text, $icon, $alt, $class = '' ) {
1010 $s = self::openElement( 'div', [ 'class' => "mw-infobox $class" ] );
1011
1012 $s .= self::openElement( 'div', [ 'class' => 'mw-infobox-left' ] ) .
1013 self::element( 'img',
1014 [
1015 'src' => $icon,
1016 'alt' => $alt,
1017 ]
1018 ) .
1019 self::closeElement( 'div' );
1020
1021 $s .= self::openElement( 'div', [ 'class' => 'mw-infobox-right' ] ) .
1022 $text .
1023 self::closeElement( 'div' );
1024 $s .= self::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
1025
1026 $s .= self::closeElement( 'div' );
1027
1028 $s .= self::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
1029
1030 return $s;
1031 }
1032
1033 /**
1034 * Generate a srcset attribute value.
1035 *
1036 * Generates a srcset attribute value from an array mapping pixel densities
1037 * to URLs. A trailing 'x' in pixel density values is optional.
1038 *
1039 * @note srcset width and height values are not supported.
1040 *
1041 * @see https://html.spec.whatwg.org/#attr-img-srcset
1042 *
1043 * @par Example:
1044 * @code
1045 * Html::srcSet( [
1046 * '1x' => 'standard.jpeg',
1047 * '1.5x' => 'large.jpeg',
1048 * '3x' => 'extra-large.jpeg',
1049 * ] );
1050 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1051 * @endcode
1052 *
1053 * @param string[] $urls
1054 * @return string
1055 */
1056 static function srcSet( array $urls ) {
1057 $candidates = [];
1058 foreach ( $urls as $density => $url ) {
1059 // Cast density to float to strip 'x', then back to string to serve
1060 // as array index.
1061 $density = (string)(float)$density;
1062 $candidates[$density] = $url;
1063 }
1064
1065 // Remove duplicates that are the same as a smaller value
1066 ksort( $candidates, SORT_NUMERIC );
1067 $candidates = array_unique( $candidates );
1068
1069 // Append density info to the url
1070 foreach ( $candidates as $density => $url ) {
1071 $candidates[$density] = $url . ' ' . $density . 'x';
1072 }
1073
1074 return implode( ", ", $candidates );
1075 }
1076 }