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 * $wgMimeType: If this is set to an xml MIME type then output should be
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 * Modifies a set of attributes meant for button elements
106 * and apply a set of default attributes when $wgUseMediaWikiUIEverywhere enabled.
107 * @param array $modifiers to add to the button
108 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
109 * @return array $attrs A modified attribute array
111 public static function buttonAttributes( $attrs, $modifiers = array() ) {
112 global $wgUseMediaWikiUIEverywhere;
113 if ( $wgUseMediaWikiUIEverywhere ) {
114 if ( isset( $attrs['class'] ) ) {
115 if ( is_array( $attrs['class'] ) ) {
116 $attrs['class'][] = 'mw-ui-button';
117 $attrs = array_merge( $attrs, $modifiers );
118 // ensure compatibility with Xml
119 $attrs['class'] = implode( ' ', $attrs['class'] );
121 $attrs['class'] .= ' mw-ui-button ' . implode( ' ', $modifiers );
124 $attrs['class'] = array( 'mw-ui-button' );
125 // ensure compatibility with Xml
126 $attrs['class'] = implode( ' ', array_merge( $attrs['class'], $modifiers ) );
133 * Modifies a set of attributes meant for text input elements
134 * and apply a set of default attributes.
135 * Removes size attribute when $wgUseMediaWikiUIEverywhere enabled.
136 * @param array $attrs An attribute array.
137 * @return array $attrs A modified attribute array
139 public static function getTextInputAttributes( $attrs ) {
140 global $wgUseMediaWikiUIEverywhere;
144 if ( isset( $attrs['class'] ) ) {
145 if ( is_array( $attrs['class'] ) ) {
146 $attrs['class'][] = 'mw-ui-input';
148 $attrs['class'] .= ' mw-ui-input';
151 $attrs['class'] = 'mw-ui-input';
153 if ( $wgUseMediaWikiUIEverywhere ) {
154 // Note that size can effect the desired width rendering of mw-ui-input elements
155 // so it is removed. Left intact when mediawiki ui not enabled.
156 unset( $attrs['size'] );
162 * Returns an HTML link element in a string styled as a button (when $wgUseMediaWikiUIEverywhere is enabled).
164 * @param string $contents The raw HTML contents of the element: *not*
166 * @param array $attrs Associative array of attributes, e.g., array(
167 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
168 * further documentation.
169 * @param array $modifiers to add to the button
170 * @see http://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
171 * @return string Raw HTML
173 public static function linkButton( $contents, $attrs, $modifiers = array() ) {
174 return Html
::element( 'a',
175 self
::buttonAttributes( $attrs, $modifiers ),
181 * Returns an HTML link element in a string styled as a button (when $wgUseMediaWikiUIEverywhere is enabled).
183 * @param string $contents The raw HTML contents of the element: *not*
185 * @param array $attrs Associative array of attributes, e.g., array(
186 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
187 * further documentation.
188 * @param array $modifiers to add to the button
189 * @see http://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
190 * @return string Raw HTML
192 public static function submitButton( $contents, $attrs, $modifiers = array() ) {
193 $attrs['type'] = 'submit';
194 $attrs['value'] = $contents;
195 return Html
::element( 'input', self
::buttonAttributes( $attrs, $modifiers ) );
199 * Returns an HTML element in a string. The major advantage here over
200 * manually typing out the HTML is that it will escape all attribute
201 * values. If you're hardcoding all the attributes, or there are none, you
202 * should probably just type out the html element yourself.
204 * This is quite similar to Xml::tags(), but it implements some useful
205 * HTML-specific logic. For instance, there is no $allowShortTag
206 * parameter: the closing tag is magically omitted if $element has an empty
207 * content model. If $wgWellFormedXml is false, then a few bytes will be
208 * shaved off the HTML output as well.
210 * @param string $element The element's name, e.g., 'a'
211 * @param array $attribs Associative array of attributes, e.g., array(
212 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
213 * further documentation.
214 * @param string $contents The raw HTML contents of the element: *not*
216 * @return string Raw HTML
218 public static function rawElement( $element, $attribs = array(), $contents = '' ) {
219 global $wgWellFormedXml;
220 $start = self
::openElement( $element, $attribs );
221 if ( in_array( $element, self
::$voidElements ) ) {
222 if ( $wgWellFormedXml ) {
224 return substr( $start, 0, -1 ) . ' />';
228 return "$start$contents" . self
::closeElement( $element );
233 * Identical to rawElement(), but HTML-escapes $contents (like
236 * @param string $element
237 * @param array $attribs
238 * @param string $contents
242 public static function element( $element, $attribs = array(), $contents = '' ) {
243 return self
::rawElement( $element, $attribs, strtr( $contents, array(
244 // There's no point in escaping quotes, >, etc. in the contents of
252 * Identical to rawElement(), but has no third parameter and omits the end
253 * tag (and the self-closing '/' in XML mode for empty elements).
255 * @param string $element
256 * @param array $attribs
260 public static function openElement( $element, $attribs = array() ) {
261 global $wgWellFormedXml;
262 $attribs = (array)$attribs;
263 // This is not required in HTML5, but let's do it anyway, for
264 // consistency and better compression.
265 $element = strtolower( $element );
267 // In text/html, initial <html> and <head> tags can be omitted under
268 // pretty much any sane circumstances, if they have no attributes. See:
269 // <http://www.whatwg.org/html/syntax.html#optional-tags>
270 if ( !$wgWellFormedXml && !$attribs && in_array( $element, array( 'html', 'head' ) ) ) {
274 // Remove invalid input types
275 if ( $element == 'input' ) {
303 if ( isset( $attribs['type'] ) && !in_array( $attribs['type'], $validTypes ) ) {
304 unset( $attribs['type'] );
308 // According to standard the default type for <button> elements is "submit".
309 // Depending on compatibility mode IE might use "button", instead.
310 // We enforce the standard "submit".
311 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
312 $attribs['type'] = 'submit';
315 return "<$element" . self
::expandAttributes(
316 self
::dropDefaults( $element, $attribs ) ) . '>';
320 * Returns "</$element>"
323 * @param string $element Name of the element, e.g., 'a'
324 * @return string A closing tag
326 public static function closeElement( $element ) {
327 $element = strtolower( $element );
329 return "</$element>";
333 * Given an element name and an associative array of element attributes,
334 * return an array that is functionally identical to the input array, but
335 * possibly smaller. In particular, attributes might be stripped if they
336 * are given their default values.
338 * This method is not guaranteed to remove all redundant attributes, only
339 * some common ones and some others selected arbitrarily at random. It
340 * only guarantees that the output array should be functionally identical
341 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
343 * @param string $element Name of the element, e.g., 'a'
344 * @param array $attribs Associative array of attributes, e.g., array(
345 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
346 * further documentation.
347 * @return array An array of attributes functionally identical to $attribs
349 private static function dropDefaults( $element, $attribs ) {
351 // Whenever altering this array, please provide a covering test case
352 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
353 static $attribDefaults = array(
354 'area' => array( 'shape' => 'rect' ),
356 'formaction' => 'GET',
357 'formenctype' => 'application/x-www-form-urlencoded',
363 'command' => array( 'type' => 'command' ),
366 'autocomplete' => 'on',
367 'enctype' => 'application/x-www-form-urlencoded',
370 'formaction' => 'GET',
373 'keygen' => array( 'keytype' => 'rsa' ),
374 'link' => array( 'media' => 'all' ),
375 'menu' => array( 'type' => 'list' ),
376 // Note: the use of text/javascript here instead of other JavaScript
377 // MIME types follows the HTML5 spec.
378 'script' => array( 'type' => 'text/javascript' ),
381 'type' => 'text/css',
383 'textarea' => array( 'wrap' => 'soft' ),
386 $element = strtolower( $element );
388 foreach ( $attribs as $attrib => $value ) {
389 $lcattrib = strtolower( $attrib );
390 if ( is_array( $value ) ) {
391 $value = implode( ' ', $value );
393 $value = strval( $value );
396 // Simple checks using $attribDefaults
397 if ( isset( $attribDefaults[$element][$lcattrib] )
398 && $attribDefaults[$element][$lcattrib] == $value
400 unset( $attribs[$attrib] );
403 if ( $lcattrib == 'class' && $value == '' ) {
404 unset( $attribs[$attrib] );
408 // More subtle checks
409 if ( $element === 'link'
410 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
412 unset( $attribs['type'] );
414 if ( $element === 'input' ) {
415 $type = isset( $attribs['type'] ) ?
$attribs['type'] : null;
416 $value = isset( $attribs['value'] ) ?
$attribs['value'] : null;
417 if ( $type === 'checkbox' ||
$type === 'radio' ) {
418 // The default value for checkboxes and radio buttons is 'on'
419 // not ''. By stripping value="" we break radio boxes that
420 // actually wants empty values.
421 if ( $value === 'on' ) {
422 unset( $attribs['value'] );
424 } elseif ( $type === 'submit' ) {
425 // The default value for submit appears to be "Submit" but
426 // let's not bother stripping out localized text that matches
429 // The default value for nearly every other field type is ''
430 // The 'range' and 'color' types use different defaults but
431 // stripping a value="" does not hurt them.
432 if ( $value === '' ) {
433 unset( $attribs['value'] );
437 if ( $element === 'select' && isset( $attribs['size'] ) ) {
438 if ( in_array( 'multiple', $attribs )
439 ||
( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
442 if ( strval( $attribs['size'] ) == '4' ) {
443 unset( $attribs['size'] );
447 if ( strval( $attribs['size'] ) == '1' ) {
448 unset( $attribs['size'] );
457 * Given an associative array of element attributes, generate a string
458 * to stick after the element name in HTML output. Like array( 'href' =>
459 * 'http://www.mediawiki.org/' ) becomes something like
460 * ' href="http://www.mediawiki.org"'. Again, this is like
461 * Xml::expandAttributes(), but it implements some HTML-specific logic.
462 * For instance, it will omit quotation marks if $wgWellFormedXml is false,
463 * and will treat boolean attributes specially.
465 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
466 * values are allowed as well, which will automagically be normalized
467 * and converted to a space-separated string. In addition to a numerical
468 * array, the attribute value may also be an associative array. See the
469 * example below for how that works.
471 * @par Numerical array
473 * Html::element( 'em', array(
474 * 'class' => array( 'foo', 'bar' )
476 * // gives '<em class="foo bar"></em>'
479 * @par Associative array
481 * Html::element( 'em', array(
482 * 'class' => array( 'foo', 'bar', 'foo' => false, 'quux' => true )
484 * // gives '<em class="bar quux"></em>'
487 * @param array $attribs Associative array of attributes, e.g., array(
488 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
489 * A value of false means to omit the attribute. For boolean attributes,
490 * you can omit the key, e.g., array( 'checked' ) instead of
491 * array( 'checked' => 'checked' ) or such.
493 * @throws MWException If an attribute that doesn't allow lists is set to an array
494 * @return string HTML fragment that goes between element name and '>'
495 * (starting with a space if at least one attribute is output)
497 public static function expandAttributes( $attribs ) {
498 global $wgWellFormedXml;
501 $attribs = (array)$attribs;
502 foreach ( $attribs as $key => $value ) {
503 // Support intuitive array( 'checked' => true/false ) form
504 if ( $value === false ||
is_null( $value ) ) {
508 // For boolean attributes, support array( 'foo' ) instead of
509 // requiring array( 'foo' => 'meaningless' ).
510 if ( is_int( $key ) && in_array( strtolower( $value ), self
::$boolAttribs ) ) {
514 // Not technically required in HTML5 but we'd like consistency
515 // and better compression anyway.
516 $key = strtolower( $key );
518 // Bug 23769: Blacklist all form validation attributes for now. Current
519 // (June 2010) WebKit has no UI, so the form just refuses to submit
520 // without telling the user why, which is much worse than failing
521 // server-side validation. Opera is the only other implementation at
522 // this time, and has ugly UI, so just kill the feature entirely until
523 // we have at least one good implementation.
525 // As the default value of "1" for "step" rejects decimal
526 // numbers to be entered in 'type="number"' fields, allow
527 // the special case 'step="any"'.
529 if ( in_array( $key, array( 'max', 'min', 'pattern', 'required' ) )
530 ||
$key === 'step' && $value !== 'any' ) {
534 // http://www.w3.org/TR/html401/index/attributes.html ("space-separated")
535 // http://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
536 $spaceSeparatedListAttributes = array(
537 'class', // html4, html5
538 'accesskey', // as of html5, multiple space-separated values allowed
539 // html4-spec doesn't document rel= as space-separated
540 // but has been used like that and is now documented as such
541 // in the html5-spec.
545 // Specific features for attributes that allow a list of space-separated values
546 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
547 // Apply some normalization and remove duplicates
549 // Convert into correct array. Array can contain space-separated
550 // values. Implode/explode to get those into the main array as well.
551 if ( is_array( $value ) ) {
552 // If input wasn't an array, we can skip this step
554 foreach ( $value as $k => $v ) {
555 if ( is_string( $v ) ) {
556 // String values should be normal `array( 'foo' )`
558 if ( !isset( $value[$v] ) ) {
559 // As a special case don't set 'foo' if a
560 // separate 'foo' => true/false exists in the array
561 // keys should be authoritative
565 // If the value is truthy but not a string this is likely
566 // an array( 'foo' => true ), falsy values don't add strings
570 $value = implode( ' ', $newValue );
572 $value = explode( ' ', $value );
574 // Normalize spacing by fixing up cases where people used
575 // more than 1 space and/or a trailing/leading space
576 $value = array_diff( $value, array( '', ' ' ) );
578 // Remove duplicates and create the string
579 $value = implode( ' ', array_unique( $value ) );
580 } elseif ( is_array( $value ) ) {
581 throw new MWException( "HTML attribute $key can not contain a list of values" );
584 // See the "Attributes" section in the HTML syntax part of HTML5,
585 // 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
586 // marks omitted, but not all. (Although a literal " is not
587 // permitted, we don't check for that, since it will be escaped
590 // See also research done on further characters that need to be
591 // escaped: http://code.google.com/p/html5lib/issues/detail?id=93
592 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
593 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
594 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
595 if ( $wgWellFormedXml ||
$value === '' ||
preg_match( "![$badChars]!u", $value ) ) {
601 if ( in_array( $key, self
::$boolAttribs ) ) {
602 // In HTML5, we can leave the value empty. If we don't need
603 // well-formed XML, we can omit the = entirely.
604 if ( !$wgWellFormedXml ) {
607 $ret .= " $key=\"\"";
610 // Apparently we need to entity-encode \n, \r, \t, although the
611 // spec doesn't mention that. Since we're doing strtr() anyway,
612 // and we don't need <> escaped here, we may as well not call
613 // htmlspecialchars().
614 // @todo FIXME: Verify that we actually need to
615 // escape \n\r\t here, and explain why, exactly.
617 // We could call Sanitizer::encodeAttribute() for this, but we
618 // don't because we're stubborn and like our marginal savings on
619 // byte size from not having to encode unnecessary quotes.
627 if ( $wgWellFormedXml ) {
628 // This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
629 // But reportedly it breaks some XML tools?
630 // @todo FIXME: Is this really true?
633 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
640 * Output a "<script>" tag with the given contents.
642 * @todo do some useful escaping as well, like if $contents contains
643 * literal "</script>" or (for XML) literal "]]>".
645 * @param string $contents JavaScript
646 * @return string Raw HTML
648 public static function inlineScript( $contents ) {
649 global $wgWellFormedXml;
653 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
654 $contents = "/*<![CDATA[*/$contents/*]]>*/";
657 return self
::rawElement( 'script', $attrs, $contents );
661 * Output a "<script>" tag linking to the given URL, e.g.,
662 * "<script src=foo.js></script>".
665 * @return string Raw HTML
667 public static function linkedScript( $url ) {
668 $attrs = array( 'src' => $url );
670 return self
::element( 'script', $attrs );
674 * Output a "<style>" tag with the given contents for the given media type
675 * (if any). TODO: do some useful escaping as well, like if $contents
676 * contains literal "</style>" (admittedly unlikely).
678 * @param string $contents CSS
679 * @param string $media A media type string, like 'screen'
680 * @return string Raw HTML
682 public static function inlineStyle( $contents, $media = 'all' ) {
683 global $wgWellFormedXml;
685 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
686 $contents = "/*<![CDATA[*/$contents/*]]>*/";
689 return self
::rawElement( 'style', array(
690 'type' => 'text/css',
696 * Output a "<link rel=stylesheet>" linking to the given URL for the given
697 * media type (if any).
700 * @param string $media A media type string, like 'screen'
701 * @return string Raw HTML
703 public static function linkedStyle( $url, $media = 'all' ) {
704 return self
::element( 'link', array(
705 'rel' => 'stylesheet',
707 'type' => 'text/css',
713 * Convenience function to produce an "<input>" element. This supports the
714 * new HTML5 input types and attributes.
716 * @param string $name Name attribute
717 * @param array $value Value attribute
718 * @param string $type Type attribute
719 * @param array $attribs Associative array of miscellaneous extra
720 * attributes, passed to Html::element()
721 * @return string Raw HTML
723 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
724 $attribs['type'] = $type;
725 $attribs['value'] = $value;
726 $attribs['name'] = $name;
727 if ( in_array( $type, array( 'text', 'search', 'email', 'password', 'number' ) ) ) {
728 $attribs = Html
::getTextInputAttributes( $attribs );
730 return self
::element( 'input', $attribs );
734 * Convenience function to produce a checkbox (input element with type=checkbox)
736 * @param string $name Name attribute
737 * @param bool $checked Whether the checkbox is checked or not
738 * @param array $attribs Array of additional attributes
741 public static function check( $name, $checked = false, array $attribs = array() ) {
742 if ( isset( $attribs['value'] ) ) {
743 $value = $attribs['value'];
744 unset( $attribs['value'] );
750 $attribs[] = 'checked';
753 return self
::input( $name, $value, 'checkbox', $attribs );
757 * Convenience function to produce a checkbox (input element with type=checkbox)
759 * @param string $name Name attribute
760 * @param bool $checked Whether the checkbox is checked or not
761 * @param array $attribs Array of additional attributes
764 public static function radio( $name, $checked = false, array $attribs = array() ) {
765 if ( isset( $attribs['value'] ) ) {
766 $value = $attribs['value'];
767 unset( $attribs['value'] );
773 $attribs[] = 'checked';
776 return self
::input( $name, $value, 'radio', $attribs );
780 * Convenience function for generating a label for inputs.
782 * @param string $label Contents of the label
783 * @param string $id ID of the element being labeled
784 * @param array $attribs Additional attributes
787 public static function label( $label, $id, array $attribs = array() ) {
791 return self
::element( 'label', $attribs, $label );
795 * Convenience function to produce an input element with type=hidden
797 * @param string $name Name attribute
798 * @param string $value Value attribute
799 * @param array $attribs Associative array of miscellaneous extra
800 * attributes, passed to Html::element()
801 * @return string Raw HTML
803 public static function hidden( $name, $value, $attribs = array() ) {
804 return self
::input( $name, $value, 'hidden', $attribs );
808 * Convenience function to produce a <textarea> element.
810 * This supports leaving out the cols= and rows= which Xml requires and are
811 * required by HTML4/XHTML but not required by HTML5.
813 * @param string $name Name attribute
814 * @param string $value Value attribute
815 * @param array $attribs Associative array of miscellaneous extra
816 * attributes, passed to Html::element()
817 * @return string Raw HTML
819 public static function textarea( $name, $value = '', $attribs = array() ) {
820 $attribs['name'] = $name;
822 if ( substr( $value, 0, 1 ) == "\n" ) {
823 // Workaround for bug 12130: browsers eat the initial newline
824 // assuming that it's just for show, but they do keep the later
825 // newlines, which we may want to preserve during editing.
826 // Prepending a single newline
827 $spacedValue = "\n" . $value;
829 $spacedValue = $value;
831 return self
::element( 'textarea', Html
::getTextInputAttributes( $attribs ), $spacedValue );
835 * Build a drop-down box for selecting a namespace
837 * @param array $params Params to set.
838 * - selected: [optional] Id of namespace which should be pre-selected
839 * - all: [optional] Value of item for "all namespaces". If null or unset,
840 * no "<option>" is generated to select all namespaces.
841 * - label: text for label to add before the field.
842 * - exclude: [optional] Array of namespace ids to exclude.
843 * - disable: [optional] Array of namespace ids for which the option should
844 * be disabled in the selector.
845 * @param array $selectAttribs HTML attributes for the generated select element.
846 * - id: [optional], default: 'namespace'.
847 * - name: [optional], default: 'namespace'.
848 * @return string HTML code to select a namespace.
850 public static function namespaceSelector( array $params = array(),
851 array $selectAttribs = array()
855 ksort( $selectAttribs );
857 // Is a namespace selected?
858 if ( isset( $params['selected'] ) ) {
859 // If string only contains digits, convert to clean int. Selected could also
860 // be "all" or "" etc. which needs to be left untouched.
861 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
862 // and returns false for already clean ints. Use regex instead..
863 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
864 $params['selected'] = intval( $params['selected'] );
866 // else: leaves it untouched for later processing
868 $params['selected'] = '';
871 if ( !isset( $params['exclude'] ) ||
!is_array( $params['exclude'] ) ) {
872 $params['exclude'] = array();
874 if ( !isset( $params['disable'] ) ||
!is_array( $params['disable'] ) ) {
875 $params['disable'] = array();
878 // Associative array between option-values and option-labels
881 if ( isset( $params['all'] ) ) {
882 // add an option that would let the user select all namespaces.
883 // Value is provided by user, the name shown is localized for the user.
884 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
886 // Add all namespaces as options (in the content language)
887 $options +
= $wgContLang->getFormattedNamespaces();
889 // Convert $options to HTML and filter out namespaces below 0
890 $optionsHtml = array();
891 foreach ( $options as $nsId => $nsName ) {
892 if ( $nsId < NS_MAIN ||
in_array( $nsId, $params['exclude'] ) ) {
895 if ( $nsId === NS_MAIN
) {
896 // For other namespaces use the namespace prefix as label, but for
897 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
898 $nsName = wfMessage( 'blanknamespace' )->text();
899 } elseif ( is_int( $nsId ) ) {
900 $nsName = $wgContLang->convertNamespace( $nsId );
902 $optionsHtml[] = Html
::element(
904 'disabled' => in_array( $nsId, $params['disable'] ),
906 'selected' => $nsId === $params['selected'],
911 if ( !array_key_exists( 'id', $selectAttribs ) ) {
912 $selectAttribs['id'] = 'namespace';
915 if ( !array_key_exists( 'name', $selectAttribs ) ) {
916 $selectAttribs['name'] = 'namespace';
920 if ( isset( $params['label'] ) ) {
921 $ret .= Html
::element(
923 'for' => isset( $selectAttribs['id'] ) ?
$selectAttribs['id'] : null,
928 // Wrap options in a <select>
929 $ret .= Html
::openElement( 'select', $selectAttribs )
931 . implode( "\n", $optionsHtml )
933 . Html
::closeElement( 'select' );
939 * Constructs the opening html-tag with necessary doctypes depending on
942 * @param array $attribs Associative array of miscellaneous extra
943 * attributes, passed to Html::element() of html tag.
944 * @return string Raw HTML
946 public static function htmlHeader( $attribs = array() ) {
949 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
951 $isXHTML = self
::isXmlMimeType( $wgMimeType );
953 if ( $isXHTML ) { // XHTML5
954 // XML MIME-typed markup should have an xml header.
955 // However a DOCTYPE is not needed.
956 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
958 // Add the standard xmlns
959 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
961 // And support custom namespaces
962 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
963 $attribs["xmlns:$tag"] = $ns;
967 $ret .= "<!DOCTYPE html>\n";
970 if ( $wgHtml5Version ) {
971 $attribs['version'] = $wgHtml5Version;
974 $html = Html
::openElement( 'html', $attribs );
986 * Determines if the given MIME type is xml.
988 * @param string $mimetype MIME type
991 public static function isXmlMimeType( $mimetype ) {
992 # http://www.whatwg.org/html/infrastructure.html#xml-mime-type
995 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
996 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1000 * Get HTML for an info box with an icon.
1002 * @param string $text Wikitext, get this with wfMessage()->plain()
1003 * @param string $icon Path to icon file (used as 'src' attribute)
1004 * @param string $alt Alternate text for the icon
1005 * @param string $class Additional class name to add to the wrapper div
1009 static function infoBox( $text, $icon, $alt, $class = false ) {
1010 $s = Html
::openElement( 'div', array( 'class' => "mw-infobox $class" ) );
1012 $s .= Html
::openElement( 'div', array( 'class' => 'mw-infobox-left' ) ) .
1013 Html
::element( 'img',
1019 Html
::closeElement( 'div' );
1021 $s .= Html
::openElement( 'div', array( 'class' => 'mw-infobox-right' ) ) .
1023 Html
::closeElement( 'div' );
1024 $s .= Html
::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
1026 $s .= Html
::closeElement( 'div' );
1028 $s .= Html
::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
1034 * Generate a srcset attribute value from an array mapping pixel densities
1035 * to URLs. Note that srcset supports width and height values as well, which
1036 * are not used here.
1038 * @param array $urls
1041 static function srcSet( $urls ) {
1042 $candidates = array();
1043 foreach ( $urls as $density => $url ) {
1044 // Image candidate syntax per current whatwg live spec, 2012-09-23:
1045 // http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
1046 $candidates[] = "{$url} {$density}x";
1048 return implode( ", ", $candidates );