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(
105 * Returns an HTML element in a string. The major advantage here over
106 * manually typing out the HTML is that it will escape all attribute
107 * values. If you're hardcoding all the attributes, or there are none, you
108 * should probably type out the string yourself.
110 * This is quite similar to Xml::tags(), but it implements some useful
111 * HTML-specific logic. For instance, there is no $allowShortTag
112 * parameter: the closing tag is magically omitted if $element has an empty
113 * content model. If $wgWellFormedXml is false, then a few bytes will be
114 * shaved off the HTML output as well.
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 # Here we're blacklisting some HTML5-only attributes...
391 if ( !$wgHtml5 && in_array( $key, array(
406 # Bug 23769: Blacklist all form validation attributes for now. Current
407 # (June 2010) WebKit has no UI, so the form just refuses to submit
408 # without telling the user why, which is much worse than failing
409 # server-side validation. Opera is the only other implementation at
410 # this time, and has ugly UI, so just kill the feature entirely until
411 # we have at least one good implementation.
412 if ( in_array( $key, array( 'max', 'min', 'pattern', 'required', 'step' ) ) ) {
416 // http://www.w3.org/TR/html401/index/attributes.html ("space-separated")
417 // http://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
418 $spaceSeparatedListAttributes = array(
419 'class', // html4, html5
420 'accesskey', // as of html5, multiple space-separated values allowed
421 // html4-spec doesn't document rel= as space-separated
422 // but has been used like that and is now documented as such
423 // in the html5-spec.
427 # Specific features for attributes that allow a list of space-separated values
428 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
429 // Apply some normalization and remove duplicates
431 // Convert into correct array. Array can contain space-seperated
432 // values. Implode/explode to get those into the main array as well.
433 if ( is_array( $value ) ) {
434 // If input wasn't an array, we can skip this step
435 $value = implode( ' ', $value );
437 $value = explode( ' ', $value );
439 // Normalize spacing by fixing up cases where people used
440 // more than 1 space and/or a trailing/leading space
441 $value = array_diff( $value, array( '', ' ') );
443 // Remove duplicates and create the string
444 $value = implode( ' ', array_unique( $value ) );
447 # See the "Attributes" section in the HTML syntax part of HTML5,
448 # 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
449 # marks omitted, but not all. (Although a literal " is not
450 # permitted, we don't check for that, since it will be escaped
453 # See also research done on further characters that need to be
454 # escaped: http://code.google.com/p/html5lib/issues/detail?id=93
455 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
456 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
457 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
458 if ( $wgWellFormedXml ||
$value === ''
459 ||
preg_match( "![$badChars]!u", $value ) ) {
465 if ( in_array( $key, self
::$boolAttribs ) ) {
466 # In XHTML 1.0 Transitional, the value needs to be equal to the
467 # key. In HTML5, we can leave the value empty instead. If we
468 # don't need well-formed XML, we can omit the = entirely.
469 if ( !$wgWellFormedXml ) {
471 } elseif ( $wgHtml5 ) {
472 $ret .= " $key=\"\"";
474 $ret .= " $key=\"$key\"";
477 # Apparently we need to entity-encode \n, \r, \t, although the
478 # spec doesn't mention that. Since we're doing strtr() anyway,
479 # and we don't need <> escaped here, we may as well not call
480 # htmlspecialchars().
481 # @todo FIXME: Verify that we actually need to
482 # escape \n\r\t here, and explain why, exactly.
484 # We could call Sanitizer::encodeAttribute() for this, but we
485 # don't because we're stubborn and like our marginal savings on
486 # byte size from not having to encode unnecessary quotes.
494 if ( $wgWellFormedXml ) {
495 # This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
496 # But reportedly it breaks some XML tools?
497 # @todo FIXME: Is this really true?
500 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
507 * Output a <script> tag with the given contents. TODO: do some useful
508 * escaping as well, like if $contents contains literal '</script>' or (for
509 * XML) literal "]]>".
511 * @param $contents string JavaScript
512 * @return string Raw HTML
514 public static function inlineScript( $contents ) {
515 global $wgHtml5, $wgJsMimeType, $wgWellFormedXml;
520 $attrs['type'] = $wgJsMimeType;
523 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
524 $contents = "/*<![CDATA[*/$contents/*]]>*/";
527 return self
::rawElement( 'script', $attrs, $contents );
531 * Output a <script> tag linking to the given URL, e.g.,
532 * <script src=foo.js></script>.
535 * @return string Raw HTML
537 public static function linkedScript( $url ) {
538 global $wgHtml5, $wgJsMimeType;
540 $attrs = array( 'src' => $url );
543 $attrs['type'] = $wgJsMimeType;
546 return self
::element( 'script', $attrs );
550 * Output a <style> tag with the given contents for the given media type
551 * (if any). TODO: do some useful escaping as well, like if $contents
552 * contains literal '</style>' (admittedly unlikely).
554 * @param $contents string CSS
555 * @param $media mixed A media type string, like 'screen'
556 * @return string Raw HTML
558 public static function inlineStyle( $contents, $media = 'all' ) {
559 global $wgWellFormedXml;
561 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
562 $contents = "/*<![CDATA[*/$contents/*]]>*/";
565 return self
::rawElement( 'style', array(
566 'type' => 'text/css',
572 * Output a <link rel=stylesheet> linking to the given URL for the given
573 * media type (if any).
576 * @param $media mixed A media type string, like 'screen'
577 * @return string Raw HTML
579 public static function linkedStyle( $url, $media = 'all' ) {
580 return self
::element( 'link', array(
581 'rel' => 'stylesheet',
583 'type' => 'text/css',
589 * Convenience function to produce an <input> element. This supports the
590 * new HTML5 input types and attributes, and will silently strip them if
593 * @param $name string name attribute
594 * @param $value mixed value attribute
595 * @param $type string type attribute
596 * @param $attribs array Associative array of miscellaneous extra
597 * attributes, passed to Html::element()
598 * @return string Raw HTML
600 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
601 $attribs['type'] = $type;
602 $attribs['value'] = $value;
603 $attribs['name'] = $name;
605 return self
::element( 'input', $attribs );
609 * Convenience function to produce an input element with type=hidden
611 * @param $name string name attribute
612 * @param $value string value attribute
613 * @param $attribs array Associative array of miscellaneous extra
614 * attributes, passed to Html::element()
615 * @return string Raw HTML
617 public static function hidden( $name, $value, $attribs = array() ) {
618 return self
::input( $name, $value, 'hidden', $attribs );
622 * Convenience function to produce an <input> element. This supports leaving
623 * out the cols= and rows= which Xml requires and are required by HTML4/XHTML
624 * but not required by HTML5 and will silently set cols="" and rows="" if
625 * $wgHtml5 is false and cols and rows are omitted (HTML4 validates present
626 * but empty cols="" and rows="" as valid).
628 * @param $name string name attribute
629 * @param $value string value attribute
630 * @param $attribs array Associative array of miscellaneous extra
631 * attributes, passed to Html::element()
632 * @return string Raw HTML
634 public static function textarea( $name, $value = '', $attribs = array() ) {
637 $attribs['name'] = $name;
640 if ( !isset( $attribs['cols'] ) ) {
641 $attribs['cols'] = "";
644 if ( !isset( $attribs['rows'] ) ) {
645 $attribs['rows'] = "";
649 return self
::element( 'textarea', $attribs, $value );
653 * Constructs the opening html-tag with necessary doctypes depending on
656 * @param $attribs array Associative array of miscellaneous extra
657 * attributes, passed to Html::element() of html tag.
658 * @return string Raw HTML
660 public static function htmlHeader( $attribs = array() ) {
665 if ( self
::isXmlMimeType( $wgMimeType ) ) {
666 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
669 global $wgHtml5, $wgHtml5Version, $wgDocType, $wgDTD;
670 global $wgXhtmlNamespaces, $wgXhtmlDefaultNamespace;
673 $ret .= "<!DOCTYPE html>\n";
675 if ( $wgHtml5Version ) {
676 $attribs['version'] = $wgHtml5Version;
679 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
680 $attribs['xmlns'] = $wgXhtmlDefaultNamespace;
682 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
683 $attribs["xmlns:$tag"] = $ns;
687 $html = Html
::openElement( 'html', $attribs );
699 * Determines if the given mime type is xml.
701 * @param $mimetype string MimeType
704 public static function isXmlMimeType( $mimetype ) {
705 switch ( $mimetype ) {
707 case 'application/xhtml+xml':
708 case 'application/xml':
716 * Get HTML for an info box with an icon.
718 * @param $text String: wikitext, get this with wfMsgNoTrans()
719 * @param $icon String: icon name, file in skins/common/images
720 * @param $alt String: alternate text for the icon
721 * @param $class String: additional class name to add to the wrapper div
722 * @param $useStylePath
726 static function infoBox( $text, $icon, $alt, $class = false, $useStylePath = true ) {
729 if ( $useStylePath ) {
730 $icon = $wgStylePath.'/common/images/'.$icon;
733 $s = Html
::openElement( 'div', array( 'class' => "mw-infobox $class") );
735 $s .= Html
::openElement( 'div', array( 'class' => 'mw-infobox-left' ) ).
736 Html
::element( 'img',
742 Html
::closeElement( 'div' );
744 $s .= Html
::openElement( 'div', array( 'class' => 'mw-infobox-right' ) ).
746 Html
::closeElement( 'div' );
747 $s .= Html
::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
749 $s .= Html
::closeElement( 'div' );
751 $s .= Html
::element( 'div', array( 'style' => 'clear: left;' ), ' ' );