2 # Copyright (C) 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 HTML 5, 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
43 # List of void elements from HTML 5, section 9.1.2 as of 2009-08-10
44 private static $voidElements = array(
61 # Boolean attributes, which may have the value omitted entirely. Manually
62 # collected from the HTML 5 spec as of 2009-08-10.
63 private static $boolAttribs = array(
88 * Returns an HTML element in a string. The major advantage here over
89 * manually typing out the HTML is that it will escape all attribute
90 * values. If you're hardcoding all the attributes, or there are none, you
91 * should probably type out the string yourself.
93 * This is quite similar to Xml::tags(), but it implements some useful
94 * HTML-specific logic. For instance, there is no $allowShortTag
95 * parameter: the closing tag is magically omitted if $element has an empty
96 * content model. If $wgWellFormedXml is false, then a few bytes will be
97 * shaved off the HTML output as well. In the future, other HTML-specific
98 * features might be added, like allowing arrays for the values of
99 * attributes like class= and media=.
101 * @param $element string The element's name, e.g., 'a'
102 * @param $attribs array Associative array of attributes, e.g., array(
103 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
104 * further documentation.
105 * @param $contents string The raw HTML contents of the element: *not*
107 * @return string Raw HTML
109 public static function rawElement( $element, $attribs = array(), $contents = '' ) {
110 global $wgHtml5, $wgWellFormedXml;
111 $attribs = (array)$attribs;
112 # This is not required in HTML 5, but let's do it anyway, for
113 # consistency and better compression.
114 $element = strtolower( $element );
116 # Element-specific hacks to slim down output and ensure validity
117 if ( $element == 'input' ) {
119 # With $wgHtml5 off we want to validate as XHTML 1, so we
120 # strip out any fancy HTML 5-only input types for now.
122 # Whitelist of valid types:
135 if ( isset( $attribs['type'] )
136 && !in_array( $attribs['type'], $validTypes ) ) {
137 # Fall back to type=text, the default
138 unset( $attribs['type'] );
140 # Here we're blacklisting some HTML5-only attributes...
141 $html5attribs = array(
153 foreach ( $html5attribs as $badAttr ) {
154 unset( $attribs[$badAttr] );
159 $start = "<$element" . self
::expandAttributes(
160 self
::dropDefaults( $element, $attribs ) );
161 if ( in_array( $element, self
::$voidElements ) ) {
162 if ( $wgWellFormedXml ) {
167 return "$start>$contents</$element>";
172 * Identical to rawElement(), but HTML-escapes $contents (like
175 public static function element( $element, $attribs = array(), $contents = '' ) {
176 return self
::rawElement( $element, $attribs, strtr( $contents, array(
177 # There's no point in escaping quotes, >, etc. in the contents of
185 * Given an element name and an associative array of element attributes,
186 * return an array that is functionally identical to the input array, but
187 * possibly smaller. In particular, attributes might be stripped if they
188 * are given their default values.
190 * This method is not guaranteed to remove all redundant attributes, only
191 * some common ones and some others selected arbitrarily at random. It
192 * only guarantees that the output array should be functionally identical
193 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
195 * @param $element string Name of the element, e.g., 'a'
196 * @param $attribs array Associative array of attributes, e.g., array(
197 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
198 * further documentation.
199 * @return array An array of attributes functionally identical to $attribs
201 private static function dropDefaults( $element, $attribs ) {
202 # Don't bother doing anything if we aren't outputting HTML5; it's too
203 # much of a pain to maintain two sets of defaults.
209 static $attribDefaults = array(
210 'area' => array( 'shape' => 'rect' ),
212 'formaction' => 'GET',
213 'formenctype' => 'application/x-www-form-urlencoded',
220 'command' => array( 'type' => 'command' ),
223 'autocomplete' => 'on',
224 'enctype' => 'application/x-www-form-urlencoded',
227 'formaction' => 'GET',
231 'keygen' => array( 'keytype' => 'rsa' ),
232 'link' => array( 'media' => 'all' ),
233 'menu' => array( 'type' => 'list' ),
234 # Note: the use of text/javascript here instead of other JavaScript
235 # MIME types follows the HTML 5 spec.
236 'script' => array( 'type' => 'text/javascript' ),
239 'type' => 'text/css',
241 'textarea' => array( 'wrap' => 'soft' ),
244 $element = strtolower( $element );
246 foreach ( $attribs as $attrib => $value ) {
247 $lcattrib = strtolower( $attrib );
248 $value = strval( $value );
250 # Simple checks using $attribDefaults
251 if ( isset( $attribDefaults[$element][$lcattrib] ) &&
252 $attribDefaults[$element][$lcattrib] == $value ) {
253 unset( $attribs[$attrib] );
256 if ( $lcattrib == 'class' && $value == '' ) {
257 unset( $attribs[$attrib] );
262 if ( $element === 'link' && isset( $attribs['type'] )
263 && strval( $attribs['type'] ) == 'text/css' ) {
264 unset( $attribs['type'] );
266 if ( $element === 'select' && isset( $attribs['size'] ) ) {
267 if ( in_array( 'multiple', $attribs )
268 ||
( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
271 if ( strval( $attribs['size'] ) == '4' ) {
272 unset( $attribs['size'] );
276 if ( strval( $attribs['size'] ) == '1' ) {
277 unset( $attribs['size'] );
286 * Given an associative array of element attributes, generate a string
287 * to stick after the element name in HTML output. Like array( 'href' =>
288 * 'http://www.mediawiki.org/' ) becomes something like
289 * ' href="http://www.mediawiki.org"'. Again, this is like
290 * Xml::expandAttributes(), but it implements some HTML-specific logic.
291 * For instance, it will omit quotation marks if $wgWellFormedXml is false,
292 * and will treat boolean attributes specially.
294 * @param $attribs array Associative array of attributes, e.g., array(
295 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
296 * A value of false means to omit the attribute. For boolean attributes,
297 * you can omit the key, e.g., array( 'checked' ) instead of
298 * array( 'checked' => 'checked' ) or such.
299 * @return string HTML fragment that goes between element name and '>'
300 * (starting with a space if at least one attribute is output)
302 public static function expandAttributes( $attribs ) {
303 global $wgHtml5, $wgWellFormedXml;
306 $attribs = (array)$attribs;
307 foreach ( $attribs as $key => $value ) {
308 if ( $value === false ) {
312 # For boolean attributes, support array( 'foo' ) instead of
313 # requiring array( 'foo' => 'meaningless' ).
315 && in_array( strtolower( $value ), self
::$boolAttribs ) ) {
319 # Not technically required in HTML 5, but required in XHTML 1.0,
320 # and we'd like consistency and better compression anyway.
321 $key = strtolower( $key );
323 # See the "Attributes" section in the HTML syntax part of HTML 5,
324 # 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
325 # marks omitted, but not all. (Although a literal " is not
326 # permitted, we don't check for that, since it will be escaped
329 # See also research done on further characters that need to be
330 # escaped: http://code.google.com/p/html5lib/issues/detail?id=93
331 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
332 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
333 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
334 if ( $wgWellFormedXml ||
$value === ''
335 ||
preg_match( "![$badChars]!u", $value ) ) {
341 if ( in_array( $key, self
::$boolAttribs ) ) {
342 # In XHTML 1.0 Transitional, the value needs to be equal to the
343 # key. In HTML 5, we can leave the value empty instead. If we
344 # don't need well-formed XML, we can omit the = entirely.
345 if ( !$wgWellFormedXml ) {
347 } elseif ( $wgHtml5 ) {
348 $ret .= " $key=\"\"";
350 $ret .= " $key=\"$key\"";
353 # Apparently we need to entity-encode \n, \r, \t, although the
354 # spec doesn't mention that. Since we're doing strtr() anyway,
355 # and we don't need <> escaped here, we may as well not call
356 # htmlspecialchars(). FIXME: verify that we actually need to
357 # escape \n\r\t here, and explain why, exactly.
359 # We could call Sanitizer::encodeAttribute() for this, but we
360 # don't because we're stubborn and like our marginal savings on
361 # byte size from not having to encode unnecessary quotes.
369 if ( $wgWellFormedXml ) {
370 # '<' must be escaped in attributes for XML for some
371 # reason, per spec: http://www.w3.org/TR/xml/#NT-AttValue
374 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
381 * Output a <script> tag with the given contents. TODO: do some useful
382 * escaping as well, like if $contents contains literal '</script>' or (for
383 * XML) literal "]]>".
385 * @param $contents string JavaScript
386 * @return string Raw HTML
388 public static function inlineScript( $contents ) {
389 global $wgHtml5, $wgJsMimeType, $wgWellFormedXml;
393 $attrs['type'] = $wgJsMimeType;
395 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
396 $contents = "/*<![CDATA[*/$contents/*]]>*/";
398 return self
::rawElement( 'script', $attrs, $contents );
402 * Output a <script> tag linking to the given URL, e.g.,
403 * <script src=foo.js></script>.
406 * @return string Raw HTML
408 public static function linkedScript( $url ) {
409 global $wgHtml5, $wgJsMimeType;
411 $attrs = array( 'src' => $url );
413 $attrs['type'] = $wgJsMimeType;
415 return self
::element( 'script', $attrs );
419 * Output a <style> tag with the given contents for the given media type
420 * (if any). TODO: do some useful escaping as well, like if $contents
421 * contains literal '</style>' (admittedly unlikely).
423 * @param $contents string CSS
424 * @param $media mixed A media type string, like 'screen'
425 * @return string Raw HTML
427 public static function inlineStyle( $contents, $media = 'all' ) {
428 global $wgWellFormedXml;
430 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
431 $contents = "/*<![CDATA[*/$contents/*]]>*/";
433 return self
::rawElement( 'style', array(
434 'type' => 'text/css',
440 * Output a <link rel=stylesheet> linking to the given URL for the given
441 * media type (if any).
444 * @param $media mixed A media type string, like 'screen'
445 * @return string Raw HTML
447 public static function linkedStyle( $url, $media = 'all' ) {
448 return self
::element( 'link', array(
449 'rel' => 'stylesheet',
451 'type' => 'text/css',
457 * Convenience function to produce an <input> element. This supports the
458 * new HTML 5 input types and attributes, and will silently strip them if
461 * @param $name string name attribute
462 * @param $value mixed value attribute
463 * @param $type string type attribute
464 * @param $attribs array Associative array of miscellaneous extra
465 * attributes, passed to Html::element()
466 * @return string Raw HTML
468 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
469 $attribs['type'] = $type;
470 $attribs['value'] = $value;
471 $attribs['name'] = $name;
473 return self
::element( 'input', $attribs );
477 * Convenience function to produce an input element with type=hidden, like
480 * @param $name string name attribute
481 * @param $value string value attribute
482 * @param $attribs array Associative array of miscellaneous extra
483 * attributes, passed to Html::element()
484 * @return string Raw HTML
486 public static function hidden( $name, $value, $attribs = array() ) {
487 return self
::input( $name, $value, 'hidden', $attribs );
491 * Convenience function to produce an <input> element. This supports leaving
492 * out the cols= and rows= which Xml requires and are required by HTML4/XHTML
493 * but not required by HTML5 and will silently set cols="" and rows="" if
494 * $wgHtml5 is false and cols and rows are omitted (HTML4 validates present
495 * but empty cols="" and rows="" as valid).
497 * @param $name string name attribute
498 * @param $value string value attribute
499 * @param $attribs array Associative array of miscellaneous extra
500 * attributes, passed to Html::element()
501 * @return string Raw HTML
503 public static function textarea( $name, $value = '', $attribs = array() ) {
505 $attribs['name'] = $name;
507 if ( !array_key_exists('cols', $attribs) )
508 $attribs['cols'] = "";
509 if ( !array_key_exists('rows', $attribs) )
510 $attribs['rows'] = "";
512 return self
::element( 'textarea', $attribs, $value );