Merge "Make Special:Contributions use OOUI"
[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 $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 * @param string $html of contents of box
722 * @return string of HTML representing a warning box.
723 */
724 public static function warningBox( $html ) {
725 return self::messageBox( $html, 'warningbox' );
726 }
727
728 /**
729 * Return an error box.
730 * @since 1.31
731 * @param string $html of contents of error box
732 * @param string $heading (optional)
733 * @return string of HTML representing an error box.
734 */
735 public static function errorBox( $html, $heading = '' ) {
736 return self::messageBox( $html, 'errorbox', $heading );
737 }
738
739 /**
740 * Return a success box.
741 * @since 1.31
742 * @param string $html of contents of box
743 * @return string of HTML representing a success box.
744 */
745 public static function successBox( $html ) {
746 return self::messageBox( $html, 'successbox' );
747 }
748
749 /**
750 * Convenience function to produce a radio button (input element with type=radio)
751 *
752 * @param string $name Name attribute
753 * @param bool $checked Whether the radio button is checked or not
754 * @param array $attribs Array of additional attributes
755 * @return string Raw HTML
756 */
757 public static function radio( $name, $checked = false, array $attribs = [] ) {
758 if ( isset( $attribs['value'] ) ) {
759 $value = $attribs['value'];
760 unset( $attribs['value'] );
761 } else {
762 $value = 1;
763 }
764
765 if ( $checked ) {
766 $attribs[] = 'checked';
767 }
768
769 return self::input( $name, $value, 'radio', $attribs );
770 }
771
772 /**
773 * Convenience function for generating a label for inputs.
774 *
775 * @param string $label Contents of the label
776 * @param string $id ID of the element being labeled
777 * @param array $attribs Additional attributes
778 * @return string Raw HTML
779 */
780 public static function label( $label, $id, array $attribs = [] ) {
781 $attribs += [
782 'for' => $id
783 ];
784 return self::element( 'label', $attribs, $label );
785 }
786
787 /**
788 * Convenience function to produce an input element with type=hidden
789 *
790 * @param string $name Name attribute
791 * @param string $value Value attribute
792 * @param array $attribs Associative array of miscellaneous extra
793 * attributes, passed to Html::element()
794 * @return string Raw HTML
795 */
796 public static function hidden( $name, $value, array $attribs = [] ) {
797 return self::input( $name, $value, 'hidden', $attribs );
798 }
799
800 /**
801 * Convenience function to produce a <textarea> element.
802 *
803 * This supports leaving out the cols= and rows= which Xml requires and are
804 * required by HTML4/XHTML but not required by HTML5.
805 *
806 * @param string $name Name attribute
807 * @param string $value Value attribute
808 * @param array $attribs Associative array of miscellaneous extra
809 * attributes, passed to Html::element()
810 * @return string Raw HTML
811 */
812 public static function textarea( $name, $value = '', array $attribs = [] ) {
813 $attribs['name'] = $name;
814
815 if ( substr( $value, 0, 1 ) == "\n" ) {
816 // Workaround for T14130: browsers eat the initial newline
817 // assuming that it's just for show, but they do keep the later
818 // newlines, which we may want to preserve during editing.
819 // Prepending a single newline
820 $spacedValue = "\n" . $value;
821 } else {
822 $spacedValue = $value;
823 }
824 return self::element( 'textarea', self::getTextInputAttributes( $attribs ), $spacedValue );
825 }
826
827 /**
828 * Helper for Html::namespaceSelector().
829 * @param array $params See Html::namespaceSelector()
830 * @return array
831 */
832 public static function namespaceSelectorOptions( array $params = [] ) {
833 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
834 $params['exclude'] = [];
835 }
836
837 if ( $params['in-user-lang'] ?? false ) {
838 global $wgLang;
839 $lang = $wgLang;
840 } else {
841 $lang = MediaWikiServices::getInstance()->getContentLanguage();
842 }
843
844 $optionsOut = [];
845 if ( isset( $params['all'] ) ) {
846 // add an option that would let the user select all namespaces.
847 // Value is provided by user, the name shown is localized for the user.
848 $optionsOut[$params['all']] = wfMessage( 'namespacesall' )->text();
849 }
850 // Add all namespaces as options
851 $options = $lang->getFormattedNamespaces();
852 // Filter out namespaces below 0 and massage labels
853 foreach ( $options as $nsId => $nsName ) {
854 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
855 continue;
856 }
857 if ( $nsId === NS_MAIN ) {
858 // For other namespaces use the namespace prefix as label, but for
859 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
860 $nsName = wfMessage( 'blanknamespace' )->text();
861 } elseif ( is_int( $nsId ) ) {
862 $nsName = $lang->convertNamespace( $nsId );
863 }
864 $optionsOut[$nsId] = $nsName;
865 }
866
867 return $optionsOut;
868 }
869
870 /**
871 * Build a drop-down box for selecting a namespace
872 *
873 * @param array $params Params to set.
874 * - selected: [optional] Id of namespace which should be pre-selected
875 * - all: [optional] Value of item for "all namespaces". If null or unset,
876 * no "<option>" is generated to select all namespaces.
877 * - label: text for label to add before the field.
878 * - exclude: [optional] Array of namespace ids to exclude.
879 * - disable: [optional] Array of namespace ids for which the option should
880 * be disabled in the selector.
881 * @param array $selectAttribs HTML attributes for the generated select element.
882 * - id: [optional], default: 'namespace'.
883 * - name: [optional], default: 'namespace'.
884 * @return string HTML code to select a namespace.
885 */
886 public static function namespaceSelector( array $params = [],
887 array $selectAttribs = []
888 ) {
889 ksort( $selectAttribs );
890
891 // Is a namespace selected?
892 if ( isset( $params['selected'] ) ) {
893 // If string only contains digits, convert to clean int. Selected could also
894 // be "all" or "" etc. which needs to be left untouched.
895 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
896 // and returns false for already clean ints. Use regex instead..
897 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
898 $params['selected'] = intval( $params['selected'] );
899 }
900 // else: leaves it untouched for later processing
901 } else {
902 $params['selected'] = '';
903 }
904
905 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
906 $params['disable'] = [];
907 }
908
909 // Associative array between option-values and option-labels
910 $options = self::namespaceSelectorOptions( $params );
911
912 // Convert $options to HTML
913 $optionsHtml = [];
914 foreach ( $options as $nsId => $nsName ) {
915 $optionsHtml[] = self::element(
916 'option', [
917 'disabled' => in_array( $nsId, $params['disable'] ),
918 'value' => $nsId,
919 'selected' => $nsId === $params['selected'],
920 ], $nsName
921 );
922 }
923
924 if ( !array_key_exists( 'id', $selectAttribs ) ) {
925 $selectAttribs['id'] = 'namespace';
926 }
927
928 if ( !array_key_exists( 'name', $selectAttribs ) ) {
929 $selectAttribs['name'] = 'namespace';
930 }
931
932 $ret = '';
933 if ( isset( $params['label'] ) ) {
934 $ret .= self::element(
935 'label', [
936 'for' => $selectAttribs['id'] ?? null,
937 ], $params['label']
938 ) . "\u{00A0}";
939 }
940
941 // Wrap options in a <select>
942 $ret .= self::openElement( 'select', $selectAttribs )
943 . "\n"
944 . implode( "\n", $optionsHtml )
945 . "\n"
946 . self::closeElement( 'select' );
947
948 return $ret;
949 }
950
951 /**
952 * Constructs the opening html-tag with necessary doctypes depending on
953 * global variables.
954 *
955 * @param array $attribs Associative array of miscellaneous extra
956 * attributes, passed to Html::element() of html tag.
957 * @return string Raw HTML
958 */
959 public static function htmlHeader( array $attribs = [] ) {
960 $ret = '';
961
962 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
963
964 $isXHTML = self::isXmlMimeType( $wgMimeType );
965
966 if ( $isXHTML ) { // XHTML5
967 // XML MIME-typed markup should have an xml header.
968 // However a DOCTYPE is not needed.
969 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
970
971 // Add the standard xmlns
972 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
973
974 // And support custom namespaces
975 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
976 $attribs["xmlns:$tag"] = $ns;
977 }
978 } else { // HTML5
979 $ret .= "<!DOCTYPE html>\n";
980 }
981
982 if ( $wgHtml5Version ) {
983 $attribs['version'] = $wgHtml5Version;
984 }
985
986 $ret .= self::openElement( 'html', $attribs );
987
988 return $ret;
989 }
990
991 /**
992 * Determines if the given MIME type is xml.
993 *
994 * @param string $mimetype MIME type
995 * @return bool
996 */
997 public static function isXmlMimeType( $mimetype ) {
998 # https://html.spec.whatwg.org/multipage/infrastructure.html#xml-mime-type
999 # * text/xml
1000 # * application/xml
1001 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1002 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1003 }
1004
1005 /**
1006 * Get HTML for an information message box with an icon.
1007 *
1008 * @internal For use by the WebInstaller class.
1009 * @param string $rawHtml HTML
1010 * @param string $icon Path to icon file (used as 'src' attribute)
1011 * @param string $alt Alternate text for the icon
1012 * @param string $class Additional class name to add to the wrapper div
1013 * @return string HTML
1014 */
1015 public static function infoBox( $rawHtml, $icon, $alt, $class = '' ) {
1016 $s = self::openElement( 'div', [ 'class' => "mw-infobox $class" ] );
1017
1018 $s .= self::openElement( 'div', [ 'class' => 'mw-infobox-left' ] ) .
1019 self::element( 'img',
1020 [
1021 'src' => $icon,
1022 'alt' => $alt,
1023 ]
1024 ) .
1025 self::closeElement( 'div' );
1026
1027 $s .= self::openElement( 'div', [ 'class' => 'mw-infobox-right' ] ) .
1028 $rawHtml .
1029 self::closeElement( 'div' );
1030 $s .= self::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
1031
1032 $s .= self::closeElement( 'div' );
1033
1034 $s .= self::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
1035
1036 return $s;
1037 }
1038
1039 /**
1040 * Generate a srcset attribute value.
1041 *
1042 * Generates a srcset attribute value from an array mapping pixel densities
1043 * to URLs. A trailing 'x' in pixel density values is optional.
1044 *
1045 * @note srcset width and height values are not supported.
1046 *
1047 * @see https://html.spec.whatwg.org/#attr-img-srcset
1048 *
1049 * @par Example:
1050 * @code
1051 * Html::srcSet( [
1052 * '1x' => 'standard.jpeg',
1053 * '1.5x' => 'large.jpeg',
1054 * '3x' => 'extra-large.jpeg',
1055 * ] );
1056 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1057 * @endcode
1058 *
1059 * @param string[] $urls
1060 * @return string
1061 */
1062 static function srcSet( array $urls ) {
1063 $candidates = [];
1064 foreach ( $urls as $density => $url ) {
1065 // Cast density to float to strip 'x', then back to string to serve
1066 // as array index.
1067 $density = (string)(float)$density;
1068 $candidates[$density] = $url;
1069 }
1070
1071 // Remove duplicates that are the same as a smaller value
1072 ksort( $candidates, SORT_NUMERIC );
1073 $candidates = array_unique( $candidates );
1074
1075 // Append density info to the url
1076 foreach ( $candidates as $density => $url ) {
1077 $candidates[$density] = $url . ' ' . $density . 'x';
1078 }
1079
1080 return implode( ", ", $candidates );
1081 }
1082 }