Actually format search error Status objects nicely
[mediawiki.git] / includes / Html.php
blob5262ffe6192bcf62739a0e16db593ffca3a066bf
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 string $element
143 * @param array $attribs
144 * @param string $contents
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 string $element
162 * @param array $attribs
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 // Support intuitive array( 'checked' => true/false ) form
426 if ( $value === false || is_null( $value ) ) {
427 continue;
430 // For boolean attributes, support array( 'foo' ) instead of
431 // requiring array( 'foo' => 'meaningless' ).
432 if ( is_int( $key )
433 && in_array( strtolower( $value ), self::$boolAttribs ) ) {
434 $key = $value;
437 // Not technically required in HTML5 but we'd like consistency
438 // and better compression anyway.
439 $key = strtolower( $key );
441 // Bug 23769: Blacklist all form validation attributes for now. Current
442 // (June 2010) WebKit has no UI, so the form just refuses to submit
443 // without telling the user why, which is much worse than failing
444 // server-side validation. Opera is the only other implementation at
445 // this time, and has ugly UI, so just kill the feature entirely until
446 // we have at least one good implementation.
448 // As the default value of "1" for "step" rejects decimal
449 // numbers to be entered in 'type="number"' fields, allow
450 // the special case 'step="any"'.
452 if ( in_array( $key, array( 'max', 'min', 'pattern', 'required' ) )
453 || $key === 'step' && $value !== 'any' ) {
454 continue;
457 // http://www.w3.org/TR/html401/index/attributes.html ("space-separated")
458 // http://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
459 $spaceSeparatedListAttributes = array(
460 'class', // html4, html5
461 'accesskey', // as of html5, multiple space-separated values allowed
462 // html4-spec doesn't document rel= as space-separated
463 // but has been used like that and is now documented as such
464 // in the html5-spec.
465 'rel',
468 // Specific features for attributes that allow a list of space-separated values
469 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
470 // Apply some normalization and remove duplicates
472 // Convert into correct array. Array can contain space-separated
473 // values. Implode/explode to get those into the main array as well.
474 if ( is_array( $value ) ) {
475 // If input wasn't an array, we can skip this step
476 $newValue = array();
477 foreach ( $value as $k => $v ) {
478 if ( is_string( $v ) ) {
479 // String values should be normal `array( 'foo' )`
480 // Just append them
481 if ( !isset( $value[$v] ) ) {
482 // As a special case don't set 'foo' if a
483 // separate 'foo' => true/false exists in the array
484 // keys should be authoritative
485 $newValue[] = $v;
487 } elseif ( $v ) {
488 // If the value is truthy but not a string this is likely
489 // an array( 'foo' => true ), falsy values don't add strings
490 $newValue[] = $k;
493 $value = implode( ' ', $newValue );
495 $value = explode( ' ', $value );
497 // Normalize spacing by fixing up cases where people used
498 // more than 1 space and/or a trailing/leading space
499 $value = array_diff( $value, array( '', ' ' ) );
501 // Remove duplicates and create the string
502 $value = implode( ' ', array_unique( $value ) );
505 // See the "Attributes" section in the HTML syntax part of HTML5,
506 // 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
507 // marks omitted, but not all. (Although a literal " is not
508 // permitted, we don't check for that, since it will be escaped
509 // anyway.)
511 // See also research done on further characters that need to be
512 // escaped: http://code.google.com/p/html5lib/issues/detail?id=93
513 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
514 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
515 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
516 if ( $wgWellFormedXml || $value === ''
517 || preg_match( "![$badChars]!u", $value ) ) {
518 $quote = '"';
519 } else {
520 $quote = '';
523 if ( in_array( $key, self::$boolAttribs ) ) {
524 // In HTML5, we can leave the value empty. If we don't need
525 // well-formed XML, we can omit the = entirely.
526 if ( !$wgWellFormedXml ) {
527 $ret .= " $key";
528 } else {
529 $ret .= " $key=\"\"";
531 } else {
532 // Apparently we need to entity-encode \n, \r, \t, although the
533 // spec doesn't mention that. Since we're doing strtr() anyway,
534 // and we don't need <> escaped here, we may as well not call
535 // htmlspecialchars().
536 // @todo FIXME: Verify that we actually need to
537 // escape \n\r\t here, and explain why, exactly.
539 // We could call Sanitizer::encodeAttribute() for this, but we
540 // don't because we're stubborn and like our marginal savings on
541 // byte size from not having to encode unnecessary quotes.
542 $map = array(
543 '&' => '&amp;',
544 '"' => '&quot;',
545 "\n" => '&#10;',
546 "\r" => '&#13;',
547 "\t" => '&#9;'
549 if ( $wgWellFormedXml ) {
550 // This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
551 // But reportedly it breaks some XML tools?
552 // @todo FIXME: Is this really true?
553 $map['<'] = '&lt;';
555 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
558 return $ret;
562 * Output a "<script>" tag with the given contents.
564 * @todo do some useful escaping as well, like if $contents contains
565 * literal "</script>" or (for XML) literal "]]>".
567 * @param string $contents JavaScript
568 * @return string Raw HTML
570 public static function inlineScript( $contents ) {
571 global $wgWellFormedXml;
573 $attrs = array();
575 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
576 $contents = "/*<![CDATA[*/$contents/*]]>*/";
579 return self::rawElement( 'script', $attrs, $contents );
583 * Output a "<script>" tag linking to the given URL, e.g.,
584 * "<script src=foo.js></script>".
586 * @param string $url
587 * @return string Raw HTML
589 public static function linkedScript( $url ) {
590 $attrs = array( 'src' => $url );
592 return self::element( 'script', $attrs );
596 * Output a "<style>" tag with the given contents for the given media type
597 * (if any). TODO: do some useful escaping as well, like if $contents
598 * contains literal "</style>" (admittedly unlikely).
600 * @param string $contents CSS
601 * @param string $media A media type string, like 'screen'
602 * @return string Raw HTML
604 public static function inlineStyle( $contents, $media = 'all' ) {
605 global $wgWellFormedXml;
607 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
608 $contents = "/*<![CDATA[*/$contents/*]]>*/";
611 return self::rawElement( 'style', array(
612 'type' => 'text/css',
613 'media' => $media,
614 ), $contents );
618 * Output a "<link rel=stylesheet>" linking to the given URL for the given
619 * media type (if any).
621 * @param string $url
622 * @param string $media A media type string, like 'screen'
623 * @return string Raw HTML
625 public static function linkedStyle( $url, $media = 'all' ) {
626 return self::element( 'link', array(
627 'rel' => 'stylesheet',
628 'href' => $url,
629 'type' => 'text/css',
630 'media' => $media,
631 ) );
635 * Convenience function to produce an "<input>" element. This supports the
636 * new HTML5 input types and attributes.
638 * @param string $name Name attribute
639 * @param array $value Value attribute
640 * @param string $type Type attribute
641 * @param array $attribs Associative array of miscellaneous extra
642 * attributes, passed to Html::element()
643 * @return string Raw HTML
645 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
646 $attribs['type'] = $type;
647 $attribs['value'] = $value;
648 $attribs['name'] = $name;
650 return self::element( 'input', $attribs );
654 * Convenience function to produce an input element with type=hidden
656 * @param string $name Name attribute
657 * @param string $value Value attribute
658 * @param array $attribs Associative array of miscellaneous extra
659 * attributes, passed to Html::element()
660 * @return string Raw HTML
662 public static function hidden( $name, $value, $attribs = array() ) {
663 return self::input( $name, $value, 'hidden', $attribs );
667 * Convenience function to produce a <textarea> element.
669 * This supports leaving out the cols= and rows= which Xml requires and are
670 * required by HTML4/XHTML but not required by HTML5.
672 * @param string $name Name attribute
673 * @param string $value Value attribute
674 * @param array $attribs Associative array of miscellaneous extra
675 * attributes, passed to Html::element()
676 * @return string Raw HTML
678 public static function textarea( $name, $value = '', $attribs = array() ) {
679 $attribs['name'] = $name;
681 if ( substr( $value, 0, 1 ) == "\n" ) {
682 // Workaround for bug 12130: browsers eat the initial newline
683 // assuming that it's just for show, but they do keep the later
684 // newlines, which we may want to preserve during editing.
685 // Prepending a single newline
686 $spacedValue = "\n" . $value;
687 } else {
688 $spacedValue = $value;
690 return self::element( 'textarea', $attribs, $spacedValue );
694 * Build a drop-down box for selecting a namespace
696 * @param array $params Params to set.
697 * - selected: [optional] Id of namespace which should be pre-selected
698 * - all: [optional] Value of item for "all namespaces". If null or unset,
699 * no "<option>" is generated to select all namespaces.
700 * - label: text for label to add before the field.
701 * - exclude: [optional] Array of namespace ids to exclude.
702 * - disable: [optional] Array of namespace ids for which the option should
703 * be disabled in the selector.
704 * @param array $selectAttribs HTML attributes for the generated select element.
705 * - id: [optional], default: 'namespace'.
706 * - name: [optional], default: 'namespace'.
707 * @return string HTML code to select a namespace.
709 public static function namespaceSelector( array $params = array(),
710 array $selectAttribs = array()
712 global $wgContLang;
714 ksort( $selectAttribs );
716 // Is a namespace selected?
717 if ( isset( $params['selected'] ) ) {
718 // If string only contains digits, convert to clean int. Selected could also
719 // be "all" or "" etc. which needs to be left untouched.
720 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
721 // and returns false for already clean ints. Use regex instead..
722 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
723 $params['selected'] = intval( $params['selected'] );
725 // else: leaves it untouched for later processing
726 } else {
727 $params['selected'] = '';
730 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
731 $params['exclude'] = array();
733 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
734 $params['disable'] = array();
737 // Associative array between option-values and option-labels
738 $options = array();
740 if ( isset( $params['all'] ) ) {
741 // add an option that would let the user select all namespaces.
742 // Value is provided by user, the name shown is localized for the user.
743 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
745 // Add all namespaces as options (in the content language)
746 $options += $wgContLang->getFormattedNamespaces();
748 // Convert $options to HTML and filter out namespaces below 0
749 $optionsHtml = array();
750 foreach ( $options as $nsId => $nsName ) {
751 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
752 continue;
754 if ( $nsId === NS_MAIN ) {
755 // For other namespaces use use the namespace prefix as label, but for
756 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
757 $nsName = wfMessage( 'blanknamespace' )->text();
758 } elseif ( is_int( $nsId ) ) {
759 $nsName = $wgContLang->convertNamespace( $nsId );
761 $optionsHtml[] = Html::element(
762 'option', array(
763 'disabled' => in_array( $nsId, $params['disable'] ),
764 'value' => $nsId,
765 'selected' => $nsId === $params['selected'],
766 ), $nsName
770 if ( !array_key_exists( 'id', $selectAttribs ) ) {
771 $selectAttribs['id'] = 'namespace';
774 if ( !array_key_exists( 'name', $selectAttribs ) ) {
775 $selectAttribs['name'] = 'namespace';
778 $ret = '';
779 if ( isset( $params['label'] ) ) {
780 $ret .= Html::element(
781 'label', array(
782 'for' => isset( $selectAttribs['id'] ) ? $selectAttribs['id'] : null,
783 ), $params['label']
784 ) . '&#160;';
787 // Wrap options in a <select>
788 $ret .= Html::openElement( 'select', $selectAttribs )
789 . "\n"
790 . implode( "\n", $optionsHtml )
791 . "\n"
792 . Html::closeElement( 'select' );
794 return $ret;
798 * Constructs the opening html-tag with necessary doctypes depending on
799 * global variables.
801 * @param array $attribs Associative array of miscellaneous extra
802 * attributes, passed to Html::element() of html tag.
803 * @return string Raw HTML
805 public static function htmlHeader( $attribs = array() ) {
806 $ret = '';
808 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
810 $isXHTML = self::isXmlMimeType( $wgMimeType );
812 if ( $isXHTML ) { // XHTML5
813 // XML mimetyped markup should have an xml header.
814 // However a DOCTYPE is not needed.
815 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
817 // Add the standard xmlns
818 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
820 // And support custom namespaces
821 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
822 $attribs["xmlns:$tag"] = $ns;
824 } else { // HTML5
825 // DOCTYPE
826 $ret .= "<!DOCTYPE html>\n";
829 if ( $wgHtml5Version ) {
830 $attribs['version'] = $wgHtml5Version;
833 $html = Html::openElement( 'html', $attribs );
835 if ( $html ) {
836 $html .= "\n";
839 $ret .= $html;
841 return $ret;
845 * Determines if the given mime type is xml.
847 * @param string $mimetype MimeType
848 * @return bool
850 public static function isXmlMimeType( $mimetype ) {
851 # http://www.whatwg.org/html/infrastructure.html#xml-mime-type
852 # * text/xml
853 # * application/xml
854 # * Any mimetype with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
855 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
859 * Get HTML for an info box with an icon.
861 * @param string $text Wikitext, get this with wfMessage()->plain()
862 * @param string $icon Icon name, file in skins/common/images
863 * @param string $alt Alternate text for the icon
864 * @param string $class Additional class name to add to the wrapper div
865 * @param bool $useStylePath
867 * @return string
869 static function infoBox( $text, $icon, $alt, $class = false, $useStylePath = true ) {
870 global $wgStylePath;
872 if ( $useStylePath ) {
873 $icon = $wgStylePath . '/common/images/' . $icon;
876 $s = Html::openElement( 'div', array( 'class' => "mw-infobox $class" ) );
878 $s .= Html::openElement( 'div', array( 'class' => 'mw-infobox-left' ) ) .
879 Html::element( 'img',
880 array(
881 'src' => $icon,
882 'alt' => $alt,
885 Html::closeElement( 'div' );
887 $s .= Html::openElement( 'div', array( 'class' => 'mw-infobox-right' ) ) .
888 $text .
889 Html::closeElement( 'div' );
890 $s .= Html::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
892 $s .= Html::closeElement( 'div' );
894 $s .= Html::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
896 return $s;
900 * Generate a srcset attribute value from an array mapping pixel densities
901 * to URLs. Note that srcset supports width and height values as well, which
902 * are not used here.
904 * @param array $urls
905 * @return string
907 static function srcSet( $urls ) {
908 $candidates = array();
909 foreach ( $urls as $density => $url ) {
910 // Image candidate syntax per current whatwg live spec, 2012-09-23:
911 // http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
912 $candidates[] = "{$url} {$density}x";
914 return implode( ", ", $candidates );