Merge "Refactor Watchlist code so mobile can be more consistent"
[mediawiki.git] / includes / Html.php
blobce439cb3ee643995deb998e881eb350eca185135
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 can contain space-separated lists ('class', 'accesskey' and 'rel') 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.
417 * @throws MWException If an attribute that doesn't allow lists is set to an array
418 * @return string HTML fragment that goes between element name and '>'
419 * (starting with a space if at least one attribute is output)
421 public static function expandAttributes( $attribs ) {
422 global $wgWellFormedXml;
424 $ret = '';
425 $attribs = (array)$attribs;
426 foreach ( $attribs as $key => $value ) {
427 // Support intuitive array( 'checked' => true/false ) form
428 if ( $value === false || is_null( $value ) ) {
429 continue;
432 // For boolean attributes, support array( 'foo' ) instead of
433 // requiring array( 'foo' => 'meaningless' ).
434 if ( is_int( $key )
435 && in_array( strtolower( $value ), self::$boolAttribs ) ) {
436 $key = $value;
439 // Not technically required in HTML5 but we'd like consistency
440 // and better compression anyway.
441 $key = strtolower( $key );
443 // Bug 23769: Blacklist all form validation attributes for now. Current
444 // (June 2010) WebKit has no UI, so the form just refuses to submit
445 // without telling the user why, which is much worse than failing
446 // server-side validation. Opera is the only other implementation at
447 // this time, and has ugly UI, so just kill the feature entirely until
448 // we have at least one good implementation.
450 // As the default value of "1" for "step" rejects decimal
451 // numbers to be entered in 'type="number"' fields, allow
452 // the special case 'step="any"'.
454 if ( in_array( $key, array( 'max', 'min', 'pattern', 'required' ) )
455 || $key === 'step' && $value !== 'any' ) {
456 continue;
459 // http://www.w3.org/TR/html401/index/attributes.html ("space-separated")
460 // http://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
461 $spaceSeparatedListAttributes = array(
462 'class', // html4, html5
463 'accesskey', // as of html5, multiple space-separated values allowed
464 // html4-spec doesn't document rel= as space-separated
465 // but has been used like that and is now documented as such
466 // in the html5-spec.
467 'rel',
470 // Specific features for attributes that allow a list of space-separated values
471 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
472 // Apply some normalization and remove duplicates
474 // Convert into correct array. Array can contain space-separated
475 // values. Implode/explode to get those into the main array as well.
476 if ( is_array( $value ) ) {
477 // If input wasn't an array, we can skip this step
478 $newValue = array();
479 foreach ( $value as $k => $v ) {
480 if ( is_string( $v ) ) {
481 // String values should be normal `array( 'foo' )`
482 // Just append them
483 if ( !isset( $value[$v] ) ) {
484 // As a special case don't set 'foo' if a
485 // separate 'foo' => true/false exists in the array
486 // keys should be authoritative
487 $newValue[] = $v;
489 } elseif ( $v ) {
490 // If the value is truthy but not a string this is likely
491 // an array( 'foo' => true ), falsy values don't add strings
492 $newValue[] = $k;
495 $value = implode( ' ', $newValue );
497 $value = explode( ' ', $value );
499 // Normalize spacing by fixing up cases where people used
500 // more than 1 space and/or a trailing/leading space
501 $value = array_diff( $value, array( '', ' ' ) );
503 // Remove duplicates and create the string
504 $value = implode( ' ', array_unique( $value ) );
505 } elseif ( is_array( $value ) ) {
506 throw new MWException( "HTML attribute $key can not contain a list of values" );
509 // See the "Attributes" section in the HTML syntax part of HTML5,
510 // 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
511 // marks omitted, but not all. (Although a literal " is not
512 // permitted, we don't check for that, since it will be escaped
513 // anyway.)
515 // See also research done on further characters that need to be
516 // escaped: http://code.google.com/p/html5lib/issues/detail?id=93
517 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
518 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
519 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
520 if ( $wgWellFormedXml || $value === ''
521 || preg_match( "![$badChars]!u", $value ) ) {
522 $quote = '"';
523 } else {
524 $quote = '';
527 if ( in_array( $key, self::$boolAttribs ) ) {
528 // In HTML5, we can leave the value empty. If we don't need
529 // well-formed XML, we can omit the = entirely.
530 if ( !$wgWellFormedXml ) {
531 $ret .= " $key";
532 } else {
533 $ret .= " $key=\"\"";
535 } else {
536 // Apparently we need to entity-encode \n, \r, \t, although the
537 // spec doesn't mention that. Since we're doing strtr() anyway,
538 // and we don't need <> escaped here, we may as well not call
539 // htmlspecialchars().
540 // @todo FIXME: Verify that we actually need to
541 // escape \n\r\t here, and explain why, exactly.
543 // We could call Sanitizer::encodeAttribute() for this, but we
544 // don't because we're stubborn and like our marginal savings on
545 // byte size from not having to encode unnecessary quotes.
546 $map = array(
547 '&' => '&amp;',
548 '"' => '&quot;',
549 "\n" => '&#10;',
550 "\r" => '&#13;',
551 "\t" => '&#9;'
553 if ( $wgWellFormedXml ) {
554 // This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
555 // But reportedly it breaks some XML tools?
556 // @todo FIXME: Is this really true?
557 $map['<'] = '&lt;';
559 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
562 return $ret;
566 * Output a "<script>" tag with the given contents.
568 * @todo do some useful escaping as well, like if $contents contains
569 * literal "</script>" or (for XML) literal "]]>".
571 * @param string $contents JavaScript
572 * @return string Raw HTML
574 public static function inlineScript( $contents ) {
575 global $wgWellFormedXml;
577 $attrs = array();
579 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
580 $contents = "/*<![CDATA[*/$contents/*]]>*/";
583 return self::rawElement( 'script', $attrs, $contents );
587 * Output a "<script>" tag linking to the given URL, e.g.,
588 * "<script src=foo.js></script>".
590 * @param string $url
591 * @return string Raw HTML
593 public static function linkedScript( $url ) {
594 $attrs = array( 'src' => $url );
596 return self::element( 'script', $attrs );
600 * Output a "<style>" tag with the given contents for the given media type
601 * (if any). TODO: do some useful escaping as well, like if $contents
602 * contains literal "</style>" (admittedly unlikely).
604 * @param string $contents CSS
605 * @param string $media A media type string, like 'screen'
606 * @return string Raw HTML
608 public static function inlineStyle( $contents, $media = 'all' ) {
609 global $wgWellFormedXml;
611 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
612 $contents = "/*<![CDATA[*/$contents/*]]>*/";
615 return self::rawElement( 'style', array(
616 'type' => 'text/css',
617 'media' => $media,
618 ), $contents );
622 * Output a "<link rel=stylesheet>" linking to the given URL for the given
623 * media type (if any).
625 * @param string $url
626 * @param string $media A media type string, like 'screen'
627 * @return string Raw HTML
629 public static function linkedStyle( $url, $media = 'all' ) {
630 return self::element( 'link', array(
631 'rel' => 'stylesheet',
632 'href' => $url,
633 'type' => 'text/css',
634 'media' => $media,
635 ) );
639 * Convenience function to produce an "<input>" element. This supports the
640 * new HTML5 input types and attributes.
642 * @param string $name Name attribute
643 * @param array $value Value attribute
644 * @param string $type Type attribute
645 * @param array $attribs Associative array of miscellaneous extra
646 * attributes, passed to Html::element()
647 * @return string Raw HTML
649 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
650 $attribs['type'] = $type;
651 $attribs['value'] = $value;
652 $attribs['name'] = $name;
654 return self::element( 'input', $attribs );
658 * Convenience function to produce a checkbox (input element with type=checkbox)
660 * @param string $name Name attribute
661 * @param bool $checked Whether the checkbox is checked or not
662 * @param array $attribs Array of additional attributes
664 public static function check( $name, $checked = false, array $attribs = array() ) {
665 if ( isset( $attribs['value'] ) ) {
666 $value = $attribs['value'];
667 unset( $attribs['value'] );
668 } else {
669 $value = 1;
672 if ( $checked ) {
673 $attribs[] = 'checked';
676 return self::input( $name, $value, 'checkbox', $attribs );
680 * Convenience function to produce a checkbox (input element with type=checkbox)
682 * @param string $name Name attribute
683 * @param bool $checked Whether the checkbox is checked or not
684 * @param array $attribs Array of additional attributes
686 public static function radio( $name, $checked = false, array $attribs = array() ) {
687 if ( isset( $attribs['value'] ) ) {
688 $value = $attribs['value'];
689 unset( $attribs['value'] );
690 } else {
691 $value = 1;
694 if ( $checked ) {
695 $attribs[] = 'checked';
698 return self::input( $name, $value, 'radio', $attribs );
702 * Convenience function for generating a label for inputs.
704 * @param string $label Contents of the label
705 * @param string $id ID of the element being labeled
706 * @param array $attribs Additional attributes
708 public static function label( $label, $id, array $attribs = array() ) {
709 $attribs += array(
710 'for' => $id
712 return self::element( 'label', $attribs, $label );
716 * Convenience function to produce an input element with type=hidden
718 * @param string $name Name attribute
719 * @param string $value Value attribute
720 * @param array $attribs Associative array of miscellaneous extra
721 * attributes, passed to Html::element()
722 * @return string Raw HTML
724 public static function hidden( $name, $value, $attribs = array() ) {
725 return self::input( $name, $value, 'hidden', $attribs );
729 * Convenience function to produce a <textarea> element.
731 * This supports leaving out the cols= and rows= which Xml requires and are
732 * required by HTML4/XHTML but not required by HTML5.
734 * @param string $name Name attribute
735 * @param string $value Value attribute
736 * @param array $attribs Associative array of miscellaneous extra
737 * attributes, passed to Html::element()
738 * @return string Raw HTML
740 public static function textarea( $name, $value = '', $attribs = array() ) {
741 $attribs['name'] = $name;
743 if ( substr( $value, 0, 1 ) == "\n" ) {
744 // Workaround for bug 12130: browsers eat the initial newline
745 // assuming that it's just for show, but they do keep the later
746 // newlines, which we may want to preserve during editing.
747 // Prepending a single newline
748 $spacedValue = "\n" . $value;
749 } else {
750 $spacedValue = $value;
752 return self::element( 'textarea', $attribs, $spacedValue );
756 * Build a drop-down box for selecting a namespace
758 * @param array $params Params to set.
759 * - selected: [optional] Id of namespace which should be pre-selected
760 * - all: [optional] Value of item for "all namespaces". If null or unset,
761 * no "<option>" is generated to select all namespaces.
762 * - label: text for label to add before the field.
763 * - exclude: [optional] Array of namespace ids to exclude.
764 * - disable: [optional] Array of namespace ids for which the option should
765 * be disabled in the selector.
766 * @param array $selectAttribs HTML attributes for the generated select element.
767 * - id: [optional], default: 'namespace'.
768 * - name: [optional], default: 'namespace'.
769 * @return string HTML code to select a namespace.
771 public static function namespaceSelector( array $params = array(),
772 array $selectAttribs = array()
774 global $wgContLang;
776 ksort( $selectAttribs );
778 // Is a namespace selected?
779 if ( isset( $params['selected'] ) ) {
780 // If string only contains digits, convert to clean int. Selected could also
781 // be "all" or "" etc. which needs to be left untouched.
782 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
783 // and returns false for already clean ints. Use regex instead..
784 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
785 $params['selected'] = intval( $params['selected'] );
787 // else: leaves it untouched for later processing
788 } else {
789 $params['selected'] = '';
792 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
793 $params['exclude'] = array();
795 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
796 $params['disable'] = array();
799 // Associative array between option-values and option-labels
800 $options = array();
802 if ( isset( $params['all'] ) ) {
803 // add an option that would let the user select all namespaces.
804 // Value is provided by user, the name shown is localized for the user.
805 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
807 // Add all namespaces as options (in the content language)
808 $options += $wgContLang->getFormattedNamespaces();
810 // Convert $options to HTML and filter out namespaces below 0
811 $optionsHtml = array();
812 foreach ( $options as $nsId => $nsName ) {
813 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
814 continue;
816 if ( $nsId === NS_MAIN ) {
817 // For other namespaces use use the namespace prefix as label, but for
818 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
819 $nsName = wfMessage( 'blanknamespace' )->text();
820 } elseif ( is_int( $nsId ) ) {
821 $nsName = $wgContLang->convertNamespace( $nsId );
823 $optionsHtml[] = Html::element(
824 'option', array(
825 'disabled' => in_array( $nsId, $params['disable'] ),
826 'value' => $nsId,
827 'selected' => $nsId === $params['selected'],
828 ), $nsName
832 if ( !array_key_exists( 'id', $selectAttribs ) ) {
833 $selectAttribs['id'] = 'namespace';
836 if ( !array_key_exists( 'name', $selectAttribs ) ) {
837 $selectAttribs['name'] = 'namespace';
840 $ret = '';
841 if ( isset( $params['label'] ) ) {
842 $ret .= Html::element(
843 'label', array(
844 'for' => isset( $selectAttribs['id'] ) ? $selectAttribs['id'] : null,
845 ), $params['label']
846 ) . '&#160;';
849 // Wrap options in a <select>
850 $ret .= Html::openElement( 'select', $selectAttribs )
851 . "\n"
852 . implode( "\n", $optionsHtml )
853 . "\n"
854 . Html::closeElement( 'select' );
856 return $ret;
860 * Constructs the opening html-tag with necessary doctypes depending on
861 * global variables.
863 * @param array $attribs Associative array of miscellaneous extra
864 * attributes, passed to Html::element() of html tag.
865 * @return string Raw HTML
867 public static function htmlHeader( $attribs = array() ) {
868 $ret = '';
870 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
872 $isXHTML = self::isXmlMimeType( $wgMimeType );
874 if ( $isXHTML ) { // XHTML5
875 // XML mimetyped markup should have an xml header.
876 // However a DOCTYPE is not needed.
877 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
879 // Add the standard xmlns
880 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
882 // And support custom namespaces
883 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
884 $attribs["xmlns:$tag"] = $ns;
886 } else { // HTML5
887 // DOCTYPE
888 $ret .= "<!DOCTYPE html>\n";
891 if ( $wgHtml5Version ) {
892 $attribs['version'] = $wgHtml5Version;
895 $html = Html::openElement( 'html', $attribs );
897 if ( $html ) {
898 $html .= "\n";
901 $ret .= $html;
903 return $ret;
907 * Determines if the given mime type is xml.
909 * @param string $mimetype MimeType
910 * @return bool
912 public static function isXmlMimeType( $mimetype ) {
913 # http://www.whatwg.org/html/infrastructure.html#xml-mime-type
914 # * text/xml
915 # * application/xml
916 # * Any mimetype with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
917 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
921 * Get HTML for an info box with an icon.
923 * @param string $text Wikitext, get this with wfMessage()->plain()
924 * @param string $icon Icon name, file in skins/common/images
925 * @param string $alt Alternate text for the icon
926 * @param string $class Additional class name to add to the wrapper div
927 * @param bool $useStylePath
929 * @return string
931 static function infoBox( $text, $icon, $alt, $class = false, $useStylePath = true ) {
932 global $wgStylePath;
934 if ( $useStylePath ) {
935 $icon = $wgStylePath . '/common/images/' . $icon;
938 $s = Html::openElement( 'div', array( 'class' => "mw-infobox $class" ) );
940 $s .= Html::openElement( 'div', array( 'class' => 'mw-infobox-left' ) ) .
941 Html::element( 'img',
942 array(
943 'src' => $icon,
944 'alt' => $alt,
947 Html::closeElement( 'div' );
949 $s .= Html::openElement( 'div', array( 'class' => 'mw-infobox-right' ) ) .
950 $text .
951 Html::closeElement( 'div' );
952 $s .= Html::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
954 $s .= Html::closeElement( 'div' );
956 $s .= Html::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
958 return $s;
962 * Generate a srcset attribute value from an array mapping pixel densities
963 * to URLs. Note that srcset supports width and height values as well, which
964 * are not used here.
966 * @param array $urls
967 * @return string
969 static function srcSet( $urls ) {
970 $candidates = array();
971 foreach ( $urls as $density => $url ) {
972 // Image candidate syntax per current whatwg live spec, 2012-09-23:
973 // http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
974 $candidates[] = "{$url} {$density}x";
976 return implode( ", ", $candidates );