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 = array(
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 = array(
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 = array() ) {
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 = array() ) {
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 = array() ) {
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 = array(), $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 = array(), $contents = '' ) {
238 return self::rawElement( $element, $attribs, strtr( $contents, array(
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 = array() ) {
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 = array(
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 = array(
340 'area' => array( 'shape' => 'rect' ),
341 'button' => array(
342 'formaction' => 'GET',
343 'formenctype' => 'application/x-www-form-urlencoded',
344 ),
345 'canvas' => array(
346 'height' => '150',
347 'width' => '300',
348 ),
349 'command' => array( 'type' => 'command' ),
350 'form' => array(
351 'action' => 'GET',
352 'autocomplete' => 'on',
353 'enctype' => 'application/x-www-form-urlencoded',
354 ),
355 'input' => array(
356 'formaction' => 'GET',
357 'type' => 'text',
358 ),
359 'keygen' => array( 'keytype' => 'rsa' ),
360 'link' => array( 'media' => 'all' ),
361 'menu' => array( 'type' => 'list' ),
362 // Note: the use of text/javascript here instead of other JavaScript
363 // MIME types follows the HTML5 spec.
364 'script' => array( 'type' => 'text/javascript' ),
365 'style' => array(
366 'media' => 'all',
367 'type' => 'text/css',
368 ),
369 'textarea' => array( '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 = isset( $attribs['type'] ) ? $attribs['type'] : null;
402 $value = isset( $attribs['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 array( 'href' =>
445 * 'http://www.mediawiki.org/' ) becomes something like
446 * ' href="http://www.mediawiki.org"'. Again, this is like
447 * Xml::expandAttributes(), but it implements some HTML-specific logic.
448 * For instance, it will omit quotation marks if $wgWellFormedXml is false,
449 * and will treat boolean attributes specially.
450 *
451 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
452 * values are allowed as well, which will automagically be normalized
453 * and converted to a space-separated string. In addition to a numerical
454 * array, the attribute value may also be an associative array. See the
455 * example below for how that works.
456 *
457 * @par Numerical array
458 * @code
459 * Html::element( 'em', array(
460 * 'class' => array( 'foo', 'bar' )
461 * ) );
462 * // gives '<em class="foo bar"></em>'
463 * @endcode
464 *
465 * @par Associative array
466 * @code
467 * Html::element( 'em', array(
468 * 'class' => array( 'foo', 'bar', 'foo' => false, 'quux' => true )
469 * ) );
470 * // gives '<em class="bar quux"></em>'
471 * @endcode
472 *
473 * @param array $attribs Associative array of attributes, e.g., array(
474 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
475 * A value of false means to omit the attribute. For boolean attributes,
476 * you can omit the key, e.g., array( 'checked' ) instead of
477 * array( 'checked' => 'checked' ) or such.
478 *
479 * @throws MWException If an attribute that doesn't allow lists is set to an array
480 * @return string HTML fragment that goes between element name and '>'
481 * (starting with a space if at least one attribute is output)
482 */
483 public static function expandAttributes( array $attribs ) {
484 global $wgWellFormedXml;
485
486 $ret = '';
487 foreach ( $attribs as $key => $value ) {
488 // Support intuitive array( 'checked' => true/false ) form
489 if ( $value === false || is_null( $value ) ) {
490 continue;
491 }
492
493 // For boolean attributes, support array( 'foo' ) instead of
494 // requiring array( 'foo' => 'meaningless' ).
495 if ( is_int( $key ) && in_array( strtolower( $value ), self::$boolAttribs ) ) {
496 $key = $value;
497 }
498
499 // Not technically required in HTML5 but we'd like consistency
500 // and better compression anyway.
501 $key = strtolower( $key );
502
503 // Bug 23769: Blacklist all form validation attributes for now. Current
504 // (June 2010) WebKit has no UI, so the form just refuses to submit
505 // without telling the user why, which is much worse than failing
506 // server-side validation. Opera is the only other implementation at
507 // this time, and has ugly UI, so just kill the feature entirely until
508 // we have at least one good implementation.
509
510 // As the default value of "1" for "step" rejects decimal
511 // numbers to be entered in 'type="number"' fields, allow
512 // the special case 'step="any"'.
513
514 if ( in_array( $key, array( 'max', 'min', 'pattern', 'required' ) )
515 || $key === 'step' && $value !== 'any' ) {
516 continue;
517 }
518
519 // http://www.w3.org/TR/html401/index/attributes.html ("space-separated")
520 // http://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
521 $spaceSeparatedListAttributes = array(
522 'class', // html4, html5
523 'accesskey', // as of html5, multiple space-separated values allowed
524 // html4-spec doesn't document rel= as space-separated
525 // but has been used like that and is now documented as such
526 // in the html5-spec.
527 'rel',
528 );
529
530 // Specific features for attributes that allow a list of space-separated values
531 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
532 // Apply some normalization and remove duplicates
533
534 // Convert into correct array. Array can contain space-separated
535 // values. Implode/explode to get those into the main array as well.
536 if ( is_array( $value ) ) {
537 // If input wasn't an array, we can skip this step
538 $newValue = array();
539 foreach ( $value as $k => $v ) {
540 if ( is_string( $v ) ) {
541 // String values should be normal `array( 'foo' )`
542 // Just append them
543 if ( !isset( $value[$v] ) ) {
544 // As a special case don't set 'foo' if a
545 // separate 'foo' => true/false exists in the array
546 // keys should be authoritative
547 $newValue[] = $v;
548 }
549 } elseif ( $v ) {
550 // If the value is truthy but not a string this is likely
551 // an array( 'foo' => true ), falsy values don't add strings
552 $newValue[] = $k;
553 }
554 }
555 $value = implode( ' ', $newValue );
556 }
557 $value = explode( ' ', $value );
558
559 // Normalize spacing by fixing up cases where people used
560 // more than 1 space and/or a trailing/leading space
561 $value = array_diff( $value, array( '', ' ' ) );
562
563 // Remove duplicates and create the string
564 $value = implode( ' ', array_unique( $value ) );
565 } elseif ( is_array( $value ) ) {
566 throw new MWException( "HTML attribute $key can not contain a list of values" );
567 }
568
569 // See the "Attributes" section in the HTML syntax part of HTML5,
570 // 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
571 // marks omitted, but not all. (Although a literal " is not
572 // permitted, we don't check for that, since it will be escaped
573 // anyway.)
574
575 // See also research done on further characters that need to be
576 // escaped: http://code.google.com/p/html5lib/issues/detail?id=93
577 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
578 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
579 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
580 if ( $wgWellFormedXml || $value === '' || preg_match( "![$badChars]!u", $value ) ) {
581 $quote = '"';
582 } else {
583 $quote = '';
584 }
585
586 if ( in_array( $key, self::$boolAttribs ) ) {
587 // In HTML5, we can leave the value empty. If we don't need
588 // well-formed XML, we can omit the = entirely.
589 if ( !$wgWellFormedXml ) {
590 $ret .= " $key";
591 } else {
592 $ret .= " $key=\"\"";
593 }
594 } else {
595 // Apparently we need to entity-encode \n, \r, \t, although the
596 // spec doesn't mention that. Since we're doing strtr() anyway,
597 // we may as well not call htmlspecialchars().
598 // @todo FIXME: Verify that we actually need to
599 // escape \n\r\t here, and explain why, exactly.
600 // We could call Sanitizer::encodeAttribute() for this, but we
601 // don't because we're stubborn and like our marginal savings on
602 // byte size from not having to encode unnecessary quotes.
603 // The only difference between this transform and the one by
604 // Sanitizer::encodeAttribute() is '<' is only encoded here if
605 // $wgWellFormedXml is set, and ' is not encoded.
606 $map = array(
607 '&' => '&amp;',
608 '"' => '&quot;',
609 '>' => '&gt;',
610 "\n" => '&#10;',
611 "\r" => '&#13;',
612 "\t" => '&#9;'
613 );
614 if ( $wgWellFormedXml ) {
615 // This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
616 // But reportedly it breaks some XML tools?
617 // @todo FIXME: Is this really true?
618 $map['<'] = '&lt;';
619 }
620 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
621 }
622 }
623 return $ret;
624 }
625
626 /**
627 * Output a "<script>" tag with the given contents.
628 *
629 * @todo do some useful escaping as well, like if $contents contains
630 * literal "</script>" or (for XML) literal "]]>".
631 *
632 * @param string $contents JavaScript
633 * @return string Raw HTML
634 */
635 public static function inlineScript( $contents ) {
636 global $wgWellFormedXml;
637
638 $attrs = array();
639
640 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
641 $contents = "/*<![CDATA[*/$contents/*]]>*/";
642 }
643
644 return self::rawElement( 'script', $attrs, $contents );
645 }
646
647 /**
648 * Output a "<script>" tag linking to the given URL, e.g.,
649 * "<script src=foo.js></script>".
650 *
651 * @param string $url
652 * @return string Raw HTML
653 */
654 public static function linkedScript( $url ) {
655 $attrs = array( 'src' => $url );
656
657 return self::element( 'script', $attrs );
658 }
659
660 /**
661 * Output a "<style>" tag with the given contents for the given media type
662 * (if any). TODO: do some useful escaping as well, like if $contents
663 * contains literal "</style>" (admittedly unlikely).
664 *
665 * @param string $contents CSS
666 * @param string $media A media type string, like 'screen'
667 * @return string Raw HTML
668 */
669 public static function inlineStyle( $contents, $media = 'all' ) {
670 global $wgWellFormedXml;
671
672 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
673 $contents = "/*<![CDATA[*/$contents/*]]>*/";
674 }
675
676 return self::rawElement( 'style', array(
677 'type' => 'text/css',
678 'media' => $media,
679 ), $contents );
680 }
681
682 /**
683 * Output a "<link rel=stylesheet>" linking to the given URL for the given
684 * media type (if any).
685 *
686 * @param string $url
687 * @param string $media A media type string, like 'screen'
688 * @return string Raw HTML
689 */
690 public static function linkedStyle( $url, $media = 'all' ) {
691 return self::element( 'link', array(
692 'rel' => 'stylesheet',
693 'href' => $url,
694 'type' => 'text/css',
695 'media' => $media,
696 ) );
697 }
698
699 /**
700 * Convenience function to produce an "<input>" element. This supports the
701 * new HTML5 input types and attributes.
702 *
703 * @param string $name Name attribute
704 * @param string $value Value attribute
705 * @param string $type Type attribute
706 * @param array $attribs Associative array of miscellaneous extra
707 * attributes, passed to Html::element()
708 * @return string Raw HTML
709 */
710 public static function input( $name, $value = '', $type = 'text', array $attribs = array() ) {
711 $attribs['type'] = $type;
712 $attribs['value'] = $value;
713 $attribs['name'] = $name;
714 if ( in_array( $type, array( 'text', 'search', 'email', 'password', 'number' ) ) ) {
715 $attribs = self::getTextInputAttributes( $attribs );
716 }
717 if ( in_array( $type, array( 'button', 'reset', 'submit' ) ) ) {
718 $attribs = self::buttonAttributes( $attribs );
719 }
720 return self::element( 'input', $attribs );
721 }
722
723 /**
724 * Convenience function to produce a checkbox (input element with type=checkbox)
725 *
726 * @param string $name Name attribute
727 * @param bool $checked Whether the checkbox is checked or not
728 * @param array $attribs Array of additional attributes
729 * @return string Raw HTML
730 */
731 public static function check( $name, $checked = false, array $attribs = array() ) {
732 if ( isset( $attribs['value'] ) ) {
733 $value = $attribs['value'];
734 unset( $attribs['value'] );
735 } else {
736 $value = 1;
737 }
738
739 if ( $checked ) {
740 $attribs[] = 'checked';
741 }
742
743 return self::input( $name, $value, 'checkbox', $attribs );
744 }
745
746 /**
747 * Convenience function to produce a radio button (input element with type=radio)
748 *
749 * @param string $name Name attribute
750 * @param bool $checked Whether the radio button is checked or not
751 * @param array $attribs Array of additional attributes
752 * @return string Raw HTML
753 */
754 public static function radio( $name, $checked = false, array $attribs = array() ) {
755 if ( isset( $attribs['value'] ) ) {
756 $value = $attribs['value'];
757 unset( $attribs['value'] );
758 } else {
759 $value = 1;
760 }
761
762 if ( $checked ) {
763 $attribs[] = 'checked';
764 }
765
766 return self::input( $name, $value, 'radio', $attribs );
767 }
768
769 /**
770 * Convenience function for generating a label for inputs.
771 *
772 * @param string $label Contents of the label
773 * @param string $id ID of the element being labeled
774 * @param array $attribs Additional attributes
775 * @return string Raw HTML
776 */
777 public static function label( $label, $id, array $attribs = array() ) {
778 $attribs += array(
779 'for' => $id
780 );
781 return self::element( 'label', $attribs, $label );
782 }
783
784 /**
785 * Convenience function to produce an input element with type=hidden
786 *
787 * @param string $name Name attribute
788 * @param string $value Value attribute
789 * @param array $attribs Associative array of miscellaneous extra
790 * attributes, passed to Html::element()
791 * @return string Raw HTML
792 */
793 public static function hidden( $name, $value, array $attribs = array() ) {
794 return self::input( $name, $value, 'hidden', $attribs );
795 }
796
797 /**
798 * Convenience function to produce a <textarea> element.
799 *
800 * This supports leaving out the cols= and rows= which Xml requires and are
801 * required by HTML4/XHTML but not required by HTML5.
802 *
803 * @param string $name Name attribute
804 * @param string $value Value attribute
805 * @param array $attribs Associative array of miscellaneous extra
806 * attributes, passed to Html::element()
807 * @return string Raw HTML
808 */
809 public static function textarea( $name, $value = '', array $attribs = array() ) {
810 $attribs['name'] = $name;
811
812 if ( substr( $value, 0, 1 ) == "\n" ) {
813 // Workaround for bug 12130: browsers eat the initial newline
814 // assuming that it's just for show, but they do keep the later
815 // newlines, which we may want to preserve during editing.
816 // Prepending a single newline
817 $spacedValue = "\n" . $value;
818 } else {
819 $spacedValue = $value;
820 }
821 return self::element( 'textarea', self::getTextInputAttributes( $attribs ), $spacedValue );
822 }
823
824 /**
825 * Helper for Html::namespaceSelector().
826 * @param array $params See Html::namespaceSelector()
827 * @return array
828 */
829 public static function namespaceSelectorOptions( array $params = array() ) {
830 global $wgContLang;
831
832 $options = array();
833
834 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
835 $params['exclude'] = array();
836 }
837
838 if ( isset( $params['all'] ) ) {
839 // add an option that would let the user select all namespaces.
840 // Value is provided by user, the name shown is localized for the user.
841 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
842 }
843 // Add all namespaces as options (in the content language)
844 $options += $wgContLang->getFormattedNamespaces();
845
846 $optionsOut = array();
847 // Filter out namespaces below 0 and massage labels
848 foreach ( $options as $nsId => $nsName ) {
849 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
850 continue;
851 }
852 if ( $nsId === NS_MAIN ) {
853 // For other namespaces use the namespace prefix as label, but for
854 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
855 $nsName = wfMessage( 'blanknamespace' )->text();
856 } elseif ( is_int( $nsId ) ) {
857 $nsName = $wgContLang->convertNamespace( $nsId );
858 }
859 $optionsOut[$nsId] = $nsName;
860 }
861
862 return $optionsOut;
863 }
864
865 /**
866 * Build a drop-down box for selecting a namespace
867 *
868 * @param array $params Params to set.
869 * - selected: [optional] Id of namespace which should be pre-selected
870 * - all: [optional] Value of item for "all namespaces". If null or unset,
871 * no "<option>" is generated to select all namespaces.
872 * - label: text for label to add before the field.
873 * - exclude: [optional] Array of namespace ids to exclude.
874 * - disable: [optional] Array of namespace ids for which the option should
875 * be disabled in the selector.
876 * @param array $selectAttribs HTML attributes for the generated select element.
877 * - id: [optional], default: 'namespace'.
878 * - name: [optional], default: 'namespace'.
879 * @return string HTML code to select a namespace.
880 */
881 public static function namespaceSelector( array $params = array(),
882 array $selectAttribs = array()
883 ) {
884 ksort( $selectAttribs );
885
886 // Is a namespace selected?
887 if ( isset( $params['selected'] ) ) {
888 // If string only contains digits, convert to clean int. Selected could also
889 // be "all" or "" etc. which needs to be left untouched.
890 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
891 // and returns false for already clean ints. Use regex instead..
892 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
893 $params['selected'] = intval( $params['selected'] );
894 }
895 // else: leaves it untouched for later processing
896 } else {
897 $params['selected'] = '';
898 }
899
900 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
901 $params['disable'] = array();
902 }
903
904 // Associative array between option-values and option-labels
905 $options = self::namespaceSelectorOptions( $params );
906
907 // Convert $options to HTML
908 $optionsHtml = array();
909 foreach ( $options as $nsId => $nsName ) {
910 $optionsHtml[] = self::element(
911 'option', array(
912 'disabled' => in_array( $nsId, $params['disable'] ),
913 'value' => $nsId,
914 'selected' => $nsId === $params['selected'],
915 ), $nsName
916 );
917 }
918
919 if ( !array_key_exists( 'id', $selectAttribs ) ) {
920 $selectAttribs['id'] = 'namespace';
921 }
922
923 if ( !array_key_exists( 'name', $selectAttribs ) ) {
924 $selectAttribs['name'] = 'namespace';
925 }
926
927 $ret = '';
928 if ( isset( $params['label'] ) ) {
929 $ret .= self::element(
930 'label', array(
931 'for' => isset( $selectAttribs['id'] ) ? $selectAttribs['id'] : null,
932 ), $params['label']
933 ) . '&#160;';
934 }
935
936 // Wrap options in a <select>
937 $ret .= self::openElement( 'select', $selectAttribs )
938 . "\n"
939 . implode( "\n", $optionsHtml )
940 . "\n"
941 . self::closeElement( 'select' );
942
943 return $ret;
944 }
945
946 /**
947 * Constructs the opening html-tag with necessary doctypes depending on
948 * global variables.
949 *
950 * @param array $attribs Associative array of miscellaneous extra
951 * attributes, passed to Html::element() of html tag.
952 * @return string Raw HTML
953 */
954 public static function htmlHeader( array $attribs = array() ) {
955 $ret = '';
956
957 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
958
959 $isXHTML = self::isXmlMimeType( $wgMimeType );
960
961 if ( $isXHTML ) { // XHTML5
962 // XML MIME-typed markup should have an xml header.
963 // However a DOCTYPE is not needed.
964 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
965
966 // Add the standard xmlns
967 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
968
969 // And support custom namespaces
970 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
971 $attribs["xmlns:$tag"] = $ns;
972 }
973 } else { // HTML5
974 // DOCTYPE
975 $ret .= "<!DOCTYPE html>\n";
976 }
977
978 if ( $wgHtml5Version ) {
979 $attribs['version'] = $wgHtml5Version;
980 }
981
982 $html = self::openElement( 'html', $attribs );
983
984 if ( $html ) {
985 $html .= "\n";
986 }
987
988 $ret .= $html;
989
990 return $ret;
991 }
992
993 /**
994 * Determines if the given MIME type is xml.
995 *
996 * @param string $mimetype MIME type
997 * @return bool
998 */
999 public static function isXmlMimeType( $mimetype ) {
1000 # http://www.whatwg.org/html/infrastructure.html#xml-mime-type
1001 # * text/xml
1002 # * application/xml
1003 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
1004 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1005 }
1006
1007 /**
1008 * Get HTML for an info box with an icon.
1009 *
1010 * @param string $text Wikitext, get this with wfMessage()->plain()
1011 * @param string $icon Path to icon file (used as 'src' attribute)
1012 * @param string $alt Alternate text for the icon
1013 * @param string $class Additional class name to add to the wrapper div
1014 *
1015 * @return string
1016 */
1017 static function infoBox( $text, $icon, $alt, $class = '' ) {
1018 $s = self::openElement( 'div', array( 'class' => "mw-infobox $class" ) );
1019
1020 $s .= self::openElement( 'div', array( 'class' => 'mw-infobox-left' ) ) .
1021 self::element( 'img',
1022 array(
1023 'src' => $icon,
1024 'alt' => $alt,
1025 )
1026 ) .
1027 self::closeElement( 'div' );
1028
1029 $s .= self::openElement( 'div', array( 'class' => 'mw-infobox-right' ) ) .
1030 $text .
1031 self::closeElement( 'div' );
1032 $s .= self::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
1033
1034 $s .= self::closeElement( 'div' );
1035
1036 $s .= self::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
1037
1038 return $s;
1039 }
1040
1041 /**
1042 * Generate a srcset attribute value.
1043 *
1044 * Generates a srcset attribute value from an array mapping pixel densities
1045 * to URLs. A trailing 'x' in pixel density values is optional.
1046 *
1047 * @note srcset width and height values are not supported.
1048 *
1049 * @see http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
1050 *
1051 * @par Example:
1052 * @code
1053 * Html::srcSet( array(
1054 * '1x' => 'standard.jpeg',
1055 * '1.5x' => 'large.jpeg',
1056 * '3x' => 'extra-large.jpeg',
1057 * ) );
1058 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1059 * @endcode
1060 *
1061 * @param string[] $urls
1062 * @return string
1063 */
1064 static function srcSet( array $urls ) {
1065 $candidates = array();
1066 foreach ( $urls as $density => $url ) {
1067 // Cast density to float to strip 'x'.
1068 $candidates[] = $url . ' ' . (float)$density . 'x';
1069 }
1070 return implode( ", ", $candidates );
1071 }
1072 }