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