6a69b9c471c4d975d874c9955c648235f7a92f95
[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 # See the "Attributes" section in the HTML syntax part of HTML5,
374 # 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
375 # marks omitted, but not all. (Although a literal " is not
376 # permitted, we don't check for that, since it will be escaped
377 # anyway.)
378 #
379 # See also research done on further characters that need to be
380 # escaped: http://code.google.com/p/html5lib/issues/detail?id=93
381 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
382 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
383 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
384 if ( $wgWellFormedXml || $value === ''
385 || preg_match( "![$badChars]!u", $value ) ) {
386 $quote = '"';
387 } else {
388 $quote = '';
389 }
390
391 if ( in_array( $key, self::$boolAttribs ) ) {
392 # In XHTML 1.0 Transitional, the value needs to be equal to the
393 # key. In HTML5, we can leave the value empty instead. If we
394 # don't need well-formed XML, we can omit the = entirely.
395 if ( !$wgWellFormedXml ) {
396 $ret .= " $key";
397 } elseif ( $wgHtml5 ) {
398 $ret .= " $key=\"\"";
399 } else {
400 $ret .= " $key=\"$key\"";
401 }
402 } else {
403 # Apparently we need to entity-encode \n, \r, \t, although the
404 # spec doesn't mention that. Since we're doing strtr() anyway,
405 # and we don't need <> escaped here, we may as well not call
406 # htmlspecialchars(). FIXME: verify that we actually need to
407 # escape \n\r\t here, and explain why, exactly.
408 #
409 # We could call Sanitizer::encodeAttribute() for this, but we
410 # don't because we're stubborn and like our marginal savings on
411 # byte size from not having to encode unnecessary quotes.
412 $map = array(
413 '&' => '&amp;',
414 '"' => '&quot;',
415 "\n" => '&#10;',
416 "\r" => '&#13;',
417 "\t" => '&#9;'
418 );
419 if ( $wgWellFormedXml ) {
420 # This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
421 # But reportedly it breaks some XML tools? FIXME: is this
422 # really true?
423 $map['<'] = '&lt;';
424 }
425 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
426 }
427 }
428 return $ret;
429 }
430
431 /**
432 * Output a <script> tag with the given contents. TODO: do some useful
433 * escaping as well, like if $contents contains literal '</script>' or (for
434 * XML) literal "]]>".
435 *
436 * @param $contents string JavaScript
437 * @return string Raw HTML
438 */
439 public static function inlineScript( $contents ) {
440 global $wgHtml5, $wgJsMimeType, $wgWellFormedXml;
441
442 $attrs = array();
443 if ( !$wgHtml5 ) {
444 $attrs['type'] = $wgJsMimeType;
445 }
446 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
447 $contents = "/*<![CDATA[*/$contents/*]]>*/";
448 }
449 return self::rawElement( 'script', $attrs, $contents );
450 }
451
452 /**
453 * Output a <script> tag linking to the given URL, e.g.,
454 * <script src=foo.js></script>.
455 *
456 * @param $url string
457 * @return string Raw HTML
458 */
459 public static function linkedScript( $url ) {
460 global $wgHtml5, $wgJsMimeType;
461
462 $attrs = array( 'src' => $url );
463 if ( !$wgHtml5 ) {
464 $attrs['type'] = $wgJsMimeType;
465 }
466 return self::element( 'script', $attrs );
467 }
468
469 /**
470 * Output a <style> tag with the given contents for the given media type
471 * (if any). TODO: do some useful escaping as well, like if $contents
472 * contains literal '</style>' (admittedly unlikely).
473 *
474 * @param $contents string CSS
475 * @param $media mixed A media type string, like 'screen'
476 * @return string Raw HTML
477 */
478 public static function inlineStyle( $contents, $media = 'all' ) {
479 global $wgWellFormedXml;
480
481 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
482 $contents = "/*<![CDATA[*/$contents/*]]>*/";
483 }
484 return self::rawElement( 'style', array(
485 'type' => 'text/css',
486 'media' => $media,
487 ), $contents );
488 }
489
490 /**
491 * Output a <link rel=stylesheet> linking to the given URL for the given
492 * media type (if any).
493 *
494 * @param $url string
495 * @param $media mixed A media type string, like 'screen'
496 * @return string Raw HTML
497 */
498 public static function linkedStyle( $url, $media = 'all' ) {
499 return self::element( 'link', array(
500 'rel' => 'stylesheet',
501 'href' => $url,
502 'type' => 'text/css',
503 'media' => $media,
504 ) );
505 }
506
507 /**
508 * Convenience function to produce an <input> element. This supports the
509 * new HTML5 input types and attributes, and will silently strip them if
510 * $wgHtml5 is false.
511 *
512 * @param $name string name attribute
513 * @param $value mixed value attribute
514 * @param $type string type attribute
515 * @param $attribs array Associative array of miscellaneous extra
516 * attributes, passed to Html::element()
517 * @return string Raw HTML
518 */
519 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
520 $attribs['type'] = $type;
521 $attribs['value'] = $value;
522 $attribs['name'] = $name;
523
524 return self::element( 'input', $attribs );
525 }
526
527 /**
528 * Convenience function to produce an input element with type=hidden, like
529 * Xml::hidden.
530 *
531 * @param $name string name attribute
532 * @param $value string value attribute
533 * @param $attribs array Associative array of miscellaneous extra
534 * attributes, passed to Html::element()
535 * @return string Raw HTML
536 */
537 public static function hidden( $name, $value, $attribs = array() ) {
538 return self::input( $name, $value, 'hidden', $attribs );
539 }
540
541 /**
542 * Convenience function to produce an <input> element. This supports leaving
543 * out the cols= and rows= which Xml requires and are required by HTML4/XHTML
544 * but not required by HTML5 and will silently set cols="" and rows="" if
545 * $wgHtml5 is false and cols and rows are omitted (HTML4 validates present
546 * but empty cols="" and rows="" as valid).
547 *
548 * @param $name string name attribute
549 * @param $value string value 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 textarea( $name, $value = '', $attribs = array() ) {
555 global $wgHtml5;
556 $attribs['name'] = $name;
557 if ( !$wgHtml5 ) {
558 if ( !isset( $attribs['cols'] ) )
559 $attribs['cols'] = "";
560 if ( !isset( $attribs['rows'] ) )
561 $attribs['rows'] = "";
562 }
563 return self::element( 'textarea', $attribs, $value );
564 }
565
566 /**
567 * Constructs the opening html-tag with necessary doctypes depending on
568 * global variables.
569 *
570 * @param $attribs array Associative array of miscellaneous extra
571 * attributes, passed to Html::element() of html tag.
572 * @return string Raw HTML
573 */
574 public static function htmlHeader( $attribs = array() ) {
575 $ret = '';
576
577 global $wgMimeType, $wgOutputEncoding;
578 if ( self::isXmlMimeType( $wgMimeType ) ) {
579 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
580 }
581
582 global $wgHtml5, $wgHtml5Version, $wgWellFormedXml, $wgDocType, $wgDTD;
583 global $wgXhtmlNamespaces, $wgXhtmlDefaultNamespace;
584 if ( $wgHtml5 ) {
585 if ( $wgWellFormedXml ) {
586 # Unknown elements and attributes are okay in XML, but unknown
587 # named entities are well-formedness errors and will break XML
588 # parsers. Thus we need a doctype that gives us appropriate
589 # entity definitions. The HTML5 spec permits four legacy
590 # doctypes as obsolete but conforming, so let's pick one of
591 # those, although it makes our pages look like XHTML1 Strict.
592 # Isn't compatibility great?
593 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
594 } else {
595 # Much saner.
596 $ret .= "<!doctype html>\n";
597 }
598 if ( $wgHtml5Version ) {
599 $attribs['version'] = $wgHtml5Version;
600 }
601 } else {
602 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
603 $attribs['xmlns'] = $wgXhtmlDefaultNamespace;
604 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
605 $attribs["xmlns:$tag"] = $ns;
606 }
607 }
608 return $ret . Html::openElement( 'html', $attribs ) . "\n";
609 }
610
611 /**
612 * Determines if the given mime type is xml.
613 *
614 * @param $mimetype string MimeType
615 * @return Boolean
616 */
617 public static function isXmlMimeType( $mimetype ) {
618 switch ( $mimetype ) {
619 case 'text/xml':
620 case 'application/xhtml+xml':
621 case 'application/xml':
622 return true;
623 default:
624 return false;
625 }
626 }
627 }