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