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