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