Only store currently-existing categories in the categories table
[mediawiki.git] / includes / Html.php
blobe5128d166c6d684f15f00c9a38c077cb7e7f1a44
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.
42 * This class is meant to be confined to utility functions that are called from
43 * trusted code paths. It does not do enforcement of policy like not allowing
44 * <a> elements.
46 * @since 1.16
48 class Html {
49 // List of void elements from HTML5, section 8.1.2 as of 2011-08-12
50 private static $voidElements = [
51 'area',
52 'base',
53 'br',
54 'col',
55 'command',
56 'embed',
57 'hr',
58 'img',
59 'input',
60 'keygen',
61 'link',
62 'meta',
63 'param',
64 'source',
65 'track',
66 'wbr',
69 // Boolean attributes, which may have the value omitted entirely. Manually
70 // collected from the HTML5 spec as of 2011-08-12.
71 private static $boolAttribs = [
72 'async',
73 'autofocus',
74 'autoplay',
75 'checked',
76 'controls',
77 'default',
78 'defer',
79 'disabled',
80 'formnovalidate',
81 'hidden',
82 'ismap',
83 'itemscope',
84 'loop',
85 'multiple',
86 'muted',
87 'novalidate',
88 'open',
89 'pubdate',
90 'readonly',
91 'required',
92 'reversed',
93 'scoped',
94 'seamless',
95 'selected',
96 'truespeed',
97 'typemustmatch',
98 // HTML5 Microdata
99 'itemscope',
103 * Modifies a set of attributes meant for button elements
104 * and apply a set of default attributes when $wgUseMediaWikiUIEverywhere enabled.
105 * @param array $attrs HTML attributes in an associative array
106 * @param string[] $modifiers classes to add to the button
107 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
108 * @return array $attrs A modified attribute array
110 public static function buttonAttributes( array $attrs, array $modifiers = [] ) {
111 global $wgUseMediaWikiUIEverywhere;
112 if ( $wgUseMediaWikiUIEverywhere ) {
113 if ( isset( $attrs['class'] ) ) {
114 if ( is_array( $attrs['class'] ) ) {
115 $attrs['class'][] = 'mw-ui-button';
116 $attrs['class'] = array_merge( $attrs['class'], $modifiers );
117 // ensure compatibility with Xml
118 $attrs['class'] = implode( ' ', $attrs['class'] );
119 } else {
120 $attrs['class'] .= ' mw-ui-button ' . implode( ' ', $modifiers );
122 } else {
123 // ensure compatibility with Xml
124 $attrs['class'] = 'mw-ui-button ' . implode( ' ', $modifiers );
127 return $attrs;
131 * Modifies a set of attributes meant for text input elements
132 * and apply a set of default attributes.
133 * Removes size attribute when $wgUseMediaWikiUIEverywhere enabled.
134 * @param array $attrs An attribute array.
135 * @return array $attrs A modified attribute array
137 public static function getTextInputAttributes( array $attrs ) {
138 global $wgUseMediaWikiUIEverywhere;
139 if ( $wgUseMediaWikiUIEverywhere ) {
140 if ( isset( $attrs['class'] ) ) {
141 if ( is_array( $attrs['class'] ) ) {
142 $attrs['class'][] = 'mw-ui-input';
143 } else {
144 $attrs['class'] .= ' mw-ui-input';
146 } else {
147 $attrs['class'] = 'mw-ui-input';
150 return $attrs;
154 * Returns an HTML link element in a string styled as a button
155 * (when $wgUseMediaWikiUIEverywhere is enabled).
157 * @param string $contents The raw HTML contents of the element: *not*
158 * escaped!
159 * @param array $attrs Associative array of attributes, e.g., array(
160 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
161 * further documentation.
162 * @param string[] $modifiers classes to add to the button
163 * @see http://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
164 * @return string Raw HTML
166 public static function linkButton( $contents, array $attrs, array $modifiers = [] ) {
167 return self::element( 'a',
168 self::buttonAttributes( $attrs, $modifiers ),
169 $contents
174 * Returns an HTML link element in a string styled as a button
175 * (when $wgUseMediaWikiUIEverywhere is enabled).
177 * @param string $contents The raw HTML contents of the element: *not*
178 * escaped!
179 * @param array $attrs Associative array of attributes, e.g., array(
180 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
181 * further documentation.
182 * @param string[] $modifiers classes to add to the button
183 * @see http://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
184 * @return string Raw HTML
186 public static function submitButton( $contents, array $attrs, array $modifiers = [] ) {
187 $attrs['type'] = 'submit';
188 $attrs['value'] = $contents;
189 return self::element( 'input', self::buttonAttributes( $attrs, $modifiers ) );
193 * Returns an HTML element in a string. The major advantage here over
194 * manually typing out the HTML is that it will escape all attribute
195 * values.
197 * This is quite similar to Xml::tags(), but it implements some useful
198 * HTML-specific logic. For instance, there is no $allowShortTag
199 * parameter: the closing tag is magically omitted if $element has an empty
200 * content model.
202 * @param string $element The element's name, e.g., 'a'
203 * @param array $attribs Associative array of attributes, e.g., array(
204 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
205 * further documentation.
206 * @param string $contents The raw HTML contents of the element: *not*
207 * escaped!
208 * @return string Raw HTML
210 public static function rawElement( $element, $attribs = [], $contents = '' ) {
211 $start = self::openElement( $element, $attribs );
212 if ( in_array( $element, self::$voidElements ) ) {
213 // Silly XML.
214 return substr( $start, 0, -1 ) . '/>';
215 } else {
216 return "$start$contents" . self::closeElement( $element );
221 * Identical to rawElement(), but HTML-escapes $contents (like
222 * Xml::element()).
224 * @param string $element
225 * @param array $attribs
226 * @param string $contents
228 * @return string
230 public static function element( $element, $attribs = [], $contents = '' ) {
231 return self::rawElement( $element, $attribs, strtr( $contents, [
232 // There's no point in escaping quotes, >, etc. in the contents of
233 // elements.
234 '&' => '&amp;',
235 '<' => '&lt;'
236 ] ) );
240 * Identical to rawElement(), but has no third parameter and omits the end
241 * tag (and the self-closing '/' in XML mode for empty elements).
243 * @param string $element
244 * @param array $attribs
246 * @return string
248 public static function openElement( $element, $attribs = [] ) {
249 $attribs = (array)$attribs;
250 // This is not required in HTML5, but let's do it anyway, for
251 // consistency and better compression.
252 $element = strtolower( $element );
254 // Remove invalid input types
255 if ( $element == 'input' ) {
256 $validTypes = [
257 'hidden',
258 'text',
259 'password',
260 'checkbox',
261 'radio',
262 'file',
263 'submit',
264 'image',
265 'reset',
266 'button',
268 // HTML input types
269 'datetime',
270 'datetime-local',
271 'date',
272 'month',
273 'time',
274 'week',
275 'number',
276 'range',
277 'email',
278 'url',
279 'search',
280 'tel',
281 'color',
283 if ( isset( $attribs['type'] ) && !in_array( $attribs['type'], $validTypes ) ) {
284 unset( $attribs['type'] );
288 // According to standard the default type for <button> elements is "submit".
289 // Depending on compatibility mode IE might use "button", instead.
290 // We enforce the standard "submit".
291 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
292 $attribs['type'] = 'submit';
295 return "<$element" . self::expandAttributes(
296 self::dropDefaults( $element, $attribs ) ) . '>';
300 * Returns "</$element>"
302 * @since 1.17
303 * @param string $element Name of the element, e.g., 'a'
304 * @return string A closing tag
306 public static function closeElement( $element ) {
307 $element = strtolower( $element );
309 return "</$element>";
313 * Given an element name and an associative array of element attributes,
314 * return an array that is functionally identical to the input array, but
315 * possibly smaller. In particular, attributes might be stripped if they
316 * are given their default values.
318 * This method is not guaranteed to remove all redundant attributes, only
319 * some common ones and some others selected arbitrarily at random. It
320 * only guarantees that the output array should be functionally identical
321 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
323 * @param string $element Name of the element, e.g., 'a'
324 * @param array $attribs Associative array of attributes, e.g., array(
325 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
326 * further documentation.
327 * @return array An array of attributes functionally identical to $attribs
329 private static function dropDefaults( $element, array $attribs ) {
330 // Whenever altering this array, please provide a covering test case
331 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
332 static $attribDefaults = [
333 'area' => [ 'shape' => 'rect' ],
334 'button' => [
335 'formaction' => 'GET',
336 'formenctype' => 'application/x-www-form-urlencoded',
338 'canvas' => [
339 'height' => '150',
340 'width' => '300',
342 'command' => [ 'type' => 'command' ],
343 'form' => [
344 'action' => 'GET',
345 'autocomplete' => 'on',
346 'enctype' => 'application/x-www-form-urlencoded',
348 'input' => [
349 'formaction' => 'GET',
350 'type' => 'text',
352 'keygen' => [ 'keytype' => 'rsa' ],
353 'link' => [ 'media' => 'all' ],
354 'menu' => [ 'type' => 'list' ],
355 'script' => [ 'type' => 'text/javascript' ],
356 'style' => [
357 'media' => 'all',
358 'type' => 'text/css',
360 'textarea' => [ 'wrap' => 'soft' ],
363 $element = strtolower( $element );
365 foreach ( $attribs as $attrib => $value ) {
366 $lcattrib = strtolower( $attrib );
367 if ( is_array( $value ) ) {
368 $value = implode( ' ', $value );
369 } else {
370 $value = strval( $value );
373 // Simple checks using $attribDefaults
374 if ( isset( $attribDefaults[$element][$lcattrib] )
375 && $attribDefaults[$element][$lcattrib] == $value
377 unset( $attribs[$attrib] );
380 if ( $lcattrib == 'class' && $value == '' ) {
381 unset( $attribs[$attrib] );
385 // More subtle checks
386 if ( $element === 'link'
387 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
389 unset( $attribs['type'] );
391 if ( $element === 'input' ) {
392 $type = isset( $attribs['type'] ) ? $attribs['type'] : null;
393 $value = isset( $attribs['value'] ) ? $attribs['value'] : null;
394 if ( $type === 'checkbox' || $type === 'radio' ) {
395 // The default value for checkboxes and radio buttons is 'on'
396 // not ''. By stripping value="" we break radio boxes that
397 // actually wants empty values.
398 if ( $value === 'on' ) {
399 unset( $attribs['value'] );
401 } elseif ( $type === 'submit' ) {
402 // The default value for submit appears to be "Submit" but
403 // let's not bother stripping out localized text that matches
404 // that.
405 } else {
406 // The default value for nearly every other field type is ''
407 // The 'range' and 'color' types use different defaults but
408 // stripping a value="" does not hurt them.
409 if ( $value === '' ) {
410 unset( $attribs['value'] );
414 if ( $element === 'select' && isset( $attribs['size'] ) ) {
415 if ( in_array( 'multiple', $attribs )
416 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
418 // A multi-select
419 if ( strval( $attribs['size'] ) == '4' ) {
420 unset( $attribs['size'] );
422 } else {
423 // Single select
424 if ( strval( $attribs['size'] ) == '1' ) {
425 unset( $attribs['size'] );
430 return $attribs;
434 * Given an associative array of element attributes, generate a string
435 * to stick after the element name in HTML output. Like array( 'href' =>
436 * 'http://www.mediawiki.org/' ) becomes something like
437 * ' href="http://www.mediawiki.org"'. Again, this is like
438 * Xml::expandAttributes(), but it implements some HTML-specific logic.
440 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
441 * values are allowed as well, which will automagically be normalized
442 * and converted to a space-separated string. In addition to a numerical
443 * array, the attribute value may also be an associative array. See the
444 * example below for how that works.
446 * @par Numerical array
447 * @code
448 * Html::element( 'em', array(
449 * 'class' => array( 'foo', 'bar' )
450 * ) );
451 * // gives '<em class="foo bar"></em>'
452 * @endcode
454 * @par Associative array
455 * @code
456 * Html::element( 'em', array(
457 * 'class' => array( 'foo', 'bar', 'foo' => false, 'quux' => true )
458 * ) );
459 * // gives '<em class="bar quux"></em>'
460 * @endcode
462 * @param array $attribs Associative array of attributes, e.g., array(
463 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
464 * A value of false means to omit the attribute. For boolean attributes,
465 * you can omit the key, e.g., array( 'checked' ) instead of
466 * array( 'checked' => 'checked' ) or such.
468 * @throws MWException If an attribute that doesn't allow lists is set to an array
469 * @return string HTML fragment that goes between element name and '>'
470 * (starting with a space if at least one attribute is output)
472 public static function expandAttributes( array $attribs ) {
473 $ret = '';
474 foreach ( $attribs as $key => $value ) {
475 // Support intuitive array( 'checked' => true/false ) form
476 if ( $value === false || is_null( $value ) ) {
477 continue;
480 // For boolean attributes, support array( 'foo' ) instead of
481 // requiring array( 'foo' => 'meaningless' ).
482 if ( is_int( $key ) && in_array( strtolower( $value ), self::$boolAttribs ) ) {
483 $key = $value;
486 // Not technically required in HTML5 but we'd like consistency
487 // and better compression anyway.
488 $key = strtolower( $key );
490 // Bug 23769: Blacklist all form validation attributes for now. Current
491 // (June 2010) WebKit has no UI, so the form just refuses to submit
492 // without telling the user why, which is much worse than failing
493 // server-side validation. Opera is the only other implementation at
494 // this time, and has ugly UI, so just kill the feature entirely until
495 // we have at least one good implementation.
497 // As the default value of "1" for "step" rejects decimal
498 // numbers to be entered in 'type="number"' fields, allow
499 // the special case 'step="any"'.
501 if ( in_array( $key, [ 'max', 'min', 'pattern', 'required' ] )
502 || $key === 'step' && $value !== 'any' ) {
503 continue;
506 // http://www.w3.org/TR/html401/index/attributes.html ("space-separated")
507 // http://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
508 $spaceSeparatedListAttributes = [
509 'class', // html4, html5
510 'accesskey', // as of html5, multiple space-separated values allowed
511 // html4-spec doesn't document rel= as space-separated
512 // but has been used like that and is now documented as such
513 // in the html5-spec.
514 'rel',
517 // Specific features for attributes that allow a list of space-separated values
518 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
519 // Apply some normalization and remove duplicates
521 // Convert into correct array. Array can contain space-separated
522 // values. Implode/explode to get those into the main array as well.
523 if ( is_array( $value ) ) {
524 // If input wasn't an array, we can skip this step
525 $newValue = [];
526 foreach ( $value as $k => $v ) {
527 if ( is_string( $v ) ) {
528 // String values should be normal `array( 'foo' )`
529 // Just append them
530 if ( !isset( $value[$v] ) ) {
531 // As a special case don't set 'foo' if a
532 // separate 'foo' => true/false exists in the array
533 // keys should be authoritative
534 $newValue[] = $v;
536 } elseif ( $v ) {
537 // If the value is truthy but not a string this is likely
538 // an array( 'foo' => true ), falsy values don't add strings
539 $newValue[] = $k;
542 $value = implode( ' ', $newValue );
544 $value = explode( ' ', $value );
546 // Normalize spacing by fixing up cases where people used
547 // more than 1 space and/or a trailing/leading space
548 $value = array_diff( $value, [ '', ' ' ] );
550 // Remove duplicates and create the string
551 $value = implode( ' ', array_unique( $value ) );
552 } elseif ( is_array( $value ) ) {
553 throw new MWException( "HTML attribute $key can not contain a list of values" );
556 $quote = '"';
558 if ( in_array( $key, self::$boolAttribs ) ) {
559 $ret .= " $key=\"\"";
560 } else {
561 // Apparently we need to entity-encode \n, \r, \t, although the
562 // spec doesn't mention that. Since we're doing strtr() anyway,
563 // we may as well not call htmlspecialchars().
564 // @todo FIXME: Verify that we actually need to
565 // escape \n\r\t here, and explain why, exactly.
566 // We could call Sanitizer::encodeAttribute() for this, but we
567 // don't because we're stubborn and like our marginal savings on
568 // byte size from not having to encode unnecessary quotes.
569 // The only difference between this transform and the one by
570 // Sanitizer::encodeAttribute() is ' is not encoded.
571 $map = [
572 '&' => '&amp;',
573 '"' => '&quot;',
574 '>' => '&gt;',
575 // '<' allegedly allowed per spec
576 // but breaks some tools if not escaped.
577 "<" => '&lt;',
578 "\n" => '&#10;',
579 "\r" => '&#13;',
580 "\t" => '&#9;'
582 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
585 return $ret;
589 * Output a "<script>" tag with the given contents.
591 * @todo do some useful escaping as well, like if $contents contains
592 * literal "</script>" or (for XML) literal "]]>".
594 * @param string $contents JavaScript
595 * @return string Raw HTML
597 public static function inlineScript( $contents ) {
598 $attrs = [];
600 if ( preg_match( '/[<&]/', $contents ) ) {
601 $contents = "/*<![CDATA[*/$contents/*]]>*/";
604 return self::rawElement( 'script', $attrs, $contents );
608 * Output a "<script>" tag linking to the given URL, e.g.,
609 * "<script src=foo.js></script>".
611 * @param string $url
612 * @return string Raw HTML
614 public static function linkedScript( $url ) {
615 $attrs = [ 'src' => $url ];
617 return self::element( 'script', $attrs );
621 * Output a "<style>" tag with the given contents for the given media type
622 * (if any). TODO: do some useful escaping as well, like if $contents
623 * contains literal "</style>" (admittedly unlikely).
625 * @param string $contents CSS
626 * @param string $media A media type string, like 'screen'
627 * @return string Raw HTML
629 public static function inlineStyle( $contents, $media = 'all' ) {
630 if ( preg_match( '/[<&]/', $contents ) ) {
631 $contents = "/*<![CDATA[*/$contents/*]]>*/";
634 return self::rawElement( 'style', [
635 'media' => $media,
636 ], $contents );
640 * Output a "<link rel=stylesheet>" linking to the given URL for the given
641 * media type (if any).
643 * @param string $url
644 * @param string $media A media type string, like 'screen'
645 * @return string Raw HTML
647 public static function linkedStyle( $url, $media = 'all' ) {
648 return self::element( 'link', [
649 'rel' => 'stylesheet',
650 'href' => $url,
651 'media' => $media,
652 ] );
656 * Convenience function to produce an "<input>" element. This supports the
657 * new HTML5 input types and attributes.
659 * @param string $name Name attribute
660 * @param string $value Value attribute
661 * @param string $type Type attribute
662 * @param array $attribs Associative array of miscellaneous extra
663 * attributes, passed to Html::element()
664 * @return string Raw HTML
666 public static function input( $name, $value = '', $type = 'text', array $attribs = [] ) {
667 $attribs['type'] = $type;
668 $attribs['value'] = $value;
669 $attribs['name'] = $name;
670 if ( in_array( $type, [ 'text', 'search', 'email', 'password', 'number' ] ) ) {
671 $attribs = self::getTextInputAttributes( $attribs );
673 if ( in_array( $type, [ 'button', 'reset', 'submit' ] ) ) {
674 $attribs = self::buttonAttributes( $attribs );
676 return self::element( 'input', $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
685 * @return string Raw HTML
687 public static function check( $name, $checked = false, array $attribs = [] ) {
688 if ( isset( $attribs['value'] ) ) {
689 $value = $attribs['value'];
690 unset( $attribs['value'] );
691 } else {
692 $value = 1;
695 if ( $checked ) {
696 $attribs[] = 'checked';
699 return self::input( $name, $value, 'checkbox', $attribs );
703 * Convenience function to produce a radio button (input element with type=radio)
705 * @param string $name Name attribute
706 * @param bool $checked Whether the radio button is checked or not
707 * @param array $attribs Array of additional attributes
708 * @return string Raw HTML
710 public static function radio( $name, $checked = false, array $attribs = [] ) {
711 if ( isset( $attribs['value'] ) ) {
712 $value = $attribs['value'];
713 unset( $attribs['value'] );
714 } else {
715 $value = 1;
718 if ( $checked ) {
719 $attribs[] = 'checked';
722 return self::input( $name, $value, 'radio', $attribs );
726 * Convenience function for generating a label for inputs.
728 * @param string $label Contents of the label
729 * @param string $id ID of the element being labeled
730 * @param array $attribs Additional attributes
731 * @return string Raw HTML
733 public static function label( $label, $id, array $attribs = [] ) {
734 $attribs += [
735 'for' => $id
737 return self::element( 'label', $attribs, $label );
741 * Convenience function to produce an input element with type=hidden
743 * @param string $name Name attribute
744 * @param string $value Value attribute
745 * @param array $attribs Associative array of miscellaneous extra
746 * attributes, passed to Html::element()
747 * @return string Raw HTML
749 public static function hidden( $name, $value, array $attribs = [] ) {
750 return self::input( $name, $value, 'hidden', $attribs );
754 * Convenience function to produce a <textarea> element.
756 * This supports leaving out the cols= and rows= which Xml requires and are
757 * required by HTML4/XHTML but not required by HTML5.
759 * @param string $name Name attribute
760 * @param string $value Value attribute
761 * @param array $attribs Associative array of miscellaneous extra
762 * attributes, passed to Html::element()
763 * @return string Raw HTML
765 public static function textarea( $name, $value = '', array $attribs = [] ) {
766 $attribs['name'] = $name;
768 if ( substr( $value, 0, 1 ) == "\n" ) {
769 // Workaround for bug 12130: browsers eat the initial newline
770 // assuming that it's just for show, but they do keep the later
771 // newlines, which we may want to preserve during editing.
772 // Prepending a single newline
773 $spacedValue = "\n" . $value;
774 } else {
775 $spacedValue = $value;
777 return self::element( 'textarea', self::getTextInputAttributes( $attribs ), $spacedValue );
781 * Helper for Html::namespaceSelector().
782 * @param array $params See Html::namespaceSelector()
783 * @return array
785 public static function namespaceSelectorOptions( array $params = [] ) {
786 global $wgContLang;
788 $options = [];
790 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
791 $params['exclude'] = [];
794 if ( isset( $params['all'] ) ) {
795 // add an option that would let the user select all namespaces.
796 // Value is provided by user, the name shown is localized for the user.
797 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
799 // Add all namespaces as options (in the content language)
800 $options += $wgContLang->getFormattedNamespaces();
802 $optionsOut = [];
803 // Filter out namespaces below 0 and massage labels
804 foreach ( $options as $nsId => $nsName ) {
805 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
806 continue;
808 if ( $nsId === NS_MAIN ) {
809 // For other namespaces use the namespace prefix as label, but for
810 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
811 $nsName = wfMessage( 'blanknamespace' )->text();
812 } elseif ( is_int( $nsId ) ) {
813 $nsName = $wgContLang->convertNamespace( $nsId );
815 $optionsOut[$nsId] = $nsName;
818 return $optionsOut;
822 * Build a drop-down box for selecting a namespace
824 * @param array $params Params to set.
825 * - selected: [optional] Id of namespace which should be pre-selected
826 * - all: [optional] Value of item for "all namespaces". If null or unset,
827 * no "<option>" is generated to select all namespaces.
828 * - label: text for label to add before the field.
829 * - exclude: [optional] Array of namespace ids to exclude.
830 * - disable: [optional] Array of namespace ids for which the option should
831 * be disabled in the selector.
832 * @param array $selectAttribs HTML attributes for the generated select element.
833 * - id: [optional], default: 'namespace'.
834 * - name: [optional], default: 'namespace'.
835 * @return string HTML code to select a namespace.
837 public static function namespaceSelector( array $params = [],
838 array $selectAttribs = []
840 ksort( $selectAttribs );
842 // Is a namespace selected?
843 if ( isset( $params['selected'] ) ) {
844 // If string only contains digits, convert to clean int. Selected could also
845 // be "all" or "" etc. which needs to be left untouched.
846 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
847 // and returns false for already clean ints. Use regex instead..
848 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
849 $params['selected'] = intval( $params['selected'] );
851 // else: leaves it untouched for later processing
852 } else {
853 $params['selected'] = '';
856 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
857 $params['disable'] = [];
860 // Associative array between option-values and option-labels
861 $options = self::namespaceSelectorOptions( $params );
863 // Convert $options to HTML
864 $optionsHtml = [];
865 foreach ( $options as $nsId => $nsName ) {
866 $optionsHtml[] = self::element(
867 'option', [
868 'disabled' => in_array( $nsId, $params['disable'] ),
869 'value' => $nsId,
870 'selected' => $nsId === $params['selected'],
871 ], $nsName
875 if ( !array_key_exists( 'id', $selectAttribs ) ) {
876 $selectAttribs['id'] = 'namespace';
879 if ( !array_key_exists( 'name', $selectAttribs ) ) {
880 $selectAttribs['name'] = 'namespace';
883 $ret = '';
884 if ( isset( $params['label'] ) ) {
885 $ret .= self::element(
886 'label', [
887 'for' => isset( $selectAttribs['id'] ) ? $selectAttribs['id'] : null,
888 ], $params['label']
889 ) . '&#160;';
892 // Wrap options in a <select>
893 $ret .= self::openElement( 'select', $selectAttribs )
894 . "\n"
895 . implode( "\n", $optionsHtml )
896 . "\n"
897 . self::closeElement( 'select' );
899 return $ret;
903 * Constructs the opening html-tag with necessary doctypes depending on
904 * global variables.
906 * @param array $attribs Associative array of miscellaneous extra
907 * attributes, passed to Html::element() of html tag.
908 * @return string Raw HTML
910 public static function htmlHeader( array $attribs = [] ) {
911 $ret = '';
913 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
915 $isXHTML = self::isXmlMimeType( $wgMimeType );
917 if ( $isXHTML ) { // XHTML5
918 // XML MIME-typed markup should have an xml header.
919 // However a DOCTYPE is not needed.
920 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
922 // Add the standard xmlns
923 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
925 // And support custom namespaces
926 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
927 $attribs["xmlns:$tag"] = $ns;
929 } else { // HTML5
930 // DOCTYPE
931 $ret .= "<!DOCTYPE html>\n";
934 if ( $wgHtml5Version ) {
935 $attribs['version'] = $wgHtml5Version;
938 $html = self::openElement( 'html', $attribs );
940 if ( $html ) {
941 $html .= "\n";
944 $ret .= $html;
946 return $ret;
950 * Determines if the given MIME type is xml.
952 * @param string $mimetype MIME type
953 * @return bool
955 public static function isXmlMimeType( $mimetype ) {
956 # http://www.whatwg.org/html/infrastructure.html#xml-mime-type
957 # * text/xml
958 # * application/xml
959 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
960 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
964 * Get HTML for an info box with an icon.
966 * @param string $text Wikitext, get this with wfMessage()->plain()
967 * @param string $icon Path to icon file (used as 'src' attribute)
968 * @param string $alt Alternate text for the icon
969 * @param string $class Additional class name to add to the wrapper div
971 * @return string
973 static function infoBox( $text, $icon, $alt, $class = '' ) {
974 $s = self::openElement( 'div', [ 'class' => "mw-infobox $class" ] );
976 $s .= self::openElement( 'div', [ 'class' => 'mw-infobox-left' ] ) .
977 self::element( 'img',
979 'src' => $icon,
980 'alt' => $alt,
983 self::closeElement( 'div' );
985 $s .= self::openElement( 'div', [ 'class' => 'mw-infobox-right' ] ) .
986 $text .
987 self::closeElement( 'div' );
988 $s .= self::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
990 $s .= self::closeElement( 'div' );
992 $s .= self::element( 'div', [ 'style' => 'clear: left;' ], ' ' );
994 return $s;
998 * Generate a srcset attribute value.
1000 * Generates a srcset attribute value from an array mapping pixel densities
1001 * to URLs. A trailing 'x' in pixel density values is optional.
1003 * @note srcset width and height values are not supported.
1005 * @see http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
1007 * @par Example:
1008 * @code
1009 * Html::srcSet( array(
1010 * '1x' => 'standard.jpeg',
1011 * '1.5x' => 'large.jpeg',
1012 * '3x' => 'extra-large.jpeg',
1013 * ) );
1014 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1015 * @endcode
1017 * @param string[] $urls
1018 * @return string
1020 static function srcSet( array $urls ) {
1021 $candidates = [];
1022 foreach ( $urls as $density => $url ) {
1023 // Cast density to float to strip 'x'.
1024 $candidates[] = $url . ' ' . (float)$density . 'x';
1026 return implode( ", ", $candidates );