Remove "related" searches
[mediawiki.git] / includes / Html.php
blob1e16e39430ab839993a7b5ff43fdcfca8923bd8b
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 MIME type 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 * Modifies a set of attributes meant for text input elements
106 * and apply a set of default attributes.
107 * Removes size attribute when $wgUseMediaWikiUIEverywhere enabled.
108 * @param array $attrs An attribute array.
109 * @return array $attrs A modified attribute array
111 public static function getTextInputAttributes( $attrs ) {
112 global $wgUseMediaWikiUIEverywhere;
113 if ( !$attrs ) {
114 $attrs = array();
116 if ( isset( $attrs['class'] ) ) {
117 if ( is_array( $attrs['class'] ) ) {
118 $attrs['class'][] = 'mw-ui-input';
119 } else {
120 $attrs['class'] .= ' mw-ui-input';
122 } else {
123 $attrs['class'] = 'mw-ui-input';
125 if ( $wgUseMediaWikiUIEverywhere ) {
126 // Note that size can effect the desired width rendering of mw-ui-input elements
127 // so it is removed. Left intact when mediawiki ui not enabled.
128 unset( $attrs['size'] );
130 return $attrs;
134 * Returns an HTML element in a string. The major advantage here over
135 * manually typing out the HTML is that it will escape all attribute
136 * values. If you're hardcoding all the attributes, or there are none, you
137 * should probably just type out the html element yourself.
139 * This is quite similar to Xml::tags(), but it implements some useful
140 * HTML-specific logic. For instance, there is no $allowShortTag
141 * parameter: the closing tag is magically omitted if $element has an empty
142 * content model. If $wgWellFormedXml is false, then a few bytes will be
143 * shaved off the HTML output as well.
145 * @param string $element The element's name, e.g., 'a'
146 * @param array $attribs Associative array of attributes, e.g., array(
147 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
148 * further documentation.
149 * @param string $contents The raw HTML contents of the element: *not*
150 * escaped!
151 * @return string Raw HTML
153 public static function rawElement( $element, $attribs = array(), $contents = '' ) {
154 global $wgWellFormedXml;
155 $start = self::openElement( $element, $attribs );
156 if ( in_array( $element, self::$voidElements ) ) {
157 if ( $wgWellFormedXml ) {
158 // Silly XML.
159 return substr( $start, 0, -1 ) . ' />';
161 return $start;
162 } else {
163 return "$start$contents" . self::closeElement( $element );
168 * Identical to rawElement(), but HTML-escapes $contents (like
169 * Xml::element()).
171 * @param string $element
172 * @param array $attribs
173 * @param string $contents
175 * @return string
177 public static function element( $element, $attribs = array(), $contents = '' ) {
178 return self::rawElement( $element, $attribs, strtr( $contents, array(
179 // There's no point in escaping quotes, >, etc. in the contents of
180 // elements.
181 '&' => '&amp;',
182 '<' => '&lt;'
183 ) ) );
187 * Identical to rawElement(), but has no third parameter and omits the end
188 * tag (and the self-closing '/' in XML mode for empty elements).
190 * @param string $element
191 * @param array $attribs
193 * @return string
195 public static function openElement( $element, $attribs = array() ) {
196 global $wgWellFormedXml;
197 $attribs = (array)$attribs;
198 // This is not required in HTML5, but let's do it anyway, for
199 // consistency and better compression.
200 $element = strtolower( $element );
202 // In text/html, initial <html> and <head> tags can be omitted under
203 // pretty much any sane circumstances, if they have no attributes. See:
204 // <http://www.whatwg.org/html/syntax.html#optional-tags>
205 if ( !$wgWellFormedXml && !$attribs
206 && in_array( $element, array( 'html', 'head' ) ) ) {
207 return '';
210 // Remove invalid input types
211 if ( $element == 'input' ) {
212 $validTypes = array(
213 'hidden',
214 'text',
215 'password',
216 'checkbox',
217 'radio',
218 'file',
219 'submit',
220 'image',
221 'reset',
222 'button',
224 // HTML input types
225 'datetime',
226 'datetime-local',
227 'date',
228 'month',
229 'time',
230 'week',
231 'number',
232 'range',
233 'email',
234 'url',
235 'search',
236 'tel',
237 'color',
239 if ( isset( $attribs['type'] )
240 && !in_array( $attribs['type'], $validTypes ) ) {
241 unset( $attribs['type'] );
245 // According to standard the default type for <button> elements is "submit".
246 // Depending on compatibility mode IE might use "button", instead.
247 // We enforce the standard "submit".
248 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
249 $attribs['type'] = 'submit';
252 return "<$element" . self::expandAttributes(
253 self::dropDefaults( $element, $attribs ) ) . '>';
257 * Returns "</$element>"
259 * @since 1.17
260 * @param string $element Name of the element, e.g., 'a'
261 * @return string A closing tag
263 public static function closeElement( $element ) {
264 $element = strtolower( $element );
266 return "</$element>";
270 * Given an element name and an associative array of element attributes,
271 * return an array that is functionally identical to the input array, but
272 * possibly smaller. In particular, attributes might be stripped if they
273 * are given their default values.
275 * This method is not guaranteed to remove all redundant attributes, only
276 * some common ones and some others selected arbitrarily at random. It
277 * only guarantees that the output array should be functionally identical
278 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
280 * @param string $element Name of the element, e.g., 'a'
281 * @param array $attribs Associative array of attributes, e.g., array(
282 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
283 * further documentation.
284 * @return array An array of attributes functionally identical to $attribs
286 private static function dropDefaults( $element, $attribs ) {
288 // Whenever altering this array, please provide a covering test case
289 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
290 static $attribDefaults = array(
291 'area' => array( 'shape' => 'rect' ),
292 'button' => array(
293 'formaction' => 'GET',
294 'formenctype' => 'application/x-www-form-urlencoded',
296 'canvas' => array(
297 'height' => '150',
298 'width' => '300',
300 'command' => array( 'type' => 'command' ),
301 'form' => array(
302 'action' => 'GET',
303 'autocomplete' => 'on',
304 'enctype' => 'application/x-www-form-urlencoded',
306 'input' => array(
307 'formaction' => 'GET',
308 'type' => 'text',
310 'keygen' => array( 'keytype' => 'rsa' ),
311 'link' => array( 'media' => 'all' ),
312 'menu' => array( 'type' => 'list' ),
313 // Note: the use of text/javascript here instead of other JavaScript
314 // MIME types follows the HTML5 spec.
315 'script' => array( 'type' => 'text/javascript' ),
316 'style' => array(
317 'media' => 'all',
318 'type' => 'text/css',
320 'textarea' => array( 'wrap' => 'soft' ),
323 $element = strtolower( $element );
325 foreach ( $attribs as $attrib => $value ) {
326 $lcattrib = strtolower( $attrib );
327 if ( is_array( $value ) ) {
328 $value = implode( ' ', $value );
329 } else {
330 $value = strval( $value );
333 // Simple checks using $attribDefaults
334 if ( isset( $attribDefaults[$element][$lcattrib] ) &&
335 $attribDefaults[$element][$lcattrib] == $value ) {
336 unset( $attribs[$attrib] );
339 if ( $lcattrib == 'class' && $value == '' ) {
340 unset( $attribs[$attrib] );
344 // More subtle checks
345 if ( $element === 'link' && isset( $attribs['type'] )
346 && strval( $attribs['type'] ) == 'text/css' ) {
347 unset( $attribs['type'] );
349 if ( $element === 'input' ) {
350 $type = isset( $attribs['type'] ) ? $attribs['type'] : null;
351 $value = isset( $attribs['value'] ) ? $attribs['value'] : null;
352 if ( $type === 'checkbox' || $type === 'radio' ) {
353 // The default value for checkboxes and radio buttons is 'on'
354 // not ''. By stripping value="" we break radio boxes that
355 // actually wants empty values.
356 if ( $value === 'on' ) {
357 unset( $attribs['value'] );
359 } elseif ( $type === 'submit' ) {
360 // The default value for submit appears to be "Submit" but
361 // let's not bother stripping out localized text that matches
362 // that.
363 } else {
364 // The default value for nearly every other field type is ''
365 // The 'range' and 'color' types use different defaults but
366 // stripping a value="" does not hurt them.
367 if ( $value === '' ) {
368 unset( $attribs['value'] );
372 if ( $element === 'select' && isset( $attribs['size'] ) ) {
373 if ( in_array( 'multiple', $attribs )
374 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
376 // A multi-select
377 if ( strval( $attribs['size'] ) == '4' ) {
378 unset( $attribs['size'] );
380 } else {
381 // Single select
382 if ( strval( $attribs['size'] ) == '1' ) {
383 unset( $attribs['size'] );
388 return $attribs;
392 * Given an associative array of element attributes, generate a string
393 * to stick after the element name in HTML output. Like array( 'href' =>
394 * 'http://www.mediawiki.org/' ) becomes something like
395 * ' href="http://www.mediawiki.org"'. Again, this is like
396 * Xml::expandAttributes(), but it implements some HTML-specific logic.
397 * For instance, it will omit quotation marks if $wgWellFormedXml is false,
398 * and will treat boolean attributes specially.
400 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
401 * values are allowed as well, which will automagically be normalized
402 * and converted to a space-separated string. In addition to a numerical
403 * array, the attribute value may also be an associative array. See the
404 * example below for how that works.
406 * @par Numerical array
407 * @code
408 * Html::element( 'em', array(
409 * 'class' => array( 'foo', 'bar' )
410 * ) );
411 * // gives '<em class="foo bar"></em>'
412 * @endcode
414 * @par Associative array
415 * @code
416 * Html::element( 'em', array(
417 * 'class' => array( 'foo', 'bar', 'foo' => false, 'quux' => true )
418 * ) );
419 * // gives '<em class="bar quux"></em>'
420 * @endcode
422 * @param array $attribs Associative array of attributes, e.g., array(
423 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
424 * A value of false means to omit the attribute. For boolean attributes,
425 * you can omit the key, e.g., array( 'checked' ) instead of
426 * array( 'checked' => 'checked' ) or such.
428 * @throws MWException If an attribute that doesn't allow lists is set to an array
429 * @return string HTML fragment that goes between element name and '>'
430 * (starting with a space if at least one attribute is output)
432 public static function expandAttributes( $attribs ) {
433 global $wgWellFormedXml;
435 $ret = '';
436 $attribs = (array)$attribs;
437 foreach ( $attribs as $key => $value ) {
438 // Support intuitive array( 'checked' => true/false ) form
439 if ( $value === false || is_null( $value ) ) {
440 continue;
443 // For boolean attributes, support array( 'foo' ) instead of
444 // requiring array( 'foo' => 'meaningless' ).
445 if ( is_int( $key )
446 && in_array( strtolower( $value ), self::$boolAttribs ) ) {
447 $key = $value;
450 // Not technically required in HTML5 but we'd like consistency
451 // and better compression anyway.
452 $key = strtolower( $key );
454 // Bug 23769: Blacklist all form validation attributes for now. Current
455 // (June 2010) WebKit has no UI, so the form just refuses to submit
456 // without telling the user why, which is much worse than failing
457 // server-side validation. Opera is the only other implementation at
458 // this time, and has ugly UI, so just kill the feature entirely until
459 // we have at least one good implementation.
461 // As the default value of "1" for "step" rejects decimal
462 // numbers to be entered in 'type="number"' fields, allow
463 // the special case 'step="any"'.
465 if ( in_array( $key, array( 'max', 'min', 'pattern', 'required' ) )
466 || $key === 'step' && $value !== 'any' ) {
467 continue;
470 // http://www.w3.org/TR/html401/index/attributes.html ("space-separated")
471 // http://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
472 $spaceSeparatedListAttributes = array(
473 'class', // html4, html5
474 'accesskey', // as of html5, multiple space-separated values allowed
475 // html4-spec doesn't document rel= as space-separated
476 // but has been used like that and is now documented as such
477 // in the html5-spec.
478 'rel',
481 // Specific features for attributes that allow a list of space-separated values
482 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
483 // Apply some normalization and remove duplicates
485 // Convert into correct array. Array can contain space-separated
486 // values. Implode/explode to get those into the main array as well.
487 if ( is_array( $value ) ) {
488 // If input wasn't an array, we can skip this step
489 $newValue = array();
490 foreach ( $value as $k => $v ) {
491 if ( is_string( $v ) ) {
492 // String values should be normal `array( 'foo' )`
493 // Just append them
494 if ( !isset( $value[$v] ) ) {
495 // As a special case don't set 'foo' if a
496 // separate 'foo' => true/false exists in the array
497 // keys should be authoritative
498 $newValue[] = $v;
500 } elseif ( $v ) {
501 // If the value is truthy but not a string this is likely
502 // an array( 'foo' => true ), falsy values don't add strings
503 $newValue[] = $k;
506 $value = implode( ' ', $newValue );
508 $value = explode( ' ', $value );
510 // Normalize spacing by fixing up cases where people used
511 // more than 1 space and/or a trailing/leading space
512 $value = array_diff( $value, array( '', ' ' ) );
514 // Remove duplicates and create the string
515 $value = implode( ' ', array_unique( $value ) );
516 } elseif ( is_array( $value ) ) {
517 throw new MWException( "HTML attribute $key can not contain a list of values" );
520 // See the "Attributes" section in the HTML syntax part of HTML5,
521 // 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
522 // marks omitted, but not all. (Although a literal " is not
523 // permitted, we don't check for that, since it will be escaped
524 // anyway.)
526 // See also research done on further characters that need to be
527 // escaped: http://code.google.com/p/html5lib/issues/detail?id=93
528 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
529 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
530 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
531 if ( $wgWellFormedXml || $value === ''
532 || preg_match( "![$badChars]!u", $value ) ) {
533 $quote = '"';
534 } else {
535 $quote = '';
538 if ( in_array( $key, self::$boolAttribs ) ) {
539 // In HTML5, we can leave the value empty. If we don't need
540 // well-formed XML, we can omit the = entirely.
541 if ( !$wgWellFormedXml ) {
542 $ret .= " $key";
543 } else {
544 $ret .= " $key=\"\"";
546 } else {
547 // Apparently we need to entity-encode \n, \r, \t, although the
548 // spec doesn't mention that. Since we're doing strtr() anyway,
549 // and we don't need <> escaped here, we may as well not call
550 // htmlspecialchars().
551 // @todo FIXME: Verify that we actually need to
552 // escape \n\r\t here, and explain why, exactly.
554 // We could call Sanitizer::encodeAttribute() for this, but we
555 // don't because we're stubborn and like our marginal savings on
556 // byte size from not having to encode unnecessary quotes.
557 $map = array(
558 '&' => '&amp;',
559 '"' => '&quot;',
560 "\n" => '&#10;',
561 "\r" => '&#13;',
562 "\t" => '&#9;'
564 if ( $wgWellFormedXml ) {
565 // This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
566 // But reportedly it breaks some XML tools?
567 // @todo FIXME: Is this really true?
568 $map['<'] = '&lt;';
570 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
573 return $ret;
577 * Output a "<script>" tag with the given contents.
579 * @todo do some useful escaping as well, like if $contents contains
580 * literal "</script>" or (for XML) literal "]]>".
582 * @param string $contents JavaScript
583 * @return string Raw HTML
585 public static function inlineScript( $contents ) {
586 global $wgWellFormedXml;
588 $attrs = array();
590 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
591 $contents = "/*<![CDATA[*/$contents/*]]>*/";
594 return self::rawElement( 'script', $attrs, $contents );
598 * Output a "<script>" tag linking to the given URL, e.g.,
599 * "<script src=foo.js></script>".
601 * @param string $url
602 * @return string Raw HTML
604 public static function linkedScript( $url ) {
605 $attrs = array( 'src' => $url );
607 return self::element( 'script', $attrs );
611 * Output a "<style>" tag with the given contents for the given media type
612 * (if any). TODO: do some useful escaping as well, like if $contents
613 * contains literal "</style>" (admittedly unlikely).
615 * @param string $contents CSS
616 * @param string $media A media type string, like 'screen'
617 * @return string Raw HTML
619 public static function inlineStyle( $contents, $media = 'all' ) {
620 global $wgWellFormedXml;
622 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
623 $contents = "/*<![CDATA[*/$contents/*]]>*/";
626 return self::rawElement( 'style', array(
627 'type' => 'text/css',
628 'media' => $media,
629 ), $contents );
633 * Output a "<link rel=stylesheet>" linking to the given URL for the given
634 * media type (if any).
636 * @param string $url
637 * @param string $media A media type string, like 'screen'
638 * @return string Raw HTML
640 public static function linkedStyle( $url, $media = 'all' ) {
641 return self::element( 'link', array(
642 'rel' => 'stylesheet',
643 'href' => $url,
644 'type' => 'text/css',
645 'media' => $media,
646 ) );
650 * Convenience function to produce an "<input>" element. This supports the
651 * new HTML5 input types and attributes.
653 * @param string $name Name attribute
654 * @param array $value Value attribute
655 * @param string $type Type attribute
656 * @param array $attribs Associative array of miscellaneous extra
657 * attributes, passed to Html::element()
658 * @return string Raw HTML
660 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
661 $attribs['type'] = $type;
662 $attribs['value'] = $value;
663 $attribs['name'] = $name;
664 if ( in_array( $type, array( 'text', 'search', 'email', 'password', 'number' ) ) ) {
665 $attribs = Html::getTextInputAttributes( $attribs );
667 return self::element( 'input', $attribs );
671 * Convenience function to produce a checkbox (input element with type=checkbox)
673 * @param string $name Name attribute
674 * @param bool $checked Whether the checkbox is checked or not
675 * @param array $attribs Array of additional attributes
676 * @return string
678 public static function check( $name, $checked = false, array $attribs = array() ) {
679 if ( isset( $attribs['value'] ) ) {
680 $value = $attribs['value'];
681 unset( $attribs['value'] );
682 } else {
683 $value = 1;
686 if ( $checked ) {
687 $attribs[] = 'checked';
690 return self::input( $name, $value, 'checkbox', $attribs );
694 * Convenience function to produce a checkbox (input element with type=checkbox)
696 * @param string $name Name attribute
697 * @param bool $checked Whether the checkbox is checked or not
698 * @param array $attribs Array of additional attributes
699 * @return string
701 public static function radio( $name, $checked = false, array $attribs = array() ) {
702 if ( isset( $attribs['value'] ) ) {
703 $value = $attribs['value'];
704 unset( $attribs['value'] );
705 } else {
706 $value = 1;
709 if ( $checked ) {
710 $attribs[] = 'checked';
713 return self::input( $name, $value, 'radio', $attribs );
717 * Convenience function for generating a label for inputs.
719 * @param string $label Contents of the label
720 * @param string $id ID of the element being labeled
721 * @param array $attribs Additional attributes
722 * @return string
724 public static function label( $label, $id, array $attribs = array() ) {
725 $attribs += array(
726 'for' => $id
728 return self::element( 'label', $attribs, $label );
732 * Convenience function to produce an input element with type=hidden
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 hidden( $name, $value, $attribs = array() ) {
741 return self::input( $name, $value, 'hidden', $attribs );
745 * Convenience function to produce a <textarea> element.
747 * This supports leaving out the cols= and rows= which Xml requires and are
748 * required by HTML4/XHTML but not required by HTML5.
750 * @param string $name Name attribute
751 * @param string $value Value attribute
752 * @param array $attribs Associative array of miscellaneous extra
753 * attributes, passed to Html::element()
754 * @return string Raw HTML
756 public static function textarea( $name, $value = '', $attribs = array() ) {
757 $attribs['name'] = $name;
759 if ( substr( $value, 0, 1 ) == "\n" ) {
760 // Workaround for bug 12130: browsers eat the initial newline
761 // assuming that it's just for show, but they do keep the later
762 // newlines, which we may want to preserve during editing.
763 // Prepending a single newline
764 $spacedValue = "\n" . $value;
765 } else {
766 $spacedValue = $value;
768 return self::element( 'textarea', Html::getTextInputAttributes( $attribs ), $spacedValue );
772 * Build a drop-down box for selecting a namespace
774 * @param array $params Params to set.
775 * - selected: [optional] Id of namespace which should be pre-selected
776 * - all: [optional] Value of item for "all namespaces". If null or unset,
777 * no "<option>" is generated to select all namespaces.
778 * - label: text for label to add before the field.
779 * - exclude: [optional] Array of namespace ids to exclude.
780 * - disable: [optional] Array of namespace ids for which the option should
781 * be disabled in the selector.
782 * @param array $selectAttribs HTML attributes for the generated select element.
783 * - id: [optional], default: 'namespace'.
784 * - name: [optional], default: 'namespace'.
785 * @return string HTML code to select a namespace.
787 public static function namespaceSelector( array $params = array(),
788 array $selectAttribs = array()
790 global $wgContLang;
792 ksort( $selectAttribs );
794 // Is a namespace selected?
795 if ( isset( $params['selected'] ) ) {
796 // If string only contains digits, convert to clean int. Selected could also
797 // be "all" or "" etc. which needs to be left untouched.
798 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
799 // and returns false for already clean ints. Use regex instead..
800 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
801 $params['selected'] = intval( $params['selected'] );
803 // else: leaves it untouched for later processing
804 } else {
805 $params['selected'] = '';
808 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
809 $params['exclude'] = array();
811 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
812 $params['disable'] = array();
815 // Associative array between option-values and option-labels
816 $options = array();
818 if ( isset( $params['all'] ) ) {
819 // add an option that would let the user select all namespaces.
820 // Value is provided by user, the name shown is localized for the user.
821 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
823 // Add all namespaces as options (in the content language)
824 $options += $wgContLang->getFormattedNamespaces();
826 // Convert $options to HTML and filter out namespaces below 0
827 $optionsHtml = array();
828 foreach ( $options as $nsId => $nsName ) {
829 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
830 continue;
832 if ( $nsId === NS_MAIN ) {
833 // For other namespaces use use the namespace prefix as label, but for
834 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
835 $nsName = wfMessage( 'blanknamespace' )->text();
836 } elseif ( is_int( $nsId ) ) {
837 $nsName = $wgContLang->convertNamespace( $nsId );
839 $optionsHtml[] = Html::element(
840 'option', array(
841 'disabled' => in_array( $nsId, $params['disable'] ),
842 'value' => $nsId,
843 'selected' => $nsId === $params['selected'],
844 ), $nsName
848 if ( !array_key_exists( 'id', $selectAttribs ) ) {
849 $selectAttribs['id'] = 'namespace';
852 if ( !array_key_exists( 'name', $selectAttribs ) ) {
853 $selectAttribs['name'] = 'namespace';
856 $ret = '';
857 if ( isset( $params['label'] ) ) {
858 $ret .= Html::element(
859 'label', array(
860 'for' => isset( $selectAttribs['id'] ) ? $selectAttribs['id'] : null,
861 ), $params['label']
862 ) . '&#160;';
865 // Wrap options in a <select>
866 $ret .= Html::openElement( 'select', $selectAttribs )
867 . "\n"
868 . implode( "\n", $optionsHtml )
869 . "\n"
870 . Html::closeElement( 'select' );
872 return $ret;
876 * Constructs the opening html-tag with necessary doctypes depending on
877 * global variables.
879 * @param array $attribs Associative array of miscellaneous extra
880 * attributes, passed to Html::element() of html tag.
881 * @return string Raw HTML
883 public static function htmlHeader( $attribs = array() ) {
884 $ret = '';
886 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
888 $isXHTML = self::isXmlMimeType( $wgMimeType );
890 if ( $isXHTML ) { // XHTML5
891 // XML MIME-typed markup should have an xml header.
892 // However a DOCTYPE is not needed.
893 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
895 // Add the standard xmlns
896 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
898 // And support custom namespaces
899 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
900 $attribs["xmlns:$tag"] = $ns;
902 } else { // HTML5
903 // DOCTYPE
904 $ret .= "<!DOCTYPE html>\n";
907 if ( $wgHtml5Version ) {
908 $attribs['version'] = $wgHtml5Version;
911 $html = Html::openElement( 'html', $attribs );
913 if ( $html ) {
914 $html .= "\n";
917 $ret .= $html;
919 return $ret;
923 * Determines if the given MIME type is xml.
925 * @param string $mimetype MIME type
926 * @return bool
928 public static function isXmlMimeType( $mimetype ) {
929 # http://www.whatwg.org/html/infrastructure.html#xml-mime-type
930 # * text/xml
931 # * application/xml
932 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
933 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
937 * Get HTML for an info box with an icon.
939 * @param string $text Wikitext, get this with wfMessage()->plain()
940 * @param string $icon Path to icon file (used as 'src' attribute)
941 * @param string $alt Alternate text for the icon
942 * @param string $class Additional class name to add to the wrapper div
944 * @return string
946 static function infoBox( $text, $icon, $alt, $class = false ) {
947 $s = Html::openElement( 'div', array( 'class' => "mw-infobox $class" ) );
949 $s .= Html::openElement( 'div', array( 'class' => 'mw-infobox-left' ) ) .
950 Html::element( 'img',
951 array(
952 'src' => $icon,
953 'alt' => $alt,
956 Html::closeElement( 'div' );
958 $s .= Html::openElement( 'div', array( 'class' => 'mw-infobox-right' ) ) .
959 $text .
960 Html::closeElement( 'div' );
961 $s .= Html::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
963 $s .= Html::closeElement( 'div' );
965 $s .= Html::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
967 return $s;
971 * Generate a srcset attribute value from an array mapping pixel densities
972 * to URLs. Note that srcset supports width and height values as well, which
973 * are not used here.
975 * @param array $urls
976 * @return string
978 static function srcSet( $urls ) {
979 $candidates = array();
980 foreach ( $urls as $density => $url ) {
981 // Image candidate syntax per current whatwg live spec, 2012-09-23:
982 // http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
983 $candidates[] = "{$url} {$density}x";
985 return implode( ", ", $candidates );