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