Do not allow a user to delete a page they can't edit
[mediawiki.git] / includes / Html.php
blob419250795dad18e98489d0f72bdcc2e504320378
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 * 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>"
230 * @since 1.17
231 * @param string $element Name of the element, e.g., 'a'
232 * @return string A closing tag
234 public static function closeElement( $element ) {
235 $element = strtolower( $element );
237 return "</$element>";
241 * Given an element name and an associative array of element attributes,
242 * return an array that is functionally identical to the input array, but
243 * possibly smaller. In particular, attributes might be stripped if they
244 * are given their default values.
246 * This method is not guaranteed to remove all redundant attributes, only
247 * some common ones and some others selected arbitrarily at random. It
248 * only guarantees that the output array should be functionally identical
249 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
251 * @param string $element Name of the element, e.g., 'a'
252 * @param array $attribs Associative array of attributes, e.g., array(
253 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
254 * further documentation.
255 * @return array An array of attributes functionally identical to $attribs
257 private static function dropDefaults( $element, $attribs ) {
259 // Whenever altering this array, please provide a covering test case
260 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
261 static $attribDefaults = array(
262 'area' => array( 'shape' => 'rect' ),
263 'button' => array(
264 'formaction' => 'GET',
265 'formenctype' => 'application/x-www-form-urlencoded',
267 'canvas' => array(
268 'height' => '150',
269 'width' => '300',
271 'command' => array( 'type' => 'command' ),
272 'form' => array(
273 'action' => 'GET',
274 'autocomplete' => 'on',
275 'enctype' => 'application/x-www-form-urlencoded',
277 'input' => array(
278 'formaction' => 'GET',
279 'type' => 'text',
281 'keygen' => array( 'keytype' => 'rsa' ),
282 'link' => array( 'media' => 'all' ),
283 'menu' => array( 'type' => 'list' ),
284 // Note: the use of text/javascript here instead of other JavaScript
285 // MIME types follows the HTML5 spec.
286 'script' => array( 'type' => 'text/javascript' ),
287 'style' => array(
288 'media' => 'all',
289 'type' => 'text/css',
291 'textarea' => array( 'wrap' => 'soft' ),
294 $element = strtolower( $element );
296 foreach ( $attribs as $attrib => $value ) {
297 $lcattrib = strtolower( $attrib );
298 if ( is_array( $value ) ) {
299 $value = implode( ' ', $value );
300 } else {
301 $value = strval( $value );
304 // Simple checks using $attribDefaults
305 if ( isset( $attribDefaults[$element][$lcattrib] ) &&
306 $attribDefaults[$element][$lcattrib] == $value ) {
307 unset( $attribs[$attrib] );
310 if ( $lcattrib == 'class' && $value == '' ) {
311 unset( $attribs[$attrib] );
315 // More subtle checks
316 if ( $element === 'link' && isset( $attribs['type'] )
317 && strval( $attribs['type'] ) == 'text/css' ) {
318 unset( $attribs['type'] );
320 if ( $element === 'input' ) {
321 $type = isset( $attribs['type'] ) ? $attribs['type'] : null;
322 $value = isset( $attribs['value'] ) ? $attribs['value'] : null;
323 if ( $type === 'checkbox' || $type === 'radio' ) {
324 // The default value for checkboxes and radio buttons is 'on'
325 // not ''. By stripping value="" we break radio boxes that
326 // actually wants empty values.
327 if ( $value === 'on' ) {
328 unset( $attribs['value'] );
330 } elseif ( $type === 'submit' ) {
331 // The default value for submit appears to be "Submit" but
332 // let's not bother stripping out localized text that matches
333 // that.
334 } else {
335 // The default value for nearly every other field type is ''
336 // The 'range' and 'color' types use different defaults but
337 // stripping a value="" does not hurt them.
338 if ( $value === '' ) {
339 unset( $attribs['value'] );
343 if ( $element === 'select' && isset( $attribs['size'] ) ) {
344 if ( in_array( 'multiple', $attribs )
345 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
347 // A multi-select
348 if ( strval( $attribs['size'] ) == '4' ) {
349 unset( $attribs['size'] );
351 } else {
352 // Single select
353 if ( strval( $attribs['size'] ) == '1' ) {
354 unset( $attribs['size'] );
359 return $attribs;
363 * Given an associative array of element attributes, generate a string
364 * to stick after the element name in HTML output. Like array( 'href' =>
365 * 'http://www.mediawiki.org/' ) becomes something like
366 * ' href="http://www.mediawiki.org"'. Again, this is like
367 * Xml::expandAttributes(), but it implements some HTML-specific logic.
368 * For instance, it will omit quotation marks if $wgWellFormedXml is false,
369 * and will treat boolean attributes specially.
371 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
372 * values are allowed as well, which will automagically be normalized
373 * and converted to a space-separated string. In addition to a numerical
374 * array, the attribute value may also be an associative array. See the
375 * example below for how that works.
377 * @par Numerical array
378 * @code
379 * Html::element( 'em', array(
380 * 'class' => array( 'foo', 'bar' )
381 * ) );
382 * // gives '<em class="foo bar"></em>'
383 * @endcode
385 * @par Associative array
386 * @code
387 * Html::element( 'em', array(
388 * 'class' => array( 'foo', 'bar', 'foo' => false, 'quux' => true )
389 * ) );
390 * // gives '<em class="bar quux"></em>'
391 * @endcode
393 * @param array $attribs Associative array of attributes, e.g., array(
394 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
395 * A value of false means to omit the attribute. For boolean attributes,
396 * you can omit the key, e.g., array( 'checked' ) instead of
397 * array( 'checked' => 'checked' ) or such.
399 * @throws MWException If an attribute that doesn't allow lists is set to an array
400 * @return string HTML fragment that goes between element name and '>'
401 * (starting with a space if at least one attribute is output)
403 public static function expandAttributes( $attribs ) {
404 global $wgWellFormedXml;
406 $ret = '';
407 $attribs = (array)$attribs;
408 foreach ( $attribs as $key => $value ) {
409 // Support intuitive array( 'checked' => true/false ) form
410 if ( $value === false || is_null( $value ) ) {
411 continue;
414 // For boolean attributes, support array( 'foo' ) instead of
415 // requiring array( 'foo' => 'meaningless' ).
416 if ( is_int( $key )
417 && in_array( strtolower( $value ), self::$boolAttribs ) ) {
418 $key = $value;
421 // Not technically required in HTML5 but we'd like consistency
422 // and better compression anyway.
423 $key = strtolower( $key );
425 // Bug 23769: Blacklist all form validation attributes for now. Current
426 // (June 2010) WebKit has no UI, so the form just refuses to submit
427 // without telling the user why, which is much worse than failing
428 // server-side validation. Opera is the only other implementation at
429 // this time, and has ugly UI, so just kill the feature entirely until
430 // we have at least one good implementation.
432 // As the default value of "1" for "step" rejects decimal
433 // numbers to be entered in 'type="number"' fields, allow
434 // the special case 'step="any"'.
436 if ( in_array( $key, array( 'max', 'min', 'pattern', 'required' ) )
437 || $key === 'step' && $value !== 'any' ) {
438 continue;
441 // http://www.w3.org/TR/html401/index/attributes.html ("space-separated")
442 // http://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
443 $spaceSeparatedListAttributes = array(
444 'class', // html4, html5
445 'accesskey', // as of html5, multiple space-separated values allowed
446 // html4-spec doesn't document rel= as space-separated
447 // but has been used like that and is now documented as such
448 // in the html5-spec.
449 'rel',
452 // Specific features for attributes that allow a list of space-separated values
453 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
454 // Apply some normalization and remove duplicates
456 // Convert into correct array. Array can contain space-separated
457 // values. Implode/explode to get those into the main array as well.
458 if ( is_array( $value ) ) {
459 // If input wasn't an array, we can skip this step
460 $newValue = array();
461 foreach ( $value as $k => $v ) {
462 if ( is_string( $v ) ) {
463 // String values should be normal `array( 'foo' )`
464 // Just append them
465 if ( !isset( $value[$v] ) ) {
466 // As a special case don't set 'foo' if a
467 // separate 'foo' => true/false exists in the array
468 // keys should be authoritative
469 $newValue[] = $v;
471 } elseif ( $v ) {
472 // If the value is truthy but not a string this is likely
473 // an array( 'foo' => true ), falsy values don't add strings
474 $newValue[] = $k;
477 $value = implode( ' ', $newValue );
479 $value = explode( ' ', $value );
481 // Normalize spacing by fixing up cases where people used
482 // more than 1 space and/or a trailing/leading space
483 $value = array_diff( $value, array( '', ' ' ) );
485 // Remove duplicates and create the string
486 $value = implode( ' ', array_unique( $value ) );
487 } elseif ( is_array( $value ) ) {
488 throw new MWException( "HTML attribute $key can not contain a list of values" );
491 // See the "Attributes" section in the HTML syntax part of HTML5,
492 // 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
493 // marks omitted, but not all. (Although a literal " is not
494 // permitted, we don't check for that, since it will be escaped
495 // anyway.)
497 // See also research done on further characters that need to be
498 // escaped: http://code.google.com/p/html5lib/issues/detail?id=93
499 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
500 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
501 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
502 if ( $wgWellFormedXml || $value === ''
503 || preg_match( "![$badChars]!u", $value ) ) {
504 $quote = '"';
505 } else {
506 $quote = '';
509 if ( in_array( $key, self::$boolAttribs ) ) {
510 // In HTML5, we can leave the value empty. If we don't need
511 // well-formed XML, we can omit the = entirely.
512 if ( !$wgWellFormedXml ) {
513 $ret .= " $key";
514 } else {
515 $ret .= " $key=\"\"";
517 } else {
518 // Apparently we need to entity-encode \n, \r, \t, although the
519 // spec doesn't mention that. Since we're doing strtr() anyway,
520 // and we don't need <> escaped here, we may as well not call
521 // htmlspecialchars().
522 // @todo FIXME: Verify that we actually need to
523 // escape \n\r\t here, and explain why, exactly.
525 // We could call Sanitizer::encodeAttribute() for this, but we
526 // don't because we're stubborn and like our marginal savings on
527 // byte size from not having to encode unnecessary quotes.
528 $map = array(
529 '&' => '&amp;',
530 '"' => '&quot;',
531 "\n" => '&#10;',
532 "\r" => '&#13;',
533 "\t" => '&#9;'
535 if ( $wgWellFormedXml ) {
536 // This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
537 // But reportedly it breaks some XML tools?
538 // @todo FIXME: Is this really true?
539 $map['<'] = '&lt;';
541 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
544 return $ret;
548 * Output a "<script>" tag with the given contents.
550 * @todo do some useful escaping as well, like if $contents contains
551 * literal "</script>" or (for XML) literal "]]>".
553 * @param string $contents JavaScript
554 * @return string Raw HTML
556 public static function inlineScript( $contents ) {
557 global $wgWellFormedXml;
559 $attrs = array();
561 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
562 $contents = "/*<![CDATA[*/$contents/*]]>*/";
565 return self::rawElement( 'script', $attrs, $contents );
569 * Output a "<script>" tag linking to the given URL, e.g.,
570 * "<script src=foo.js></script>".
572 * @param string $url
573 * @return string Raw HTML
575 public static function linkedScript( $url ) {
576 $attrs = array( 'src' => $url );
578 return self::element( 'script', $attrs );
582 * Output a "<style>" tag with the given contents for the given media type
583 * (if any). TODO: do some useful escaping as well, like if $contents
584 * contains literal "</style>" (admittedly unlikely).
586 * @param string $contents CSS
587 * @param string $media A media type string, like 'screen'
588 * @return string Raw HTML
590 public static function inlineStyle( $contents, $media = 'all' ) {
591 global $wgWellFormedXml;
593 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
594 $contents = "/*<![CDATA[*/$contents/*]]>*/";
597 return self::rawElement( 'style', array(
598 'type' => 'text/css',
599 'media' => $media,
600 ), $contents );
604 * Output a "<link rel=stylesheet>" linking to the given URL for the given
605 * media type (if any).
607 * @param string $url
608 * @param string $media A media type string, like 'screen'
609 * @return string Raw HTML
611 public static function linkedStyle( $url, $media = 'all' ) {
612 return self::element( 'link', array(
613 'rel' => 'stylesheet',
614 'href' => $url,
615 'type' => 'text/css',
616 'media' => $media,
617 ) );
621 * Convenience function to produce an "<input>" element. This supports the
622 * new HTML5 input types and attributes.
624 * @param string $name Name attribute
625 * @param array $value Value attribute
626 * @param string $type Type attribute
627 * @param array $attribs Associative array of miscellaneous extra
628 * attributes, passed to Html::element()
629 * @return string Raw HTML
631 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
632 $attribs['type'] = $type;
633 $attribs['value'] = $value;
634 $attribs['name'] = $name;
636 return self::element( 'input', $attribs );
640 * Convenience function to produce a checkbox (input element with type=checkbox)
642 * @param string $name Name attribute
643 * @param bool $checked Whether the checkbox is checked or not
644 * @param array $attribs Array of additional attributes
646 public static function check( $name, $checked = false, array $attribs = array() ) {
647 if ( isset( $attribs['value'] ) ) {
648 $value = $attribs['value'];
649 unset( $attribs['value'] );
650 } else {
651 $value = 1;
654 if ( $checked ) {
655 $attribs[] = 'checked';
658 return self::input( $name, $value, 'checkbox', $attribs );
662 * Convenience function to produce a checkbox (input element with type=checkbox)
664 * @param string $name Name attribute
665 * @param bool $checked Whether the checkbox is checked or not
666 * @param array $attribs Array of additional attributes
668 public static function radio( $name, $checked = false, array $attribs = array() ) {
669 if ( isset( $attribs['value'] ) ) {
670 $value = $attribs['value'];
671 unset( $attribs['value'] );
672 } else {
673 $value = 1;
676 if ( $checked ) {
677 $attribs[] = 'checked';
680 return self::input( $name, $value, 'radio', $attribs );
684 * Convenience function for generating a label for inputs.
686 * @param string $label Contents of the label
687 * @param string $id ID of the element being labeled
688 * @param array $attribs Additional attributes
690 public static function label( $label, $id, array $attribs = array() ) {
691 $attribs += array(
692 'for' => $id
694 return self::element( 'label', $attribs, $label );
698 * Convenience function to produce an input element with type=hidden
700 * @param string $name Name attribute
701 * @param string $value Value attribute
702 * @param array $attribs Associative array of miscellaneous extra
703 * attributes, passed to Html::element()
704 * @return string Raw HTML
706 public static function hidden( $name, $value, $attribs = array() ) {
707 return self::input( $name, $value, 'hidden', $attribs );
711 * Convenience function to produce a <textarea> element.
713 * This supports leaving out the cols= and rows= which Xml requires and are
714 * required by HTML4/XHTML but not required by HTML5.
716 * @param string $name Name attribute
717 * @param string $value Value attribute
718 * @param array $attribs Associative array of miscellaneous extra
719 * attributes, passed to Html::element()
720 * @return string Raw HTML
722 public static function textarea( $name, $value = '', $attribs = array() ) {
723 $attribs['name'] = $name;
725 if ( substr( $value, 0, 1 ) == "\n" ) {
726 // Workaround for bug 12130: browsers eat the initial newline
727 // assuming that it's just for show, but they do keep the later
728 // newlines, which we may want to preserve during editing.
729 // Prepending a single newline
730 $spacedValue = "\n" . $value;
731 } else {
732 $spacedValue = $value;
734 return self::element( 'textarea', $attribs, $spacedValue );
738 * Build a drop-down box for selecting a namespace
740 * @param array $params Params to set.
741 * - selected: [optional] Id of namespace which should be pre-selected
742 * - all: [optional] Value of item for "all namespaces". If null or unset,
743 * no "<option>" is generated to select all namespaces.
744 * - label: text for label to add before the field.
745 * - exclude: [optional] Array of namespace ids to exclude.
746 * - disable: [optional] Array of namespace ids for which the option should
747 * be disabled in the selector.
748 * @param array $selectAttribs HTML attributes for the generated select element.
749 * - id: [optional], default: 'namespace'.
750 * - name: [optional], default: 'namespace'.
751 * @return string HTML code to select a namespace.
753 public static function namespaceSelector( array $params = array(),
754 array $selectAttribs = array()
756 global $wgContLang;
758 ksort( $selectAttribs );
760 // Is a namespace selected?
761 if ( isset( $params['selected'] ) ) {
762 // If string only contains digits, convert to clean int. Selected could also
763 // be "all" or "" etc. which needs to be left untouched.
764 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
765 // and returns false for already clean ints. Use regex instead..
766 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
767 $params['selected'] = intval( $params['selected'] );
769 // else: leaves it untouched for later processing
770 } else {
771 $params['selected'] = '';
774 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
775 $params['exclude'] = array();
777 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
778 $params['disable'] = array();
781 // Associative array between option-values and option-labels
782 $options = array();
784 if ( isset( $params['all'] ) ) {
785 // add an option that would let the user select all namespaces.
786 // Value is provided by user, the name shown is localized for the user.
787 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
789 // Add all namespaces as options (in the content language)
790 $options += $wgContLang->getFormattedNamespaces();
792 // Convert $options to HTML and filter out namespaces below 0
793 $optionsHtml = array();
794 foreach ( $options as $nsId => $nsName ) {
795 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
796 continue;
798 if ( $nsId === NS_MAIN ) {
799 // For other namespaces use use the namespace prefix as label, but for
800 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
801 $nsName = wfMessage( 'blanknamespace' )->text();
802 } elseif ( is_int( $nsId ) ) {
803 $nsName = $wgContLang->convertNamespace( $nsId );
805 $optionsHtml[] = Html::element(
806 'option', array(
807 'disabled' => in_array( $nsId, $params['disable'] ),
808 'value' => $nsId,
809 'selected' => $nsId === $params['selected'],
810 ), $nsName
814 if ( !array_key_exists( 'id', $selectAttribs ) ) {
815 $selectAttribs['id'] = 'namespace';
818 if ( !array_key_exists( 'name', $selectAttribs ) ) {
819 $selectAttribs['name'] = 'namespace';
822 $ret = '';
823 if ( isset( $params['label'] ) ) {
824 $ret .= Html::element(
825 'label', array(
826 'for' => isset( $selectAttribs['id'] ) ? $selectAttribs['id'] : null,
827 ), $params['label']
828 ) . '&#160;';
831 // Wrap options in a <select>
832 $ret .= Html::openElement( 'select', $selectAttribs )
833 . "\n"
834 . implode( "\n", $optionsHtml )
835 . "\n"
836 . Html::closeElement( 'select' );
838 return $ret;
842 * Constructs the opening html-tag with necessary doctypes depending on
843 * global variables.
845 * @param array $attribs Associative array of miscellaneous extra
846 * attributes, passed to Html::element() of html tag.
847 * @return string Raw HTML
849 public static function htmlHeader( $attribs = array() ) {
850 $ret = '';
852 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
854 $isXHTML = self::isXmlMimeType( $wgMimeType );
856 if ( $isXHTML ) { // XHTML5
857 // XML MIME-typed markup should have an xml header.
858 // However a DOCTYPE is not needed.
859 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
861 // Add the standard xmlns
862 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
864 // And support custom namespaces
865 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
866 $attribs["xmlns:$tag"] = $ns;
868 } else { // HTML5
869 // DOCTYPE
870 $ret .= "<!DOCTYPE html>\n";
873 if ( $wgHtml5Version ) {
874 $attribs['version'] = $wgHtml5Version;
877 $html = Html::openElement( 'html', $attribs );
879 if ( $html ) {
880 $html .= "\n";
883 $ret .= $html;
885 return $ret;
889 * Determines if the given MIME type is xml.
891 * @param string $mimetype MIME type
892 * @return bool
894 public static function isXmlMimeType( $mimetype ) {
895 # http://www.whatwg.org/html/infrastructure.html#xml-mime-type
896 # * text/xml
897 # * application/xml
898 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
899 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
903 * Get HTML for an info box with an icon.
905 * @param string $text Wikitext, get this with wfMessage()->plain()
906 * @param string $icon Icon name, file in skins/common/images
907 * @param string $alt Alternate text for the icon
908 * @param string $class Additional class name to add to the wrapper div
909 * @param bool $useStylePath
911 * @return string
913 static function infoBox( $text, $icon, $alt, $class = false, $useStylePath = true ) {
914 global $wgStylePath;
916 if ( $useStylePath ) {
917 $icon = $wgStylePath . '/common/images/' . $icon;
920 $s = Html::openElement( 'div', array( 'class' => "mw-infobox $class" ) );
922 $s .= Html::openElement( 'div', array( 'class' => 'mw-infobox-left' ) ) .
923 Html::element( 'img',
924 array(
925 'src' => $icon,
926 'alt' => $alt,
929 Html::closeElement( 'div' );
931 $s .= Html::openElement( 'div', array( 'class' => 'mw-infobox-right' ) ) .
932 $text .
933 Html::closeElement( 'div' );
934 $s .= Html::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
936 $s .= Html::closeElement( 'div' );
938 $s .= Html::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
940 return $s;
944 * Generate a srcset attribute value from an array mapping pixel densities
945 * to URLs. Note that srcset supports width and height values as well, which
946 * are not used here.
948 * @param array $urls
949 * @return string
951 static function srcSet( $urls ) {
952 $candidates = array();
953 foreach ( $urls as $density => $url ) {
954 // Image candidate syntax per current whatwg live spec, 2012-09-23:
955 // http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
956 $candidates[] = "{$url} {$density}x";
958 return implode( ", ", $candidates );