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