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