(bug 23769) Disable HTML5 form validation for now
[lhc/web/wiklou.git] / includes / Html.php
1 <?php
2 # Copyright © 2009 Aryeh Gregor
3 # http://www.mediawiki.org/
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # http://www.gnu.org/copyleft/gpl.html
19
20 /**
21 * This class is a collection of static functions that serve two purposes:
22 *
23 * 1) Implement any algorithms specified by HTML5, or other HTML
24 * specifications, in a convenient and self-contained way.
25 *
26 * 2) Allow HTML elements to be conveniently and safely generated, like the
27 * current Xml class but a) less confused (Xml supports HTML-specific things,
28 * but only sometimes!) and b) not necessarily confined to XML-compatible
29 * output.
30 *
31 * There are two important configuration options this class uses:
32 *
33 * $wgHtml5: If this is set to false, then all output should be valid XHTML 1.0
34 * Transitional.
35 * $wgWellFormedXml: If this is set to true, then all output should be
36 * well-formed XML (quotes on attributes, self-closing tags, etc.).
37 *
38 * This class is meant to be confined to utility functions that are called from
39 * trusted code paths. It does not do enforcement of policy like not allowing
40 * <a> elements.
41 *
42 * @since 1.16
43 */
44 class Html {
45 # List of void elements from HTML5, section 9.1.2 as of 2009-08-10
46 private static $voidElements = array(
47 'area',
48 'base',
49 'br',
50 'col',
51 'command',
52 'embed',
53 'hr',
54 'img',
55 'input',
56 'keygen',
57 'link',
58 'meta',
59 'param',
60 'source',
61 );
62
63 # Boolean attributes, which may have the value omitted entirely. Manually
64 # collected from the HTML5 spec as of 2009-08-10.
65 private static $boolAttribs = array(
66 'async',
67 'autobuffer',
68 'autofocus',
69 'autoplay',
70 'checked',
71 'controls',
72 'defer',
73 'disabled',
74 'formnovalidate',
75 'hidden',
76 'ismap',
77 'loop',
78 'multiple',
79 'novalidate',
80 'open',
81 'readonly',
82 'required',
83 'reversed',
84 'scoped',
85 'seamless',
86 'selected',
87 );
88
89 /**
90 * Returns an HTML element in a string. The major advantage here over
91 * manually typing out the HTML is that it will escape all attribute
92 * values. If you're hardcoding all the attributes, or there are none, you
93 * should probably type out the string yourself.
94 *
95 * This is quite similar to Xml::tags(), but it implements some useful
96 * HTML-specific logic. For instance, there is no $allowShortTag
97 * parameter: the closing tag is magically omitted if $element has an empty
98 * content model. If $wgWellFormedXml is false, then a few bytes will be
99 * shaved off the HTML output as well. In the future, other HTML-specific
100 * features might be added, like allowing arrays for the values of
101 * attributes like class= and media=.
102 *
103 * @param $element string The element's name, e.g., 'a'
104 * @param $attribs array Associative array of attributes, e.g., array(
105 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
106 * further documentation.
107 * @param $contents string The raw HTML contents of the element: *not*
108 * escaped!
109 * @return string Raw HTML
110 */
111 public static function rawElement( $element, $attribs = array(), $contents = '' ) {
112 global $wgWellFormedXml;
113 $start = self::openElement( $element, $attribs );
114 if ( in_array( $element, self::$voidElements ) ) {
115 if ( $wgWellFormedXml ) {
116 # Silly XML.
117 return substr( $start, 0, -1 ) . ' />';
118 }
119 return $start;
120 } else {
121 return "$start$contents" . self::closeElement( $element );
122 }
123 }
124
125 /**
126 * Identical to rawElement(), but HTML-escapes $contents (like
127 * Xml::element()).
128 */
129 public static function element( $element, $attribs = array(), $contents = '' ) {
130 return self::rawElement( $element, $attribs, strtr( $contents, array(
131 # There's no point in escaping quotes, >, etc. in the contents of
132 # elements.
133 '&' => '&amp;',
134 '<' => '&lt;'
135 ) ) );
136 }
137
138 /**
139 * Identical to rawElement(), but has no third parameter and omits the end
140 * tag (and the self-closing '/' in XML mode for empty elements).
141 */
142 public static function openElement( $element, $attribs = array() ) {
143 global $wgHtml5, $wgWellFormedXml;
144 $attribs = (array)$attribs;
145 # This is not required in HTML5, but let's do it anyway, for
146 # consistency and better compression.
147 $element = strtolower( $element );
148
149 # In text/html, initial <html> and <head> tags can be omitted under
150 # pretty much any sane circumstances, if they have no attributes. See:
151 # <http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags>
152 if ( !$wgWellFormedXml && !$attribs
153 && in_array( $element, array( 'html', 'head' ) ) ) {
154 return '';
155 }
156
157 # Remove HTML5-only attributes if we aren't doing HTML5
158 if ( !$wgHtml5 ) {
159 if ( $element == 'input' ) {
160 # Whitelist of valid XHTML1 types
161 $validTypes = array(
162 'hidden',
163 'text',
164 'password',
165 'checkbox',
166 'radio',
167 'file',
168 'submit',
169 'image',
170 'reset',
171 'button',
172 );
173 if ( isset( $attribs['type'] )
174 && !in_array( $attribs['type'], $validTypes ) ) {
175 # Fall back to type=text, the default
176 unset( $attribs['type'] );
177 }
178 }
179 if ( $element == 'textarea' && isset( $attribs['maxlength'] ) ) {
180 unset( $attribs['maxlength'] );
181 }
182 # Here we're blacklisting some HTML5-only attributes...
183 $html5attribs = array(
184 'autocomplete',
185 'autofocus',
186 'max',
187 'min',
188 'multiple',
189 'pattern',
190 'placeholder',
191 'required',
192 'step',
193 'spellcheck',
194 );
195 foreach ( $html5attribs as $badAttr ) {
196 unset( $attribs[$badAttr] );
197 }
198 }
199
200 return "<$element" . self::expandAttributes(
201 self::dropDefaults( $element, $attribs ) ) . '>';
202 }
203
204 /**
205 * Returns "</$element>", except if $wgWellFormedXml is off, in which case
206 * it returns the empty string when that's guaranteed to be safe.
207 *
208 * @param $element string Name of the element, e.g., 'a'
209 * @return string A closing tag, if required
210 */
211 public static function closeElement( $element ) {
212 global $wgWellFormedXml;
213
214 $element = strtolower( $element );
215
216 # Reference:
217 # http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags
218 if ( !$wgWellFormedXml && in_array( $element, array(
219 'html',
220 'head',
221 'body',
222 'li',
223 'dt',
224 'dd',
225 'tr',
226 'td',
227 'th',
228 ) ) ) {
229 return '';
230 }
231 return "</$element>";
232 }
233
234 /**
235 * Given an element name and an associative array of element attributes,
236 * return an array that is functionally identical to the input array, but
237 * possibly smaller. In particular, attributes might be stripped if they
238 * are given their default values.
239 *
240 * This method is not guaranteed to remove all redundant attributes, only
241 * some common ones and some others selected arbitrarily at random. It
242 * only guarantees that the output array should be functionally identical
243 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
244 *
245 * @param $element string Name of the element, e.g., 'a'
246 * @param $attribs array Associative array of attributes, e.g., array(
247 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
248 * further documentation.
249 * @return array An array of attributes functionally identical to $attribs
250 */
251 private static function dropDefaults( $element, $attribs ) {
252 # Don't bother doing anything if we aren't outputting HTML5; it's too
253 # much of a pain to maintain two sets of defaults.
254 global $wgHtml5;
255 if ( !$wgHtml5 ) {
256 return $attribs;
257 }
258
259 static $attribDefaults = array(
260 'area' => array( 'shape' => 'rect' ),
261 'button' => array(
262 'formaction' => 'GET',
263 'formenctype' => 'application/x-www-form-urlencoded',
264 'type' => 'submit',
265 ),
266 'canvas' => array(
267 'height' => '150',
268 'width' => '300',
269 ),
270 'command' => array( 'type' => 'command' ),
271 'form' => array(
272 'action' => 'GET',
273 'autocomplete' => 'on',
274 'enctype' => 'application/x-www-form-urlencoded',
275 ),
276 'input' => array(
277 'formaction' => 'GET',
278 'type' => 'text',
279 'value' => '',
280 ),
281 'keygen' => array( 'keytype' => 'rsa' ),
282 'link' => array( 'media' => 'all' ),
283 'menu' => array( 'type' => 'list' ),
284 # Note: the use of text/javascript here instead of other JavaScript
285 # MIME types follows the HTML5 spec.
286 'script' => array( 'type' => 'text/javascript' ),
287 'style' => array(
288 'media' => 'all',
289 'type' => 'text/css',
290 ),
291 'textarea' => array( 'wrap' => 'soft' ),
292 );
293
294 $element = strtolower( $element );
295
296 foreach ( $attribs as $attrib => $value ) {
297 $lcattrib = strtolower( $attrib );
298 $value = strval( $value );
299
300 # Simple checks using $attribDefaults
301 if ( isset( $attribDefaults[$element][$lcattrib] ) &&
302 $attribDefaults[$element][$lcattrib] == $value ) {
303 unset( $attribs[$attrib] );
304 }
305
306 if ( $lcattrib == 'class' && $value == '' ) {
307 unset( $attribs[$attrib] );
308 }
309 }
310
311 # More subtle checks
312 if ( $element === 'link' && isset( $attribs['type'] )
313 && strval( $attribs['type'] ) == 'text/css' ) {
314 unset( $attribs['type'] );
315 }
316 if ( $element === 'select' && isset( $attribs['size'] ) ) {
317 if ( in_array( 'multiple', $attribs )
318 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
319 ) {
320 # A multi-select
321 if ( strval( $attribs['size'] ) == '4' ) {
322 unset( $attribs['size'] );
323 }
324 } else {
325 # Single select
326 if ( strval( $attribs['size'] ) == '1' ) {
327 unset( $attribs['size'] );
328 }
329 }
330 }
331
332 return $attribs;
333 }
334
335 /**
336 * Given an associative array of element attributes, generate a string
337 * to stick after the element name in HTML output. Like array( 'href' =>
338 * 'http://www.mediawiki.org/' ) becomes something like
339 * ' href="http://www.mediawiki.org"'. Again, this is like
340 * Xml::expandAttributes(), but it implements some HTML-specific logic.
341 * For instance, it will omit quotation marks if $wgWellFormedXml is false,
342 * and will treat boolean attributes specially.
343 *
344 * @param $attribs array Associative array of attributes, e.g., array(
345 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
346 * A value of false means to omit the attribute. For boolean attributes,
347 * you can omit the key, e.g., array( 'checked' ) instead of
348 * array( 'checked' => 'checked' ) or such.
349 * @return string HTML fragment that goes between element name and '>'
350 * (starting with a space if at least one attribute is output)
351 */
352 public static function expandAttributes( $attribs ) {
353 global $wgHtml5, $wgWellFormedXml;
354
355 $ret = '';
356 $attribs = (array)$attribs;
357 foreach ( $attribs as $key => $value ) {
358 if ( $value === false ) {
359 continue;
360 }
361
362 # For boolean attributes, support array( 'foo' ) instead of
363 # requiring array( 'foo' => 'meaningless' ).
364 if ( is_int( $key )
365 && in_array( strtolower( $value ), self::$boolAttribs ) ) {
366 $key = $value;
367 }
368
369 # Not technically required in HTML5, but required in XHTML 1.0,
370 # and we'd like consistency and better compression anyway.
371 $key = strtolower( $key );
372
373 # Bug 23769: Blacklist all form validation attributes for now. Current
374 # (June 2010) WebKit has no UI, so the form just refuses to submit
375 # without telling the user why, which is much worse than failing
376 # server-side validation. Opera is the only other implementation at
377 # this time, and has ugly UI, so just kill the feature entirely until
378 # we have at least one good implementation.
379 if ( in_array( $key, array( 'max', 'min', 'pattern', 'required', 'step' ) ) ) {
380 continue;
381 }
382
383 # See the "Attributes" section in the HTML syntax part of HTML5,
384 # 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
385 # marks omitted, but not all. (Although a literal " is not
386 # permitted, we don't check for that, since it will be escaped
387 # anyway.)
388 #
389 # See also research done on further characters that need to be
390 # escaped: http://code.google.com/p/html5lib/issues/detail?id=93
391 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
392 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
393 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
394 if ( $wgWellFormedXml || $value === ''
395 || preg_match( "![$badChars]!u", $value ) ) {
396 $quote = '"';
397 } else {
398 $quote = '';
399 }
400
401 if ( in_array( $key, self::$boolAttribs ) ) {
402 # In XHTML 1.0 Transitional, the value needs to be equal to the
403 # key. In HTML5, we can leave the value empty instead. If we
404 # don't need well-formed XML, we can omit the = entirely.
405 if ( !$wgWellFormedXml ) {
406 $ret .= " $key";
407 } elseif ( $wgHtml5 ) {
408 $ret .= " $key=\"\"";
409 } else {
410 $ret .= " $key=\"$key\"";
411 }
412 } else {
413 # Apparently we need to entity-encode \n, \r, \t, although the
414 # spec doesn't mention that. Since we're doing strtr() anyway,
415 # and we don't need <> escaped here, we may as well not call
416 # htmlspecialchars(). FIXME: verify that we actually need to
417 # escape \n\r\t here, and explain why, exactly.
418 #
419 # We could call Sanitizer::encodeAttribute() for this, but we
420 # don't because we're stubborn and like our marginal savings on
421 # byte size from not having to encode unnecessary quotes.
422 $map = array(
423 '&' => '&amp;',
424 '"' => '&quot;',
425 "\n" => '&#10;',
426 "\r" => '&#13;',
427 "\t" => '&#9;'
428 );
429 if ( $wgWellFormedXml ) {
430 # This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
431 # But reportedly it breaks some XML tools? FIXME: is this
432 # really true?
433 $map['<'] = '&lt;';
434 }
435 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
436 }
437 }
438 return $ret;
439 }
440
441 /**
442 * Output a <script> tag with the given contents. TODO: do some useful
443 * escaping as well, like if $contents contains literal '</script>' or (for
444 * XML) literal "]]>".
445 *
446 * @param $contents string JavaScript
447 * @return string Raw HTML
448 */
449 public static function inlineScript( $contents ) {
450 global $wgHtml5, $wgJsMimeType, $wgWellFormedXml;
451
452 $attrs = array();
453 if ( !$wgHtml5 ) {
454 $attrs['type'] = $wgJsMimeType;
455 }
456 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
457 $contents = "/*<![CDATA[*/$contents/*]]>*/";
458 }
459 return self::rawElement( 'script', $attrs, $contents );
460 }
461
462 /**
463 * Output a <script> tag linking to the given URL, e.g.,
464 * <script src=foo.js></script>.
465 *
466 * @param $url string
467 * @return string Raw HTML
468 */
469 public static function linkedScript( $url ) {
470 global $wgHtml5, $wgJsMimeType;
471
472 $attrs = array( 'src' => $url );
473 if ( !$wgHtml5 ) {
474 $attrs['type'] = $wgJsMimeType;
475 }
476 return self::element( 'script', $attrs );
477 }
478
479 /**
480 * Output a <style> tag with the given contents for the given media type
481 * (if any). TODO: do some useful escaping as well, like if $contents
482 * contains literal '</style>' (admittedly unlikely).
483 *
484 * @param $contents string CSS
485 * @param $media mixed A media type string, like 'screen'
486 * @return string Raw HTML
487 */
488 public static function inlineStyle( $contents, $media = 'all' ) {
489 global $wgWellFormedXml;
490
491 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
492 $contents = "/*<![CDATA[*/$contents/*]]>*/";
493 }
494 return self::rawElement( 'style', array(
495 'type' => 'text/css',
496 'media' => $media,
497 ), $contents );
498 }
499
500 /**
501 * Output a <link rel=stylesheet> linking to the given URL for the given
502 * media type (if any).
503 *
504 * @param $url string
505 * @param $media mixed A media type string, like 'screen'
506 * @return string Raw HTML
507 */
508 public static function linkedStyle( $url, $media = 'all' ) {
509 return self::element( 'link', array(
510 'rel' => 'stylesheet',
511 'href' => $url,
512 'type' => 'text/css',
513 'media' => $media,
514 ) );
515 }
516
517 /**
518 * Convenience function to produce an <input> element. This supports the
519 * new HTML5 input types and attributes, and will silently strip them if
520 * $wgHtml5 is false.
521 *
522 * @param $name string name attribute
523 * @param $value mixed value attribute
524 * @param $type string type attribute
525 * @param $attribs array Associative array of miscellaneous extra
526 * attributes, passed to Html::element()
527 * @return string Raw HTML
528 */
529 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
530 $attribs['type'] = $type;
531 $attribs['value'] = $value;
532 $attribs['name'] = $name;
533
534 return self::element( 'input', $attribs );
535 }
536
537 /**
538 * Convenience function to produce an input element with type=hidden, like
539 * Xml::hidden.
540 *
541 * @param $name string name attribute
542 * @param $value string value attribute
543 * @param $attribs array Associative array of miscellaneous extra
544 * attributes, passed to Html::element()
545 * @return string Raw HTML
546 */
547 public static function hidden( $name, $value, $attribs = array() ) {
548 return self::input( $name, $value, 'hidden', $attribs );
549 }
550
551 /**
552 * Convenience function to produce an <input> element. This supports leaving
553 * out the cols= and rows= which Xml requires and are required by HTML4/XHTML
554 * but not required by HTML5 and will silently set cols="" and rows="" if
555 * $wgHtml5 is false and cols and rows are omitted (HTML4 validates present
556 * but empty cols="" and rows="" as valid).
557 *
558 * @param $name string name attribute
559 * @param $value string value attribute
560 * @param $attribs array Associative array of miscellaneous extra
561 * attributes, passed to Html::element()
562 * @return string Raw HTML
563 */
564 public static function textarea( $name, $value = '', $attribs = array() ) {
565 global $wgHtml5;
566 $attribs['name'] = $name;
567 if ( !$wgHtml5 ) {
568 if ( !isset( $attribs['cols'] ) )
569 $attribs['cols'] = "";
570 if ( !isset( $attribs['rows'] ) )
571 $attribs['rows'] = "";
572 }
573 return self::element( 'textarea', $attribs, $value );
574 }
575
576 /**
577 * Constructs the opening html-tag with necessary doctypes depending on
578 * global variables.
579 *
580 * @param $attribs array Associative array of miscellaneous extra
581 * attributes, passed to Html::element() of html tag.
582 * @return string Raw HTML
583 */
584 public static function htmlHeader( $attribs = array() ) {
585 $ret = '';
586
587 global $wgMimeType, $wgOutputEncoding;
588 if ( self::isXmlMimeType( $wgMimeType ) ) {
589 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
590 }
591
592 global $wgHtml5, $wgHtml5Version, $wgWellFormedXml, $wgDocType, $wgDTD;
593 global $wgXhtmlNamespaces, $wgXhtmlDefaultNamespace;
594 if ( $wgHtml5 ) {
595 if ( $wgWellFormedXml ) {
596 # Unknown elements and attributes are okay in XML, but unknown
597 # named entities are well-formedness errors and will break XML
598 # parsers. Thus we need a doctype that gives us appropriate
599 # entity definitions. The HTML5 spec permits four legacy
600 # doctypes as obsolete but conforming, so let's pick one of
601 # those, although it makes our pages look like XHTML1 Strict.
602 # Isn't compatibility great?
603 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
604 } else {
605 # Much saner.
606 $ret .= "<!doctype html>\n";
607 }
608 if ( $wgHtml5Version ) {
609 $attribs['version'] = $wgHtml5Version;
610 }
611 } else {
612 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
613 $attribs['xmlns'] = $wgXhtmlDefaultNamespace;
614 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
615 $attribs["xmlns:$tag"] = $ns;
616 }
617 }
618 return $ret . Html::openElement( 'html', $attribs ) . "\n";
619 }
620
621 /**
622 * Determines if the given mime type is xml.
623 *
624 * @param $mimetype string MimeType
625 * @return Boolean
626 */
627 public static function isXmlMimeType( $mimetype ) {
628 switch ( $mimetype ) {
629 case 'text/xml':
630 case 'application/xhtml+xml':
631 case 'application/xml':
632 return true;
633 default:
634 return false;
635 }
636 }
637 }