Kill off the long deprecated $wgInputEncoding and $wgOutputEncoding globals
[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(). FIXME: verify that we actually need to
441 # escape \n\r\t here, and explain why, exactly.
442 #
443 # We could call Sanitizer::encodeAttribute() for this, but we
444 # don't because we're stubborn and like our marginal savings on
445 # byte size from not having to encode unnecessary quotes.
446 $map = array(
447 '&' => '&amp;',
448 '"' => '&quot;',
449 "\n" => '&#10;',
450 "\r" => '&#13;',
451 "\t" => '&#9;'
452 );
453 if ( $wgWellFormedXml ) {
454 # This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
455 # But reportedly it breaks some XML tools? FIXME: is this
456 # really true?
457 $map['<'] = '&lt;';
458 }
459 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
460 }
461 }
462 return $ret;
463 }
464
465 /**
466 * Output a <script> tag with the given contents. TODO: do some useful
467 * escaping as well, like if $contents contains literal '</script>' or (for
468 * XML) literal "]]>".
469 *
470 * @param $contents string JavaScript
471 * @return string Raw HTML
472 */
473 public static function inlineScript( $contents ) {
474 global $wgHtml5, $wgJsMimeType, $wgWellFormedXml;
475
476 $attrs = array();
477 if ( !$wgHtml5 ) {
478 $attrs['type'] = $wgJsMimeType;
479 }
480 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
481 $contents = "/*<![CDATA[*/$contents/*]]>*/";
482 }
483 return self::rawElement( 'script', $attrs, $contents );
484 }
485
486 /**
487 * Output a <script> tag linking to the given URL, e.g.,
488 * <script src=foo.js></script>.
489 *
490 * @param $url string
491 * @return string Raw HTML
492 */
493 public static function linkedScript( $url ) {
494 global $wgHtml5, $wgJsMimeType;
495
496 $attrs = array( 'src' => $url );
497 if ( !$wgHtml5 ) {
498 $attrs['type'] = $wgJsMimeType;
499 }
500 return self::element( 'script', $attrs );
501 }
502
503 /**
504 * Output a <style> tag with the given contents for the given media type
505 * (if any). TODO: do some useful escaping as well, like if $contents
506 * contains literal '</style>' (admittedly unlikely).
507 *
508 * @param $contents string CSS
509 * @param $media mixed A media type string, like 'screen'
510 * @return string Raw HTML
511 */
512 public static function inlineStyle( $contents, $media = 'all' ) {
513 global $wgWellFormedXml;
514
515 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
516 $contents = "/*<![CDATA[*/$contents/*]]>*/";
517 }
518 return self::rawElement( 'style', array(
519 'type' => 'text/css',
520 'media' => $media,
521 ), $contents );
522 }
523
524 /**
525 * Output a <link rel=stylesheet> linking to the given URL for the given
526 * media type (if any).
527 *
528 * @param $url string
529 * @param $media mixed A media type string, like 'screen'
530 * @return string Raw HTML
531 */
532 public static function linkedStyle( $url, $media = 'all' ) {
533 return self::element( 'link', array(
534 'rel' => 'stylesheet',
535 'href' => $url,
536 'type' => 'text/css',
537 'media' => $media,
538 ) );
539 }
540
541 /**
542 * Convenience function to produce an <input> element. This supports the
543 * new HTML5 input types and attributes, and will silently strip them if
544 * $wgHtml5 is false.
545 *
546 * @param $name string name attribute
547 * @param $value mixed value attribute
548 * @param $type string type attribute
549 * @param $attribs array Associative array of miscellaneous extra
550 * attributes, passed to Html::element()
551 * @return string Raw HTML
552 */
553 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
554 $attribs['type'] = $type;
555 $attribs['value'] = $value;
556 $attribs['name'] = $name;
557
558 return self::element( 'input', $attribs );
559 }
560
561 /**
562 * Convenience function to produce an input element with type=hidden
563 *
564 * @param $name string name attribute
565 * @param $value string value attribute
566 * @param $attribs array Associative array of miscellaneous extra
567 * attributes, passed to Html::element()
568 * @return string Raw HTML
569 */
570 public static function hidden( $name, $value, $attribs = array() ) {
571 return self::input( $name, $value, 'hidden', $attribs );
572 }
573
574 /**
575 * Convenience function to produce an <input> element. This supports leaving
576 * out the cols= and rows= which Xml requires and are required by HTML4/XHTML
577 * but not required by HTML5 and will silently set cols="" and rows="" if
578 * $wgHtml5 is false and cols and rows are omitted (HTML4 validates present
579 * but empty cols="" and rows="" as valid).
580 *
581 * @param $name string name attribute
582 * @param $value string value attribute
583 * @param $attribs array Associative array of miscellaneous extra
584 * attributes, passed to Html::element()
585 * @return string Raw HTML
586 */
587 public static function textarea( $name, $value = '', $attribs = array() ) {
588 global $wgHtml5;
589 $attribs['name'] = $name;
590 if ( !$wgHtml5 ) {
591 if ( !isset( $attribs['cols'] ) ) {
592 $attribs['cols'] = "";
593 }
594 if ( !isset( $attribs['rows'] ) ) {
595 $attribs['rows'] = "";
596 }
597 }
598 return self::element( 'textarea', $attribs, $value );
599 }
600
601 /**
602 * Constructs the opening html-tag with necessary doctypes depending on
603 * global variables.
604 *
605 * @param $attribs array Associative array of miscellaneous extra
606 * attributes, passed to Html::element() of html tag.
607 * @return string Raw HTML
608 */
609 public static function htmlHeader( $attribs = array() ) {
610 $ret = '';
611
612 global $wgMimeType;
613 if ( self::isXmlMimeType( $wgMimeType ) ) {
614 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
615 }
616
617 global $wgHtml5, $wgHtml5Version, $wgDocType, $wgDTD;
618 global $wgXhtmlNamespaces, $wgXhtmlDefaultNamespace;
619 if ( $wgHtml5 ) {
620 $ret .= "<!DOCTYPE html>\n";
621 if ( $wgHtml5Version ) {
622 $attribs['version'] = $wgHtml5Version;
623 }
624 } else {
625 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
626 $attribs['xmlns'] = $wgXhtmlDefaultNamespace;
627 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
628 $attribs["xmlns:$tag"] = $ns;
629 }
630 }
631 $html = Html::openElement( 'html', $attribs );
632 if ( $html ) {
633 $html .= "\n";
634 }
635 $ret .= $html;
636 return $ret;
637 }
638
639 /**
640 * Determines if the given mime type is xml.
641 *
642 * @param $mimetype string MimeType
643 * @return Boolean
644 */
645 public static function isXmlMimeType( $mimetype ) {
646 switch ( $mimetype ) {
647 case 'text/xml':
648 case 'application/xhtml+xml':
649 case 'application/xml':
650 return true;
651 default:
652 return false;
653 }
654 }
655 }