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
271 && in_array( $element, array( 'html', 'head' ) ) ) {
275 // Remove invalid input types
276 if ( $element == 'input' ) {
304 if ( isset( $attribs['type'] )
305 && !in_array( $attribs['type'], $validTypes ) ) {
306 unset( $attribs['type'] );
310 // According to standard the default type for <button> elements is "submit".
311 // Depending on compatibility mode IE might use "button", instead.
312 // We enforce the standard "submit".
313 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
314 $attribs['type'] = 'submit';
317 return "<$element" . self
::expandAttributes(
318 self
::dropDefaults( $element, $attribs ) ) . '>';
322 * Returns "</$element>"
325 * @param string $element Name of the element, e.g., 'a'
326 * @return string A closing tag
328 public static function closeElement( $element ) {
329 $element = strtolower( $element );
331 return "</$element>";
335 * Given an element name and an associative array of element attributes,
336 * return an array that is functionally identical to the input array, but
337 * possibly smaller. In particular, attributes might be stripped if they
338 * are given their default values.
340 * This method is not guaranteed to remove all redundant attributes, only
341 * some common ones and some others selected arbitrarily at random. It
342 * only guarantees that the output array should be functionally identical
343 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
345 * @param string $element Name of the element, e.g., 'a'
346 * @param array $attribs Associative array of attributes, e.g., array(
347 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
348 * further documentation.
349 * @return array An array of attributes functionally identical to $attribs
351 private static function dropDefaults( $element, $attribs ) {
353 // Whenever altering this array, please provide a covering test case
354 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
355 static $attribDefaults = array(
356 'area' => array( 'shape' => 'rect' ),
358 'formaction' => 'GET',
359 'formenctype' => 'application/x-www-form-urlencoded',
365 'command' => array( 'type' => 'command' ),
368 'autocomplete' => 'on',
369 'enctype' => 'application/x-www-form-urlencoded',
372 'formaction' => 'GET',
375 'keygen' => array( 'keytype' => 'rsa' ),
376 'link' => array( 'media' => 'all' ),
377 'menu' => array( 'type' => 'list' ),
378 // Note: the use of text/javascript here instead of other JavaScript
379 // MIME types follows the HTML5 spec.
380 'script' => array( 'type' => 'text/javascript' ),
383 'type' => 'text/css',
385 'textarea' => array( 'wrap' => 'soft' ),
388 $element = strtolower( $element );
390 foreach ( $attribs as $attrib => $value ) {
391 $lcattrib = strtolower( $attrib );
392 if ( is_array( $value ) ) {
393 $value = implode( ' ', $value );
395 $value = strval( $value );
398 // Simple checks using $attribDefaults
399 if ( isset( $attribDefaults[$element][$lcattrib] ) &&
400 $attribDefaults[$element][$lcattrib] == $value ) {
401 unset( $attribs[$attrib] );
404 if ( $lcattrib == 'class' && $value == '' ) {
405 unset( $attribs[$attrib] );
409 // More subtle checks
410 if ( $element === 'link' && isset( $attribs['type'] )
411 && 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' ).
511 && in_array( strtolower( $value ), self
::$boolAttribs ) ) {
515 // Not technically required in HTML5 but we'd like consistency
516 // and better compression anyway.
517 $key = strtolower( $key );
519 // Bug 23769: Blacklist all form validation attributes for now. Current
520 // (June 2010) WebKit has no UI, so the form just refuses to submit
521 // without telling the user why, which is much worse than failing
522 // server-side validation. Opera is the only other implementation at
523 // this time, and has ugly UI, so just kill the feature entirely until
524 // we have at least one good implementation.
526 // As the default value of "1" for "step" rejects decimal
527 // numbers to be entered in 'type="number"' fields, allow
528 // the special case 'step="any"'.
530 if ( in_array( $key, array( 'max', 'min', 'pattern', 'required' ) )
531 ||
$key === 'step' && $value !== 'any' ) {
535 // http://www.w3.org/TR/html401/index/attributes.html ("space-separated")
536 // http://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
537 $spaceSeparatedListAttributes = array(
538 'class', // html4, html5
539 'accesskey', // as of html5, multiple space-separated values allowed
540 // html4-spec doesn't document rel= as space-separated
541 // but has been used like that and is now documented as such
542 // in the html5-spec.
546 // Specific features for attributes that allow a list of space-separated values
547 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
548 // Apply some normalization and remove duplicates
550 // Convert into correct array. Array can contain space-separated
551 // values. Implode/explode to get those into the main array as well.
552 if ( is_array( $value ) ) {
553 // If input wasn't an array, we can skip this step
555 foreach ( $value as $k => $v ) {
556 if ( is_string( $v ) ) {
557 // String values should be normal `array( 'foo' )`
559 if ( !isset( $value[$v] ) ) {
560 // As a special case don't set 'foo' if a
561 // separate 'foo' => true/false exists in the array
562 // keys should be authoritative
566 // If the value is truthy but not a string this is likely
567 // an array( 'foo' => true ), falsy values don't add strings
571 $value = implode( ' ', $newValue );
573 $value = explode( ' ', $value );
575 // Normalize spacing by fixing up cases where people used
576 // more than 1 space and/or a trailing/leading space
577 $value = array_diff( $value, array( '', ' ' ) );
579 // Remove duplicates and create the string
580 $value = implode( ' ', array_unique( $value ) );
581 } elseif ( is_array( $value ) ) {
582 throw new MWException( "HTML attribute $key can not contain a list of values" );
585 // See the "Attributes" section in the HTML syntax part of HTML5,
586 // 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
587 // marks omitted, but not all. (Although a literal " is not
588 // permitted, we don't check for that, since it will be escaped
591 // See also research done on further characters that need to be
592 // escaped: http://code.google.com/p/html5lib/issues/detail?id=93
593 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
594 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
595 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
596 if ( $wgWellFormedXml ||
$value === ''
597 ||
preg_match( "![$badChars]!u", $value ) ) {
603 if ( in_array( $key, self
::$boolAttribs ) ) {
604 // In HTML5, we can leave the value empty. If we don't need
605 // well-formed XML, we can omit the = entirely.
606 if ( !$wgWellFormedXml ) {
609 $ret .= " $key=\"\"";
612 // Apparently we need to entity-encode \n, \r, \t, although the
613 // spec doesn't mention that. Since we're doing strtr() anyway,
614 // and we don't need <> escaped here, we may as well not call
615 // htmlspecialchars().
616 // @todo FIXME: Verify that we actually need to
617 // escape \n\r\t here, and explain why, exactly.
619 // We could call Sanitizer::encodeAttribute() for this, but we
620 // don't because we're stubborn and like our marginal savings on
621 // byte size from not having to encode unnecessary quotes.
629 if ( $wgWellFormedXml ) {
630 // This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
631 // But reportedly it breaks some XML tools?
632 // @todo FIXME: Is this really true?
635 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
642 * Output a "<script>" tag with the given contents.
644 * @todo do some useful escaping as well, like if $contents contains
645 * literal "</script>" or (for XML) literal "]]>".
647 * @param string $contents JavaScript
648 * @return string Raw HTML
650 public static function inlineScript( $contents ) {
651 global $wgWellFormedXml;
655 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
656 $contents = "/*<![CDATA[*/$contents/*]]>*/";
659 return self
::rawElement( 'script', $attrs, $contents );
663 * Output a "<script>" tag linking to the given URL, e.g.,
664 * "<script src=foo.js></script>".
667 * @return string Raw HTML
669 public static function linkedScript( $url ) {
670 $attrs = array( 'src' => $url );
672 return self
::element( 'script', $attrs );
676 * Output a "<style>" tag with the given contents for the given media type
677 * (if any). TODO: do some useful escaping as well, like if $contents
678 * contains literal "</style>" (admittedly unlikely).
680 * @param string $contents CSS
681 * @param string $media A media type string, like 'screen'
682 * @return string Raw HTML
684 public static function inlineStyle( $contents, $media = 'all' ) {
685 global $wgWellFormedXml;
687 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
688 $contents = "/*<![CDATA[*/$contents/*]]>*/";
691 return self
::rawElement( 'style', array(
692 'type' => 'text/css',
698 * Output a "<link rel=stylesheet>" linking to the given URL for the given
699 * media type (if any).
702 * @param string $media A media type string, like 'screen'
703 * @return string Raw HTML
705 public static function linkedStyle( $url, $media = 'all' ) {
706 return self
::element( 'link', array(
707 'rel' => 'stylesheet',
709 'type' => 'text/css',
715 * Convenience function to produce an "<input>" element. This supports the
716 * new HTML5 input types and attributes.
718 * @param string $name Name attribute
719 * @param array $value Value attribute
720 * @param string $type Type attribute
721 * @param array $attribs Associative array of miscellaneous extra
722 * attributes, passed to Html::element()
723 * @return string Raw HTML
725 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
726 $attribs['type'] = $type;
727 $attribs['value'] = $value;
728 $attribs['name'] = $name;
729 if ( in_array( $type, array( 'text', 'search', 'email', 'password', 'number' ) ) ) {
730 $attribs = Html
::getTextInputAttributes( $attribs );
732 return self
::element( 'input', $attribs );
736 * Convenience function to produce a checkbox (input element with type=checkbox)
738 * @param string $name Name attribute
739 * @param bool $checked Whether the checkbox is checked or not
740 * @param array $attribs Array of additional attributes
743 public static function check( $name, $checked = false, array $attribs = array() ) {
744 if ( isset( $attribs['value'] ) ) {
745 $value = $attribs['value'];
746 unset( $attribs['value'] );
752 $attribs[] = 'checked';
755 return self
::input( $name, $value, 'checkbox', $attribs );
759 * Convenience function to produce a checkbox (input element with type=checkbox)
761 * @param string $name Name attribute
762 * @param bool $checked Whether the checkbox is checked or not
763 * @param array $attribs Array of additional attributes
766 public static function radio( $name, $checked = false, array $attribs = array() ) {
767 if ( isset( $attribs['value'] ) ) {
768 $value = $attribs['value'];
769 unset( $attribs['value'] );
775 $attribs[] = 'checked';
778 return self
::input( $name, $value, 'radio', $attribs );
782 * Convenience function for generating a label for inputs.
784 * @param string $label Contents of the label
785 * @param string $id ID of the element being labeled
786 * @param array $attribs Additional attributes
789 public static function label( $label, $id, array $attribs = array() ) {
793 return self
::element( 'label', $attribs, $label );
797 * Convenience function to produce an input element with type=hidden
799 * @param string $name Name attribute
800 * @param string $value Value attribute
801 * @param array $attribs Associative array of miscellaneous extra
802 * attributes, passed to Html::element()
803 * @return string Raw HTML
805 public static function hidden( $name, $value, $attribs = array() ) {
806 return self
::input( $name, $value, 'hidden', $attribs );
810 * Convenience function to produce a <textarea> element.
812 * This supports leaving out the cols= and rows= which Xml requires and are
813 * required by HTML4/XHTML but not required by HTML5.
815 * @param string $name Name attribute
816 * @param string $value Value attribute
817 * @param array $attribs Associative array of miscellaneous extra
818 * attributes, passed to Html::element()
819 * @return string Raw HTML
821 public static function textarea( $name, $value = '', $attribs = array() ) {
822 $attribs['name'] = $name;
824 if ( substr( $value, 0, 1 ) == "\n" ) {
825 // Workaround for bug 12130: browsers eat the initial newline
826 // assuming that it's just for show, but they do keep the later
827 // newlines, which we may want to preserve during editing.
828 // Prepending a single newline
829 $spacedValue = "\n" . $value;
831 $spacedValue = $value;
833 return self
::element( 'textarea', Html
::getTextInputAttributes( $attribs ), $spacedValue );
837 * Build a drop-down box for selecting a namespace
839 * @param array $params Params to set.
840 * - selected: [optional] Id of namespace which should be pre-selected
841 * - all: [optional] Value of item for "all namespaces". If null or unset,
842 * no "<option>" is generated to select all namespaces.
843 * - label: text for label to add before the field.
844 * - exclude: [optional] Array of namespace ids to exclude.
845 * - disable: [optional] Array of namespace ids for which the option should
846 * be disabled in the selector.
847 * @param array $selectAttribs HTML attributes for the generated select element.
848 * - id: [optional], default: 'namespace'.
849 * - name: [optional], default: 'namespace'.
850 * @return string HTML code to select a namespace.
852 public static function namespaceSelector( array $params = array(),
853 array $selectAttribs = array()
857 ksort( $selectAttribs );
859 // Is a namespace selected?
860 if ( isset( $params['selected'] ) ) {
861 // If string only contains digits, convert to clean int. Selected could also
862 // be "all" or "" etc. which needs to be left untouched.
863 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
864 // and returns false for already clean ints. Use regex instead..
865 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
866 $params['selected'] = intval( $params['selected'] );
868 // else: leaves it untouched for later processing
870 $params['selected'] = '';
873 if ( !isset( $params['exclude'] ) ||
!is_array( $params['exclude'] ) ) {
874 $params['exclude'] = array();
876 if ( !isset( $params['disable'] ) ||
!is_array( $params['disable'] ) ) {
877 $params['disable'] = array();
880 // Associative array between option-values and option-labels
883 if ( isset( $params['all'] ) ) {
884 // add an option that would let the user select all namespaces.
885 // Value is provided by user, the name shown is localized for the user.
886 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
888 // Add all namespaces as options (in the content language)
889 $options +
= $wgContLang->getFormattedNamespaces();
891 // Convert $options to HTML and filter out namespaces below 0
892 $optionsHtml = array();
893 foreach ( $options as $nsId => $nsName ) {
894 if ( $nsId < NS_MAIN ||
in_array( $nsId, $params['exclude'] ) ) {
897 if ( $nsId === NS_MAIN
) {
898 // For other namespaces use use the namespace prefix as label, but for
899 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
900 $nsName = wfMessage( 'blanknamespace' )->text();
901 } elseif ( is_int( $nsId ) ) {
902 $nsName = $wgContLang->convertNamespace( $nsId );
904 $optionsHtml[] = Html
::element(
906 'disabled' => in_array( $nsId, $params['disable'] ),
908 'selected' => $nsId === $params['selected'],
913 if ( !array_key_exists( 'id', $selectAttribs ) ) {
914 $selectAttribs['id'] = 'namespace';
917 if ( !array_key_exists( 'name', $selectAttribs ) ) {
918 $selectAttribs['name'] = 'namespace';
922 if ( isset( $params['label'] ) ) {
923 $ret .= Html
::element(
925 'for' => isset( $selectAttribs['id'] ) ?
$selectAttribs['id'] : null,
930 // Wrap options in a <select>
931 $ret .= Html
::openElement( 'select', $selectAttribs )
933 . implode( "\n", $optionsHtml )
935 . Html
::closeElement( 'select' );
941 * Constructs the opening html-tag with necessary doctypes depending on
944 * @param array $attribs Associative array of miscellaneous extra
945 * attributes, passed to Html::element() of html tag.
946 * @return string Raw HTML
948 public static function htmlHeader( $attribs = array() ) {
951 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
953 $isXHTML = self
::isXmlMimeType( $wgMimeType );
955 if ( $isXHTML ) { // XHTML5
956 // XML MIME-typed markup should have an xml header.
957 // However a DOCTYPE is not needed.
958 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
960 // Add the standard xmlns
961 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
963 // And support custom namespaces
964 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
965 $attribs["xmlns:$tag"] = $ns;
969 $ret .= "<!DOCTYPE html>\n";
972 if ( $wgHtml5Version ) {
973 $attribs['version'] = $wgHtml5Version;
976 $html = Html
::openElement( 'html', $attribs );
988 * Determines if the given MIME type is xml.
990 * @param string $mimetype MIME type
993 public static function isXmlMimeType( $mimetype ) {
994 # http://www.whatwg.org/html/infrastructure.html#xml-mime-type
997 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
998 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
1002 * Get HTML for an info box with an icon.
1004 * @param string $text Wikitext, get this with wfMessage()->plain()
1005 * @param string $icon Path to icon file (used as 'src' attribute)
1006 * @param string $alt Alternate text for the icon
1007 * @param string $class Additional class name to add to the wrapper div
1011 static function infoBox( $text, $icon, $alt, $class = false ) {
1012 $s = Html
::openElement( 'div', array( 'class' => "mw-infobox $class" ) );
1014 $s .= Html
::openElement( 'div', array( 'class' => 'mw-infobox-left' ) ) .
1015 Html
::element( 'img',
1021 Html
::closeElement( 'div' );
1023 $s .= Html
::openElement( 'div', array( 'class' => 'mw-infobox-right' ) ) .
1025 Html
::closeElement( 'div' );
1026 $s .= Html
::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
1028 $s .= Html
::closeElement( 'div' );
1030 $s .= Html
::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
1036 * Generate a srcset attribute value from an array mapping pixel densities
1037 * to URLs. Note that srcset supports width and height values as well, which
1038 * are not used here.
1040 * @param array $urls
1043 static function srcSet( $urls ) {
1044 $candidates = array();
1045 foreach ( $urls as $density => $url ) {
1046 // Image candidate syntax per current whatwg live spec, 2012-09-23:
1047 // http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
1048 $candidates[] = "{$url} {$density}x";
1050 return implode( ", ", $candidates );