3 * Collection of methods to generate HTML content
5 * Copyright © 2009 Aryeh Gregor
6 * http://www.mediawiki.org/
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.
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.
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
27 * This class is a collection of static functions that serve two purposes:
29 * 1) Implement any algorithms specified by HTML5, or other HTML
30 * specifications, in a convenient and self-contained way.
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
37 * There are two important configuration options this class uses:
39 * $wgHtml5: If this is set to false, then all output should be valid XHTML 1.0
41 * $wgWellFormedXml: If this is set to true, then all output should be
42 * well-formed XML (quotes on attributes, self-closing tags, etc.).
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
51 # List of void elements from HTML5, section 8.1.2 as of 2011-08-12
52 private static $voidElements = array(
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(
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.
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=.
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*
122 * @return string Raw HTML
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 ) {
130 return substr( $start, 0, -1 ) . ' />';
134 return "$start$contents" . self
::closeElement( $element );
139 * Identical to rawElement(), but HTML-escapes $contents (like
142 * @param $element string
143 * @param $attribs array
144 * @param $contents string
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
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).
161 * @param $element string
162 * @param $attribs array
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 );
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' ) ) ) {
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.
201 if ( isset( $attribs['type'] )
202 && !in_array( $attribs['type'], $validTypes ) ) {
203 unset( $attribs['type'] );
206 if ( isset( $attribs['type'] ) && $attribs['type'] == 'search'
208 unset( $attribs['type'] );
212 if ( !$wgHtml5 && $element == 'textarea' && isset( $attribs['maxlength'] ) ) {
213 unset( $attribs['maxlength'] );
216 return "<$element" . self
::expandAttributes(
217 self
::dropDefaults( $element, $attribs ) ) . '>';
221 * Returns "</$element>", except if $wgWellFormedXml is off, in which case
222 * it returns the empty string when that's guaranteed to be safe.
225 * @param $element string Name of the element, e.g., 'a'
226 * @return string A closing tag, if required
228 public static function closeElement( $element ) {
229 global $wgWellFormedXml;
231 $element = strtolower( $element );
234 # http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags
235 if ( !$wgWellFormedXml && in_array( $element, array(
248 return "</$element>";
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.
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).
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
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.
276 static $attribDefaults = array(
277 'area' => array( 'shape' => 'rect' ),
279 'formaction' => 'GET',
280 'formenctype' => 'application/x-www-form-urlencoded',
287 'command' => array( 'type' => 'command' ),
290 'autocomplete' => 'on',
291 'enctype' => 'application/x-www-form-urlencoded',
294 'formaction' => 'GET',
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' ),
306 'type' => 'text/css',
308 'textarea' => array( 'wrap' => 'soft' ),
311 $element = strtolower( $element );
313 foreach ( $attribs as $attrib => $value ) {
314 $lcattrib = strtolower( $attrib );
315 $value = strval( $value );
317 # Simple checks using $attribDefaults
318 if ( isset( $attribDefaults[$element][$lcattrib] ) &&
319 $attribDefaults[$element][$lcattrib] == $value ) {
320 unset( $attribs[$attrib] );
323 if ( $lcattrib == 'class' && $value == '' ) {
324 unset( $attribs[$attrib] );
329 if ( $element === 'link' && isset( $attribs['type'] )
330 && strval( $attribs['type'] ) == 'text/css' ) {
331 unset( $attribs['type'] );
333 if ( $element === 'select' && isset( $attribs['size'] ) ) {
334 if ( in_array( 'multiple', $attribs )
335 ||
( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
338 if ( strval( $attribs['size'] ) == '4' ) {
339 unset( $attribs['size'] );
343 if ( strval( $attribs['size'] ) == '1' ) {
344 unset( $attribs['size'] );
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.
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)
369 public static function expandAttributes( $attribs ) {
370 global $wgHtml5, $wgWellFormedXml;
373 $attribs = (array)$attribs;
374 foreach ( $attribs as $key => $value ) {
375 if ( $value === false ||
is_null( $value ) ) {
379 # For boolean attributes, support array( 'foo' ) instead of
380 # requiring array( 'foo' => 'meaningless' ).
382 && in_array( strtolower( $value ), self
::$boolAttribs ) ) {
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 );
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' ) ) ) {
400 # Here we're blacklisting some HTML5-only attributes...
401 if ( !$wgHtml5 && in_array( $key, array(
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
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 ) ) {
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 ) {
440 } elseif ( $wgHtml5 ) {
441 $ret .= " $key=\"\"";
443 $ret .= " $key=\"$key\"";
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.
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.
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?
469 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
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 "]]>".
480 * @param $contents string JavaScript
481 * @return string Raw HTML
483 public static function inlineScript( $contents ) {
484 global $wgHtml5, $wgJsMimeType, $wgWellFormedXml;
489 $attrs['type'] = $wgJsMimeType;
492 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
493 $contents = "/*<![CDATA[*/$contents/*]]>*/";
496 return self
::rawElement( 'script', $attrs, $contents );
500 * Output a <script> tag linking to the given URL, e.g.,
501 * <script src=foo.js></script>.
504 * @return string Raw HTML
506 public static function linkedScript( $url ) {
507 global $wgHtml5, $wgJsMimeType;
509 $attrs = array( 'src' => $url );
512 $attrs['type'] = $wgJsMimeType;
515 return self
::element( 'script', $attrs );
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).
523 * @param $contents string CSS
524 * @param $media mixed A media type string, like 'screen'
525 * @return string Raw HTML
527 public static function inlineStyle( $contents, $media = 'all' ) {
528 global $wgWellFormedXml;
530 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
531 $contents = "/*<![CDATA[*/$contents/*]]>*/";
534 return self
::rawElement( 'style', array(
535 'type' => 'text/css',
541 * Output a <link rel=stylesheet> linking to the given URL for the given
542 * media type (if any).
545 * @param $media mixed A media type string, like 'screen'
546 * @return string Raw HTML
548 public static function linkedStyle( $url, $media = 'all' ) {
549 return self
::element( 'link', array(
550 'rel' => 'stylesheet',
552 'type' => 'text/css',
558 * Convenience function to produce an <input> element. This supports the
559 * new HTML5 input types and attributes, and will silently strip them if
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
569 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
570 $attribs['type'] = $type;
571 $attribs['value'] = $value;
572 $attribs['name'] = $name;
574 return self
::element( 'input', $attribs );
578 * Convenience function to produce an input element with type=hidden
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
586 public static function hidden( $name, $value, $attribs = array() ) {
587 return self
::input( $name, $value, 'hidden', $attribs );
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).
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
603 public static function textarea( $name, $value = '', $attribs = array() ) {
606 $attribs['name'] = $name;
609 if ( !isset( $attribs['cols'] ) ) {
610 $attribs['cols'] = "";
613 if ( !isset( $attribs['rows'] ) ) {
614 $attribs['rows'] = "";
618 return self
::element( 'textarea', $attribs, $value );
622 * Constructs the opening html-tag with necessary doctypes depending on
625 * @param $attribs array Associative array of miscellaneous extra
626 * attributes, passed to Html::element() of html tag.
627 * @return string Raw HTML
629 public static function htmlHeader( $attribs = array() ) {
634 if ( self
::isXmlMimeType( $wgMimeType ) ) {
635 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
638 global $wgHtml5, $wgHtml5Version, $wgDocType, $wgDTD;
639 global $wgXhtmlNamespaces, $wgXhtmlDefaultNamespace;
642 $ret .= "<!DOCTYPE html>\n";
644 if ( $wgHtml5Version ) {
645 $attribs['version'] = $wgHtml5Version;
648 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
649 $attribs['xmlns'] = $wgXhtmlDefaultNamespace;
651 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
652 $attribs["xmlns:$tag"] = $ns;
656 $html = Html
::openElement( 'html', $attribs );
668 * Determines if the given mime type is xml.
670 * @param $mimetype string MimeType
673 public static function isXmlMimeType( $mimetype ) {
674 switch ( $mimetype ) {
676 case 'application/xhtml+xml':
677 case 'application/xml':
685 * Get HTML for an info box with an icon.
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
695 static function infoBox( $text, $icon, $alt, $class = false, $useStylePath = true ) {
698 if ( $useStylePath ) {
699 $icon = $wgStylePath.'/common/images/'.$icon;
702 $s = Html
::openElement( 'div', array( 'class' => "mw-infobox $class") );
704 $s .= Html
::openElement( 'div', array( 'class' => 'mw-infobox-left' ) ).
705 Html
::element( 'img',
711 Html
::closeElement( 'div' );
713 $s .= Html
::openElement( 'div', array( 'class' => 'mw-infobox-right' ) ).
715 Html
::closeElement( 'div' );
716 $s .= Html
::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
718 $s .= Html
::closeElement( 'div' );
720 $s .= Html
::element( 'div', array( 'style' => 'clear: left;' ), ' ' );