2 # Copyright © 2009 Aryeh Gregor
3 # http://www.mediawiki.org/
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.
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.
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
21 * This class is a collection of static functions that serve two purposes:
23 * 1) Implement any algorithms specified by HTML5, or other HTML
24 * specifications, in a convenient and self-contained way.
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
31 * There are two important configuration options this class uses:
33 * $wgHtml5: If this is set to false, then all output should be valid XHTML 1.0
35 * $wgWellFormedXml: If this is set to true, then all output should be
36 * well-formed XML (quotes on attributes, self-closing tags, etc.).
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
45 # List of void elements from HTML5, section 9.1.2 as of 2009-08-10
46 private static $voidElements = array(
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(
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.
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=.
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*
109 * @return string Raw HTML
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 ) {
117 return substr( $start, 0, -1 ) . ' />';
121 return "$start$contents" . self
::closeElement( $element );
126 * Identical to rawElement(), but HTML-escapes $contents (like
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
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).
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 );
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' ) ) ) {
157 # Remove HTML5-only attributes if we aren't doing HTML5
159 if ( $element == 'input' ) {
160 # Whitelist of valid XHTML1 types
173 if ( isset( $attribs['type'] )
174 && !in_array( $attribs['type'], $validTypes ) ) {
175 # Fall back to type=text, the default
176 unset( $attribs['type'] );
179 if ( $element == 'textarea' && isset( $attribs['maxlength'] ) ) {
180 unset( $attribs['maxlength'] );
182 # Here we're blacklisting some HTML5-only attributes...
183 $html5attribs = array(
195 foreach ( $html5attribs as $badAttr ) {
196 unset( $attribs[$badAttr] );
200 return "<$element" . self
::expandAttributes(
201 self
::dropDefaults( $element, $attribs ) ) . '>';
205 * Returns "</$element>", except if $wgWellFormedXml is off, in which case
206 * it returns the empty string when that's guaranteed to be safe.
208 * @param $element string Name of the element, e.g., 'a'
209 * @return string A closing tag, if required
211 public static function closeElement( $element ) {
212 global $wgWellFormedXml;
214 $element = strtolower( $element );
217 # http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags
218 if ( !$wgWellFormedXml && in_array( $element, array(
231 return "</$element>";
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.
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).
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
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.
259 static $attribDefaults = array(
260 'area' => array( 'shape' => 'rect' ),
262 'formaction' => 'GET',
263 'formenctype' => 'application/x-www-form-urlencoded',
270 'command' => array( 'type' => 'command' ),
273 'autocomplete' => 'on',
274 'enctype' => 'application/x-www-form-urlencoded',
277 'formaction' => 'GET',
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' ),
289 'type' => 'text/css',
291 'textarea' => array( 'wrap' => 'soft' ),
294 $element = strtolower( $element );
296 foreach ( $attribs as $attrib => $value ) {
297 $lcattrib = strtolower( $attrib );
298 $value = strval( $value );
300 # Simple checks using $attribDefaults
301 if ( isset( $attribDefaults[$element][$lcattrib] ) &&
302 $attribDefaults[$element][$lcattrib] == $value ) {
303 unset( $attribs[$attrib] );
306 if ( $lcattrib == 'class' && $value == '' ) {
307 unset( $attribs[$attrib] );
312 if ( $element === 'link' && isset( $attribs['type'] )
313 && strval( $attribs['type'] ) == 'text/css' ) {
314 unset( $attribs['type'] );
316 if ( $element === 'select' && isset( $attribs['size'] ) ) {
317 if ( in_array( 'multiple', $attribs )
318 ||
( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
321 if ( strval( $attribs['size'] ) == '4' ) {
322 unset( $attribs['size'] );
326 if ( strval( $attribs['size'] ) == '1' ) {
327 unset( $attribs['size'] );
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.
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)
352 public static function expandAttributes( $attribs ) {
353 global $wgHtml5, $wgWellFormedXml;
356 $attribs = (array)$attribs;
357 foreach ( $attribs as $key => $value ) {
358 if ( $value === false ) {
362 # For boolean attributes, support array( 'foo' ) instead of
363 # requiring array( 'foo' => 'meaningless' ).
365 && in_array( strtolower( $value ), self
::$boolAttribs ) ) {
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 );
373 # Bug 23769: Blacklist all form validation attributes for now. Current
374 # (June 2010) WebKit has no UI, so the form just refuses to submit
375 # without telling the user why, which is much worse than failing
376 # server-side validation. Opera is the only other implementation at
377 # this time, and has ugly UI, so just kill the feature entirely until
378 # we have at least one good implementation.
379 if ( in_array( $key, array( 'max', 'min', 'pattern', 'required', 'step' ) ) ) {
383 # See the "Attributes" section in the HTML syntax part of HTML5,
384 # 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
385 # marks omitted, but not all. (Although a literal " is not
386 # permitted, we don't check for that, since it will be escaped
389 # See also research done on further characters that need to be
390 # escaped: http://code.google.com/p/html5lib/issues/detail?id=93
391 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
392 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
393 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
394 if ( $wgWellFormedXml ||
$value === ''
395 ||
preg_match( "![$badChars]!u", $value ) ) {
401 if ( in_array( $key, self
::$boolAttribs ) ) {
402 # In XHTML 1.0 Transitional, the value needs to be equal to the
403 # key. In HTML5, we can leave the value empty instead. If we
404 # don't need well-formed XML, we can omit the = entirely.
405 if ( !$wgWellFormedXml ) {
407 } elseif ( $wgHtml5 ) {
408 $ret .= " $key=\"\"";
410 $ret .= " $key=\"$key\"";
413 # Apparently we need to entity-encode \n, \r, \t, although the
414 # spec doesn't mention that. Since we're doing strtr() anyway,
415 # and we don't need <> escaped here, we may as well not call
416 # htmlspecialchars(). FIXME: verify that we actually need to
417 # escape \n\r\t here, and explain why, exactly.
419 # We could call Sanitizer::encodeAttribute() for this, but we
420 # don't because we're stubborn and like our marginal savings on
421 # byte size from not having to encode unnecessary quotes.
429 if ( $wgWellFormedXml ) {
430 # This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
431 # But reportedly it breaks some XML tools? FIXME: is this
435 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
442 * Output a <script> tag with the given contents. TODO: do some useful
443 * escaping as well, like if $contents contains literal '</script>' or (for
444 * XML) literal "]]>".
446 * @param $contents string JavaScript
447 * @return string Raw HTML
449 public static function inlineScript( $contents ) {
450 global $wgHtml5, $wgJsMimeType, $wgWellFormedXml;
454 $attrs['type'] = $wgJsMimeType;
456 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
457 $contents = "/*<![CDATA[*/$contents/*]]>*/";
459 return self
::rawElement( 'script', $attrs, $contents );
463 * Output a <script> tag linking to the given URL, e.g.,
464 * <script src=foo.js></script>.
467 * @return string Raw HTML
469 public static function linkedScript( $url ) {
470 global $wgHtml5, $wgJsMimeType;
472 $attrs = array( 'src' => $url );
474 $attrs['type'] = $wgJsMimeType;
476 return self
::element( 'script', $attrs );
480 * Output a <style> tag with the given contents for the given media type
481 * (if any). TODO: do some useful escaping as well, like if $contents
482 * contains literal '</style>' (admittedly unlikely).
484 * @param $contents string CSS
485 * @param $media mixed A media type string, like 'screen'
486 * @return string Raw HTML
488 public static function inlineStyle( $contents, $media = 'all' ) {
489 global $wgWellFormedXml;
491 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
492 $contents = "/*<![CDATA[*/$contents/*]]>*/";
494 return self
::rawElement( 'style', array(
495 'type' => 'text/css',
501 * Output a <link rel=stylesheet> linking to the given URL for the given
502 * media type (if any).
505 * @param $media mixed A media type string, like 'screen'
506 * @return string Raw HTML
508 public static function linkedStyle( $url, $media = 'all' ) {
509 return self
::element( 'link', array(
510 'rel' => 'stylesheet',
512 'type' => 'text/css',
518 * Convenience function to produce an <input> element. This supports the
519 * new HTML5 input types and attributes, and will silently strip them if
522 * @param $name string name attribute
523 * @param $value mixed value attribute
524 * @param $type string type attribute
525 * @param $attribs array Associative array of miscellaneous extra
526 * attributes, passed to Html::element()
527 * @return string Raw HTML
529 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
530 $attribs['type'] = $type;
531 $attribs['value'] = $value;
532 $attribs['name'] = $name;
534 return self
::element( 'input', $attribs );
538 * Convenience function to produce an input element with type=hidden, like
541 * @param $name string name attribute
542 * @param $value string value attribute
543 * @param $attribs array Associative array of miscellaneous extra
544 * attributes, passed to Html::element()
545 * @return string Raw HTML
547 public static function hidden( $name, $value, $attribs = array() ) {
548 return self
::input( $name, $value, 'hidden', $attribs );
552 * Convenience function to produce an <input> element. This supports leaving
553 * out the cols= and rows= which Xml requires and are required by HTML4/XHTML
554 * but not required by HTML5 and will silently set cols="" and rows="" if
555 * $wgHtml5 is false and cols and rows are omitted (HTML4 validates present
556 * but empty cols="" and rows="" as valid).
558 * @param $name string name attribute
559 * @param $value string value attribute
560 * @param $attribs array Associative array of miscellaneous extra
561 * attributes, passed to Html::element()
562 * @return string Raw HTML
564 public static function textarea( $name, $value = '', $attribs = array() ) {
566 $attribs['name'] = $name;
568 if ( !isset( $attribs['cols'] ) )
569 $attribs['cols'] = "";
570 if ( !isset( $attribs['rows'] ) )
571 $attribs['rows'] = "";
573 return self
::element( 'textarea', $attribs, $value );
577 * Constructs the opening html-tag with necessary doctypes depending on
580 * @param $attribs array Associative array of miscellaneous extra
581 * attributes, passed to Html::element() of html tag.
582 * @return string Raw HTML
584 public static function htmlHeader( $attribs = array() ) {
587 global $wgMimeType, $wgOutputEncoding;
588 if ( self
::isXmlMimeType( $wgMimeType ) ) {
589 $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
592 global $wgHtml5, $wgHtml5Version, $wgWellFormedXml, $wgDocType, $wgDTD;
593 global $wgXhtmlNamespaces, $wgXhtmlDefaultNamespace;
595 if ( $wgWellFormedXml ) {
596 # Unknown elements and attributes are okay in XML, but unknown
597 # named entities are well-formedness errors and will break XML
598 # parsers. Thus we need a doctype that gives us appropriate
599 # entity definitions. The HTML5 spec permits four legacy
600 # doctypes as obsolete but conforming, so let's pick one of
601 # those, although it makes our pages look like XHTML1 Strict.
602 # Isn't compatibility great?
603 $ret .= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
606 $ret .= "<!doctype html>\n";
608 if ( $wgHtml5Version ) {
609 $attribs['version'] = $wgHtml5Version;
612 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
613 $attribs['xmlns'] = $wgXhtmlDefaultNamespace;
614 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
615 $attribs["xmlns:$tag"] = $ns;
618 return $ret . Html
::openElement( 'html', $attribs ) . "\n";
622 * Determines if the given mime type is xml.
624 * @param $mimetype string MimeType
627 public static function isXmlMimeType( $mimetype ) {
628 switch ( $mimetype ) {
630 case 'application/xhtml+xml':
631 case 'application/xml':