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