Non-word characters don't terminate tag names.
[mediawiki.git] / includes / Html.php
blob1d45e6a504d27905d9cd3d4179d81046aac4ab88
1 <?php
2 /**
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
23 * @file
26 /**
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
35 * output.
37 * There are two important configuration options this class uses:
39 * $wgMimeType: If this is set to an xml mimetype then output should be
40 * valid XHTML5.
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
46 * <a> elements.
48 * @since 1.16
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',
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 // HTML5 Microdata
101 'itemscope',
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 just type out the html element 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 string $element The element's name, e.g., 'a'
117 * @param array $attribs Associative array of attributes, e.g., array(
118 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
119 * further documentation.
120 * @param string $contents The raw HTML contents of the element: *not*
121 * escaped!
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 ) {
129 // Silly XML.
130 return substr( $start, 0, -1 ) . ' />';
132 return $start;
133 } else {
134 return "$start$contents" . self::closeElement( $element );
139 * Identical to rawElement(), but HTML-escapes $contents (like
140 * Xml::element()).
142 * @param $element string
143 * @param $attribs array
144 * @param $contents string
146 * @return 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
151 // elements.
152 '&' => '&amp;',
153 '<' => '&lt;'
154 ) ) );
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
164 * @return string
166 public static function openElement( $element, $attribs = array() ) {
167 global $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/html/syntax.html#optional-tags>
176 if ( !$wgWellFormedXml && !$attribs
177 && in_array( $element, array( 'html', 'head' ) ) ) {
178 return '';
181 // Remove invalid input types
182 if ( $element == 'input' ) {
183 $validTypes = array(
184 'hidden',
185 'text',
186 'password',
187 'checkbox',
188 'radio',
189 'file',
190 'submit',
191 'image',
192 'reset',
193 'button',
195 // HTML input types
196 'datetime',
197 'datetime-local',
198 'date',
199 'month',
200 'time',
201 'week',
202 'number',
203 'range',
204 'email',
205 'url',
206 'search',
207 'tel',
208 'color',
210 if ( isset( $attribs['type'] )
211 && !in_array( $attribs['type'], $validTypes ) ) {
212 unset( $attribs['type'] );
216 // According to standard the default type for <button> elements is "submit".
217 // Depending on compatibility mode IE might use "button", instead.
218 // We enforce the standard "submit".
219 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
220 $attribs['type'] = 'submit';
223 return "<$element" . self::expandAttributes(
224 self::dropDefaults( $element, $attribs ) ) . '>';
228 * Returns "</$element>", except if $wgWellFormedXml is off, in which case
229 * it returns the empty string when that's guaranteed to be safe.
231 * @since 1.17
232 * @param string $element Name of the element, e.g., 'a'
233 * @return string A closing tag, if required
235 public static function closeElement( $element ) {
236 global $wgWellFormedXml;
238 $element = strtolower( $element );
240 // Reference:
241 // http://www.whatwg.org/html/syntax.html#optional-tags
242 if ( !$wgWellFormedXml && in_array( $element, array(
243 'html',
244 'head',
245 'body',
246 'li',
247 'dt',
248 'dd',
249 'tr',
250 'td',
251 'th',
252 ) ) ) {
253 return '';
255 return "</$element>";
259 * Given an element name and an associative array of element attributes,
260 * return an array that is functionally identical to the input array, but
261 * possibly smaller. In particular, attributes might be stripped if they
262 * are given their default values.
264 * This method is not guaranteed to remove all redundant attributes, only
265 * some common ones and some others selected arbitrarily at random. It
266 * only guarantees that the output array should be functionally identical
267 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
269 * @param string $element Name of the element, e.g., 'a'
270 * @param array $attribs Associative array of attributes, e.g., array(
271 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
272 * further documentation.
273 * @return array An array of attributes functionally identical to $attribs
275 private static function dropDefaults( $element, $attribs ) {
277 // Whenever altering this array, please provide a covering test case
278 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
279 static $attribDefaults = array(
280 'area' => array( 'shape' => 'rect' ),
281 'button' => array(
282 'formaction' => 'GET',
283 'formenctype' => 'application/x-www-form-urlencoded',
285 'canvas' => array(
286 'height' => '150',
287 'width' => '300',
289 'command' => array( 'type' => 'command' ),
290 'form' => array(
291 'action' => 'GET',
292 'autocomplete' => 'on',
293 'enctype' => 'application/x-www-form-urlencoded',
295 'input' => array(
296 'formaction' => 'GET',
297 'type' => 'text',
299 'keygen' => array( 'keytype' => 'rsa' ),
300 'link' => array( 'media' => 'all' ),
301 'menu' => array( 'type' => 'list' ),
302 // Note: the use of text/javascript here instead of other JavaScript
303 // MIME types follows the HTML5 spec.
304 'script' => array( 'type' => 'text/javascript' ),
305 'style' => array(
306 'media' => 'all',
307 'type' => 'text/css',
309 'textarea' => array( 'wrap' => 'soft' ),
312 $element = strtolower( $element );
314 foreach ( $attribs as $attrib => $value ) {
315 $lcattrib = strtolower( $attrib );
316 if ( is_array( $value ) ) {
317 $value = implode( ' ', $value );
318 } else {
319 $value = strval( $value );
322 // Simple checks using $attribDefaults
323 if ( isset( $attribDefaults[$element][$lcattrib] ) &&
324 $attribDefaults[$element][$lcattrib] == $value ) {
325 unset( $attribs[$attrib] );
328 if ( $lcattrib == 'class' && $value == '' ) {
329 unset( $attribs[$attrib] );
333 // More subtle checks
334 if ( $element === 'link' && isset( $attribs['type'] )
335 && strval( $attribs['type'] ) == 'text/css' ) {
336 unset( $attribs['type'] );
338 if ( $element === 'input' ) {
339 $type = isset( $attribs['type'] ) ? $attribs['type'] : null;
340 $value = isset( $attribs['value'] ) ? $attribs['value'] : null;
341 if ( $type === 'checkbox' || $type === 'radio' ) {
342 // The default value for checkboxes and radio buttons is 'on'
343 // not ''. By stripping value="" we break radio boxes that
344 // actually wants empty values.
345 if ( $value === 'on' ) {
346 unset( $attribs['value'] );
348 } elseif ( $type === 'submit' ) {
349 // The default value for submit appears to be "Submit" but
350 // let's not bother stripping out localized text that matches
351 // that.
352 } else {
353 // The default value for nearly every other field type is ''
354 // The 'range' and 'color' types use different defaults but
355 // stripping a value="" does not hurt them.
356 if ( $value === '' ) {
357 unset( $attribs['value'] );
361 if ( $element === 'select' && isset( $attribs['size'] ) ) {
362 if ( in_array( 'multiple', $attribs )
363 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
365 // A multi-select
366 if ( strval( $attribs['size'] ) == '4' ) {
367 unset( $attribs['size'] );
369 } else {
370 // Single select
371 if ( strval( $attribs['size'] ) == '1' ) {
372 unset( $attribs['size'] );
377 return $attribs;
381 * Given an associative array of element attributes, generate a string
382 * to stick after the element name in HTML output. Like array( 'href' =>
383 * 'http://www.mediawiki.org/' ) becomes something like
384 * ' href="http://www.mediawiki.org"'. Again, this is like
385 * Xml::expandAttributes(), but it implements some HTML-specific logic.
386 * For instance, it will omit quotation marks if $wgWellFormedXml is false,
387 * and will treat boolean attributes specially.
389 * Attributes that should contain space-separated lists (such as 'class') array
390 * values are allowed as well, which will automagically be normalized
391 * and converted to a space-separated string. In addition to a numerical
392 * array, the attribute value may also be an associative array. See the
393 * example below for how that works.
395 * @par Numerical array
396 * @code
397 * Html::element( 'em', array(
398 * 'class' => array( 'foo', 'bar' )
399 * ) );
400 * // gives '<em class="foo bar"></em>'
401 * @endcode
403 * @par Associative array
404 * @code
405 * Html::element( 'em', array(
406 * 'class' => array( 'foo', 'bar', 'foo' => false, 'quux' => true )
407 * ) );
408 * // gives '<em class="bar quux"></em>'
409 * @endcode
411 * @param array $attribs Associative array of attributes, e.g., array(
412 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
413 * A value of false means to omit the attribute. For boolean attributes,
414 * you can omit the key, e.g., array( 'checked' ) instead of
415 * array( 'checked' => 'checked' ) or such.
416 * @return string HTML fragment that goes between element name and '>'
417 * (starting with a space if at least one attribute is output)
419 public static function expandAttributes( $attribs ) {
420 global $wgWellFormedXml;
422 $ret = '';
423 $attribs = (array)$attribs;
424 foreach ( $attribs as $key => $value ) {
425 if ( $value === false || is_null( $value ) ) {
426 continue;
429 // For boolean attributes, support array( 'foo' ) instead of
430 // requiring array( 'foo' => 'meaningless' ).
431 if ( is_int( $key )
432 && in_array( strtolower( $value ), self::$boolAttribs ) ) {
433 $key = $value;
436 // Not technically required in HTML5 but we'd like consistency
437 // and better compression anyway.
438 $key = strtolower( $key );
440 // Bug 23769: Blacklist all form validation attributes for now. Current
441 // (June 2010) WebKit has no UI, so the form just refuses to submit
442 // without telling the user why, which is much worse than failing
443 // server-side validation. Opera is the only other implementation at
444 // this time, and has ugly UI, so just kill the feature entirely until
445 // we have at least one good implementation.
447 // As the default value of "1" for "step" rejects decimal
448 // numbers to be entered in 'type="number"' fields, allow
449 // the special case 'step="any"'.
451 if ( in_array( $key, array( 'max', 'min', 'pattern', 'required' ) ) ||
452 $key === 'step' && $value !== 'any' ) {
453 continue;
456 // http://www.w3.org/TR/html401/index/attributes.html ("space-separated")
457 // http://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
458 $spaceSeparatedListAttributes = array(
459 'class', // html4, html5
460 'accesskey', // as of html5, multiple space-separated values allowed
461 // html4-spec doesn't document rel= as space-separated
462 // but has been used like that and is now documented as such
463 // in the html5-spec.
464 'rel',
467 // Specific features for attributes that allow a list of space-separated values
468 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
469 // Apply some normalization and remove duplicates
471 // Convert into correct array. Array can contain space-separated
472 // values. Implode/explode to get those into the main array as well.
473 if ( is_array( $value ) ) {
474 // If input wasn't an array, we can skip this step
475 $newValue = array();
476 foreach ( $value as $k => $v ) {
477 if ( is_string( $v ) ) {
478 // String values should be normal `array( 'foo' )`
479 // Just append them
480 if ( !isset( $value[$v] ) ) {
481 // As a special case don't set 'foo' if a
482 // separate 'foo' => true/false exists in the array
483 // keys should be authoritative
484 $newValue[] = $v;
486 } elseif ( $v ) {
487 // If the value is truthy but not a string this is likely
488 // an array( 'foo' => true ), falsy values don't add strings
489 $newValue[] = $k;
492 $value = implode( ' ', $newValue );
494 $value = explode( ' ', $value );
496 // Normalize spacing by fixing up cases where people used
497 // more than 1 space and/or a trailing/leading space
498 $value = array_diff( $value, array( '', ' ' ) );
500 // Remove duplicates and create the string
501 $value = implode( ' ', array_unique( $value ) );
504 // See the "Attributes" section in the HTML syntax part of HTML5,
505 // 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
506 // marks omitted, but not all. (Although a literal " is not
507 // permitted, we don't check for that, since it will be escaped
508 // anyway.)
510 // See also research done on further characters that need to be
511 // escaped: http://code.google.com/p/html5lib/issues/detail?id=93
512 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
513 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
514 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
515 if ( $wgWellFormedXml || $value === ''
516 || preg_match( "![$badChars]!u", $value ) ) {
517 $quote = '"';
518 } else {
519 $quote = '';
522 if ( in_array( $key, self::$boolAttribs ) ) {
523 // In HTML5, we can leave the value empty. If we don't need
524 // well-formed XML, we can omit the = entirely.
525 if ( !$wgWellFormedXml ) {
526 $ret .= " $key";
527 } else {
528 $ret .= " $key=\"\"";
530 } else {
531 // Apparently we need to entity-encode \n, \r, \t, although the
532 // spec doesn't mention that. Since we're doing strtr() anyway,
533 // and we don't need <> escaped here, we may as well not call
534 // htmlspecialchars().
535 // @todo FIXME: Verify that we actually need to
536 // escape \n\r\t here, and explain why, exactly.
538 // We could call Sanitizer::encodeAttribute() for this, but we
539 // don't because we're stubborn and like our marginal savings on
540 // byte size from not having to encode unnecessary quotes.
541 $map = array(
542 '&' => '&amp;',
543 '"' => '&quot;',
544 "\n" => '&#10;',
545 "\r" => '&#13;',
546 "\t" => '&#9;'
548 if ( $wgWellFormedXml ) {
549 // This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
550 // But reportedly it breaks some XML tools?
551 // @todo FIXME: Is this really true?
552 $map['<'] = '&lt;';
554 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
557 return $ret;
561 * Output a "<script>" tag with the given contents.
563 * @todo do some useful escaping as well, like if $contents contains
564 * literal "</script>" or (for XML) literal "]]>".
566 * @param string $contents JavaScript
567 * @return string Raw HTML
569 public static function inlineScript( $contents ) {
570 global $wgWellFormedXml;
572 $attrs = array();
574 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
575 $contents = "/*<![CDATA[*/$contents/*]]>*/";
578 return self::rawElement( 'script', $attrs, $contents );
582 * Output a "<script>" tag linking to the given URL, e.g.,
583 * "<script src=foo.js></script>".
585 * @param $url string
586 * @return string Raw HTML
588 public static function linkedScript( $url ) {
589 $attrs = array( 'src' => $url );
591 return self::element( 'script', $attrs );
595 * Output a "<style>" tag with the given contents for the given media type
596 * (if any). TODO: do some useful escaping as well, like if $contents
597 * contains literal "</style>" (admittedly unlikely).
599 * @param string $contents CSS
600 * @param $media mixed A media type string, like 'screen'
601 * @return string Raw HTML
603 public static function inlineStyle( $contents, $media = 'all' ) {
604 global $wgWellFormedXml;
606 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
607 $contents = "/*<![CDATA[*/$contents/*]]>*/";
610 return self::rawElement( 'style', array(
611 'type' => 'text/css',
612 'media' => $media,
613 ), $contents );
617 * Output a "<link rel=stylesheet>" linking to the given URL for the given
618 * media type (if any).
620 * @param $url string
621 * @param $media mixed A media type string, like 'screen'
622 * @return string Raw HTML
624 public static function linkedStyle( $url, $media = 'all' ) {
625 return self::element( 'link', array(
626 'rel' => 'stylesheet',
627 'href' => $url,
628 'type' => 'text/css',
629 'media' => $media,
630 ) );
634 * Convenience function to produce an "<input>" element. This supports the
635 * new HTML5 input types and attributes.
637 * @param $name string name attribute
638 * @param $value mixed value attribute
639 * @param $type string type attribute
640 * @param array $attribs Associative array of miscellaneous extra
641 * attributes, passed to Html::element()
642 * @return string Raw HTML
644 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
645 $attribs['type'] = $type;
646 $attribs['value'] = $value;
647 $attribs['name'] = $name;
649 return self::element( 'input', $attribs );
653 * Convenience function to produce an input element with type=hidden
655 * @param $name string name attribute
656 * @param $value string value attribute
657 * @param array $attribs Associative array of miscellaneous extra
658 * attributes, passed to Html::element()
659 * @return string Raw HTML
661 public static function hidden( $name, $value, $attribs = array() ) {
662 return self::input( $name, $value, 'hidden', $attribs );
666 * Convenience function to produce an "<input>" element.
668 * This supports leaving out the cols= and rows= which Xml requires and are
669 * required by HTML4/XHTML but not required by HTML5.
671 * @param $name string name attribute
672 * @param $value string value attribute
673 * @param array $attribs Associative array of miscellaneous extra
674 * attributes, passed to Html::element()
675 * @return string Raw HTML
677 public static function textarea( $name, $value = '', $attribs = array() ) {
678 $attribs['name'] = $name;
680 if ( substr( $value, 0, 1 ) == "\n" ) {
681 // Workaround for bug 12130: browsers eat the initial newline
682 // assuming that it's just for show, but they do keep the later
683 // newlines, which we may want to preserve during editing.
684 // Prepending a single newline
685 $spacedValue = "\n" . $value;
686 } else {
687 $spacedValue = $value;
689 return self::element( 'textarea', $attribs, $spacedValue );
692 * Build a drop-down box for selecting a namespace
694 * @param $params array:
695 * - selected: [optional] Id of namespace which should be pre-selected
696 * - all: [optional] Value of item for "all namespaces". If null or unset, no "<option>" is generated to select all namespaces
697 * - label: text for label to add before the field
698 * - exclude: [optional] Array of namespace ids to exclude
699 * - disable: [optional] Array of namespace ids for which the option should be disabled in the selector
700 * @param array $selectAttribs HTML attributes for the generated select element.
701 * - id: [optional], default: 'namespace'
702 * - name: [optional], default: 'namespace'
703 * @return string HTML code to select a namespace.
705 public static function namespaceSelector( array $params = array(), array $selectAttribs = array() ) {
706 global $wgContLang;
708 ksort( $selectAttribs );
710 // Is a namespace selected?
711 if ( isset( $params['selected'] ) ) {
712 // If string only contains digits, convert to clean int. Selected could also
713 // be "all" or "" etc. which needs to be left untouched.
714 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
715 // and returns false for already clean ints. Use regex instead..
716 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
717 $params['selected'] = intval( $params['selected'] );
719 // else: leaves it untouched for later processing
720 } else {
721 $params['selected'] = '';
724 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
725 $params['exclude'] = array();
727 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
728 $params['disable'] = array();
731 // Associative array between option-values and option-labels
732 $options = array();
734 if ( isset( $params['all'] ) ) {
735 // add an option that would let the user select all namespaces.
736 // Value is provided by user, the name shown is localized for the user.
737 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
739 // Add all namespaces as options (in the content language)
740 $options += $wgContLang->getFormattedNamespaces();
742 // Convert $options to HTML and filter out namespaces below 0
743 $optionsHtml = array();
744 foreach ( $options as $nsId => $nsName ) {
745 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
746 continue;
748 if ( $nsId === NS_MAIN ) {
749 // For other namespaces use use the namespace prefix as label, but for
750 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
751 $nsName = wfMessage( 'blanknamespace' )->text();
752 } elseif ( is_int( $nsId ) ) {
753 $nsName = $wgContLang->convertNamespace( $nsId );
755 $optionsHtml[] = Html::element(
756 'option', array(
757 'disabled' => in_array( $nsId, $params['disable'] ),
758 'value' => $nsId,
759 'selected' => $nsId === $params['selected'],
760 ), $nsName
764 if ( !array_key_exists( 'id', $selectAttribs ) ) {
765 $selectAttribs['id'] = 'namespace';
768 if ( !array_key_exists( 'name', $selectAttribs ) ) {
769 $selectAttribs['name'] = 'namespace';
772 $ret = '';
773 if ( isset( $params['label'] ) ) {
774 $ret .= Html::element(
775 'label', array(
776 'for' => isset( $selectAttribs['id'] ) ? $selectAttribs['id'] : null,
777 ), $params['label']
778 ) . '&#160;';
781 // Wrap options in a <select>
782 $ret .= Html::openElement( 'select', $selectAttribs )
783 . "\n"
784 . implode( "\n", $optionsHtml )
785 . "\n"
786 . Html::closeElement( 'select' );
788 return $ret;
792 * Constructs the opening html-tag with necessary doctypes depending on
793 * global variables.
795 * @param array $attribs Associative array of miscellaneous extra
796 * attributes, passed to Html::element() of html tag.
797 * @return string Raw HTML
799 public static function htmlHeader( $attribs = array() ) {
800 $ret = '';
802 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
804 $isXHTML = self::isXmlMimeType( $wgMimeType );
806 if ( $isXHTML ) { // XHTML5
807 // XML mimetyped markup should have an xml header.
808 // However a DOCTYPE is not needed.
809 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
811 // Add the standard xmlns
812 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
814 // And support custom namespaces
815 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
816 $attribs["xmlns:$tag"] = $ns;
818 } else { // HTML5
819 // DOCTYPE
820 $ret .= "<!DOCTYPE html>\n";
823 if ( $wgHtml5Version ) {
824 $attribs['version'] = $wgHtml5Version;
827 $html = Html::openElement( 'html', $attribs );
829 if ( $html ) {
830 $html .= "\n";
833 $ret .= $html;
835 return $ret;
839 * Determines if the given mime type is xml.
841 * @param $mimetype string MimeType
842 * @return Boolean
844 public static function isXmlMimeType( $mimetype ) {
845 # http://www.whatwg.org/html/infrastructure.html#xml-mime-type
846 # * text/xml
847 # * application/xml
848 # * Any mimetype with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
849 return (bool) preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
853 * Get HTML for an info box with an icon.
855 * @param string $text wikitext, get this with wfMessage()->plain()
856 * @param string $icon icon name, file in skins/common/images
857 * @param string $alt alternate text for the icon
858 * @param string $class additional class name to add to the wrapper div
859 * @param $useStylePath
861 * @return string
863 static function infoBox( $text, $icon, $alt, $class = false, $useStylePath = true ) {
864 global $wgStylePath;
866 if ( $useStylePath ) {
867 $icon = $wgStylePath . '/common/images/' . $icon;
870 $s = Html::openElement( 'div', array( 'class' => "mw-infobox $class" ) );
872 $s .= Html::openElement( 'div', array( 'class' => 'mw-infobox-left' ) ) .
873 Html::element( 'img',
874 array(
875 'src' => $icon,
876 'alt' => $alt,
879 Html::closeElement( 'div' );
881 $s .= Html::openElement( 'div', array( 'class' => 'mw-infobox-right' ) ) .
882 $text .
883 Html::closeElement( 'div' );
884 $s .= Html::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
886 $s .= Html::closeElement( 'div' );
888 $s .= Html::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
890 return $s;
894 * Generate a srcset attribute value from an array mapping pixel densities
895 * to URLs. Note that srcset supports width and height values as well, which
896 * are not used here.
898 * @param array $urls
899 * @return string
901 static function srcSet( $urls ) {
902 $candidates = array();
903 foreach ( $urls as $density => $url ) {
904 // Image candidate syntax per current whatwg live spec, 2012-09-23:
905 // http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
906 $candidates[] = "{$url} {$density}x";
908 return implode( ", ", $candidates );