Switch some HTMLForms in special pages to OOUI
[lhc/web/wiklou.git] / includes / Html.php
1 <?php
2 /**
3 * Collection of methods to generate HTML content
4 *
5 * Copyright © 2009 Aryeh Gregor
6 * http://www.mediawiki.org/
7 *
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.
12 *
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.
17 *
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
22 *
23 * @file
24 */
25
26 /**
27 * This class is a collection of static functions that serve two purposes:
28 *
29 * 1) Implement any algorithms specified by HTML5, or other HTML
30 * specifications, in a convenient and self-contained way.
31 *
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.
36 *
37 * There are two important configuration options this class uses:
38 *
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.).
43 *
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.
47 *
48 * @since 1.16
49 */
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',
69 );
70
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',
102 );
103
104 /**
105 * Modifies a set of attributes meant for button elements
106 * and apply a set of default attributes when $wgUseMediaWikiUIEverywhere enabled.
107 * @param array $attrs HTML attributes in an associative array
108 * @param string[] $modifiers classes to add to the button
109 * @see https://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
110 * @return array $attrs A modified attribute array
111 */
112 public static function buttonAttributes( array $attrs, array $modifiers = array() ) {
113 global $wgUseMediaWikiUIEverywhere;
114 if ( $wgUseMediaWikiUIEverywhere ) {
115 if ( isset( $attrs['class'] ) ) {
116 if ( is_array( $attrs['class'] ) ) {
117 $attrs['class'][] = 'mw-ui-button';
118 $attrs['class'] = array_merge( $attrs['class'], $modifiers );
119 // ensure compatibility with Xml
120 $attrs['class'] = implode( ' ', $attrs['class'] );
121 } else {
122 $attrs['class'] .= ' mw-ui-button ' . implode( ' ', $modifiers );
123 }
124 } else {
125 // ensure compatibility with Xml
126 $attrs['class'] = 'mw-ui-button ' . implode( ' ', $modifiers );
127 }
128 }
129 return $attrs;
130 }
131
132 /**
133 * Modifies a set of attributes meant for text input elements
134 * and apply a set of default attributes.
135 * Removes size attribute when $wgUseMediaWikiUIEverywhere enabled.
136 * @param array $attrs An attribute array.
137 * @return array $attrs A modified attribute array
138 */
139 public static function getTextInputAttributes( array $attrs ) {
140 global $wgUseMediaWikiUIEverywhere;
141 if ( $wgUseMediaWikiUIEverywhere ) {
142 if ( isset( $attrs['class'] ) ) {
143 if ( is_array( $attrs['class'] ) ) {
144 $attrs['class'][] = 'mw-ui-input';
145 } else {
146 $attrs['class'] .= ' mw-ui-input';
147 }
148 } else {
149 $attrs['class'] = 'mw-ui-input';
150 }
151 }
152 return $attrs;
153 }
154
155 /**
156 * Returns an HTML link element in a string styled as a button
157 * (when $wgUseMediaWikiUIEverywhere is enabled).
158 *
159 * @param string $contents The raw HTML contents of the element: *not*
160 * escaped!
161 * @param array $attrs Associative array of attributes, e.g., array(
162 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
163 * further documentation.
164 * @param string[] $modifiers classes to add to the button
165 * @see http://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
166 * @return string Raw HTML
167 */
168 public static function linkButton( $contents, array $attrs, array $modifiers = array() ) {
169 return self::element( 'a',
170 self::buttonAttributes( $attrs, $modifiers ),
171 $contents
172 );
173 }
174
175 /**
176 * Returns an HTML link element in a string styled as a button
177 * (when $wgUseMediaWikiUIEverywhere is enabled).
178 *
179 * @param string $contents The raw HTML contents of the element: *not*
180 * escaped!
181 * @param array $attrs Associative array of attributes, e.g., array(
182 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
183 * further documentation.
184 * @param string[] $modifiers classes to add to the button
185 * @see http://tools.wmflabs.org/styleguide/desktop/index.html for guidance on available modifiers
186 * @return string Raw HTML
187 */
188 public static function submitButton( $contents, array $attrs, array $modifiers = array() ) {
189 $attrs['type'] = 'submit';
190 $attrs['value'] = $contents;
191 return self::element( 'input', self::buttonAttributes( $attrs, $modifiers ) );
192 }
193
194 /**
195 * Returns an HTML element in a string. The major advantage here over
196 * manually typing out the HTML is that it will escape all attribute
197 * values.
198 *
199 * This is quite similar to Xml::tags(), but it implements some useful
200 * HTML-specific logic. For instance, there is no $allowShortTag
201 * parameter: the closing tag is magically omitted if $element has an empty
202 * content model. If $wgWellFormedXml is false, then a few bytes will be
203 * shaved off the HTML output as well.
204 *
205 * @param string $element The element's name, e.g., 'a'
206 * @param array $attribs Associative array of attributes, e.g., array(
207 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
208 * further documentation.
209 * @param string $contents The raw HTML contents of the element: *not*
210 * escaped!
211 * @return string Raw HTML
212 */
213 public static function rawElement( $element, $attribs = array(), $contents = '' ) {
214 global $wgWellFormedXml;
215 $start = self::openElement( $element, $attribs );
216 if ( in_array( $element, self::$voidElements ) ) {
217 if ( $wgWellFormedXml ) {
218 // Silly XML.
219 return substr( $start, 0, -1 ) . ' />';
220 }
221 return $start;
222 } else {
223 return "$start$contents" . self::closeElement( $element );
224 }
225 }
226
227 /**
228 * Identical to rawElement(), but HTML-escapes $contents (like
229 * Xml::element()).
230 *
231 * @param string $element
232 * @param array $attribs
233 * @param string $contents
234 *
235 * @return string
236 */
237 public static function element( $element, $attribs = array(), $contents = '' ) {
238 return self::rawElement( $element, $attribs, strtr( $contents, array(
239 // There's no point in escaping quotes, >, etc. in the contents of
240 // elements.
241 '&' => '&amp;',
242 '<' => '&lt;'
243 ) ) );
244 }
245
246 /**
247 * Identical to rawElement(), but has no third parameter and omits the end
248 * tag (and the self-closing '/' in XML mode for empty elements).
249 *
250 * @param string $element
251 * @param array $attribs
252 *
253 * @return string
254 */
255 public static function openElement( $element, $attribs = array() ) {
256 $attribs = (array)$attribs;
257 // This is not required in HTML5, but let's do it anyway, for
258 // consistency and better compression.
259 $element = strtolower( $element );
260
261 // Remove invalid input types
262 if ( $element == 'input' ) {
263 $validTypes = array(
264 'hidden',
265 'text',
266 'password',
267 'checkbox',
268 'radio',
269 'file',
270 'submit',
271 'image',
272 'reset',
273 'button',
274
275 // HTML input types
276 'datetime',
277 'datetime-local',
278 'date',
279 'month',
280 'time',
281 'week',
282 'number',
283 'range',
284 'email',
285 'url',
286 'search',
287 'tel',
288 'color',
289 );
290 if ( isset( $attribs['type'] ) && !in_array( $attribs['type'], $validTypes ) ) {
291 unset( $attribs['type'] );
292 }
293 }
294
295 // According to standard the default type for <button> elements is "submit".
296 // Depending on compatibility mode IE might use "button", instead.
297 // We enforce the standard "submit".
298 if ( $element == 'button' && !isset( $attribs['type'] ) ) {
299 $attribs['type'] = 'submit';
300 }
301
302 return "<$element" . self::expandAttributes(
303 self::dropDefaults( $element, $attribs ) ) . '>';
304 }
305
306 /**
307 * Returns "</$element>"
308 *
309 * @since 1.17
310 * @param string $element Name of the element, e.g., 'a'
311 * @return string A closing tag
312 */
313 public static function closeElement( $element ) {
314 $element = strtolower( $element );
315
316 return "</$element>";
317 }
318
319 /**
320 * Given an element name and an associative array of element attributes,
321 * return an array that is functionally identical to the input array, but
322 * possibly smaller. In particular, attributes might be stripped if they
323 * are given their default values.
324 *
325 * This method is not guaranteed to remove all redundant attributes, only
326 * some common ones and some others selected arbitrarily at random. It
327 * only guarantees that the output array should be functionally identical
328 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
329 *
330 * @param string $element Name of the element, e.g., 'a'
331 * @param array $attribs Associative array of attributes, e.g., array(
332 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
333 * further documentation.
334 * @return array An array of attributes functionally identical to $attribs
335 */
336 private static function dropDefaults( $element, array $attribs ) {
337 // Whenever altering this array, please provide a covering test case
338 // in HtmlTest::provideElementsWithAttributesHavingDefaultValues
339 static $attribDefaults = array(
340 'area' => array( 'shape' => 'rect' ),
341 'button' => array(
342 'formaction' => 'GET',
343 'formenctype' => 'application/x-www-form-urlencoded',
344 ),
345 'canvas' => array(
346 'height' => '150',
347 'width' => '300',
348 ),
349 'command' => array( 'type' => 'command' ),
350 'form' => array(
351 'action' => 'GET',
352 'autocomplete' => 'on',
353 'enctype' => 'application/x-www-form-urlencoded',
354 ),
355 'input' => array(
356 'formaction' => 'GET',
357 'type' => 'text',
358 ),
359 'keygen' => array( 'keytype' => 'rsa' ),
360 'link' => array( 'media' => 'all' ),
361 'menu' => array( 'type' => 'list' ),
362 // Note: the use of text/javascript here instead of other JavaScript
363 // MIME types follows the HTML5 spec.
364 'script' => array( 'type' => 'text/javascript' ),
365 'style' => array(
366 'media' => 'all',
367 'type' => 'text/css',
368 ),
369 'textarea' => array( 'wrap' => 'soft' ),
370 );
371
372 $element = strtolower( $element );
373
374 foreach ( $attribs as $attrib => $value ) {
375 $lcattrib = strtolower( $attrib );
376 if ( is_array( $value ) ) {
377 $value = implode( ' ', $value );
378 } else {
379 $value = strval( $value );
380 }
381
382 // Simple checks using $attribDefaults
383 if ( isset( $attribDefaults[$element][$lcattrib] )
384 && $attribDefaults[$element][$lcattrib] == $value
385 ) {
386 unset( $attribs[$attrib] );
387 }
388
389 if ( $lcattrib == 'class' && $value == '' ) {
390 unset( $attribs[$attrib] );
391 }
392 }
393
394 // More subtle checks
395 if ( $element === 'link'
396 && isset( $attribs['type'] ) && strval( $attribs['type'] ) == 'text/css'
397 ) {
398 unset( $attribs['type'] );
399 }
400 if ( $element === 'input' ) {
401 $type = isset( $attribs['type'] ) ? $attribs['type'] : null;
402 $value = isset( $attribs['value'] ) ? $attribs['value'] : null;
403 if ( $type === 'checkbox' || $type === 'radio' ) {
404 // The default value for checkboxes and radio buttons is 'on'
405 // not ''. By stripping value="" we break radio boxes that
406 // actually wants empty values.
407 if ( $value === 'on' ) {
408 unset( $attribs['value'] );
409 }
410 } elseif ( $type === 'submit' ) {
411 // The default value for submit appears to be "Submit" but
412 // let's not bother stripping out localized text that matches
413 // that.
414 } else {
415 // The default value for nearly every other field type is ''
416 // The 'range' and 'color' types use different defaults but
417 // stripping a value="" does not hurt them.
418 if ( $value === '' ) {
419 unset( $attribs['value'] );
420 }
421 }
422 }
423 if ( $element === 'select' && isset( $attribs['size'] ) ) {
424 if ( in_array( 'multiple', $attribs )
425 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
426 ) {
427 // A multi-select
428 if ( strval( $attribs['size'] ) == '4' ) {
429 unset( $attribs['size'] );
430 }
431 } else {
432 // Single select
433 if ( strval( $attribs['size'] ) == '1' ) {
434 unset( $attribs['size'] );
435 }
436 }
437 }
438
439 return $attribs;
440 }
441
442 /**
443 * Given an associative array of element attributes, generate a string
444 * to stick after the element name in HTML output. Like array( 'href' =>
445 * 'http://www.mediawiki.org/' ) becomes something like
446 * ' href="http://www.mediawiki.org"'. Again, this is like
447 * Xml::expandAttributes(), but it implements some HTML-specific logic.
448 * For instance, it will omit quotation marks if $wgWellFormedXml is false,
449 * and will treat boolean attributes specially.
450 *
451 * Attributes that can contain space-separated lists ('class', 'accesskey' and 'rel') array
452 * values are allowed as well, which will automagically be normalized
453 * and converted to a space-separated string. In addition to a numerical
454 * array, the attribute value may also be an associative array. See the
455 * example below for how that works.
456 *
457 * @par Numerical array
458 * @code
459 * Html::element( 'em', array(
460 * 'class' => array( 'foo', 'bar' )
461 * ) );
462 * // gives '<em class="foo bar"></em>'
463 * @endcode
464 *
465 * @par Associative array
466 * @code
467 * Html::element( 'em', array(
468 * 'class' => array( 'foo', 'bar', 'foo' => false, 'quux' => true )
469 * ) );
470 * // gives '<em class="bar quux"></em>'
471 * @endcode
472 *
473 * @param array $attribs Associative array of attributes, e.g., array(
474 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
475 * A value of false means to omit the attribute. For boolean attributes,
476 * you can omit the key, e.g., array( 'checked' ) instead of
477 * array( 'checked' => 'checked' ) or such.
478 *
479 * @throws MWException If an attribute that doesn't allow lists is set to an array
480 * @return string HTML fragment that goes between element name and '>'
481 * (starting with a space if at least one attribute is output)
482 */
483 public static function expandAttributes( array $attribs ) {
484 global $wgWellFormedXml;
485
486 $ret = '';
487 foreach ( $attribs as $key => $value ) {
488 // Support intuitive array( 'checked' => true/false ) form
489 if ( $value === false || is_null( $value ) ) {
490 continue;
491 }
492
493 // For boolean attributes, support array( 'foo' ) instead of
494 // requiring array( 'foo' => 'meaningless' ).
495 if ( is_int( $key ) && in_array( strtolower( $value ), self::$boolAttribs ) ) {
496 $key = $value;
497 }
498
499 // Not technically required in HTML5 but we'd like consistency
500 // and better compression anyway.
501 $key = strtolower( $key );
502
503 // Bug 23769: Blacklist all form validation attributes for now. Current
504 // (June 2010) WebKit has no UI, so the form just refuses to submit
505 // without telling the user why, which is much worse than failing
506 // server-side validation. Opera is the only other implementation at
507 // this time, and has ugly UI, so just kill the feature entirely until
508 // we have at least one good implementation.
509
510 // As the default value of "1" for "step" rejects decimal
511 // numbers to be entered in 'type="number"' fields, allow
512 // the special case 'step="any"'.
513
514 if ( in_array( $key, array( 'max', 'min', 'pattern', 'required' ) )
515 || $key === 'step' && $value !== 'any' ) {
516 continue;
517 }
518
519 // http://www.w3.org/TR/html401/index/attributes.html ("space-separated")
520 // http://www.w3.org/TR/html5/index.html#attributes-1 ("space-separated")
521 $spaceSeparatedListAttributes = array(
522 'class', // html4, html5
523 'accesskey', // as of html5, multiple space-separated values allowed
524 // html4-spec doesn't document rel= as space-separated
525 // but has been used like that and is now documented as such
526 // in the html5-spec.
527 'rel',
528 );
529
530 // Specific features for attributes that allow a list of space-separated values
531 if ( in_array( $key, $spaceSeparatedListAttributes ) ) {
532 // Apply some normalization and remove duplicates
533
534 // Convert into correct array. Array can contain space-separated
535 // values. Implode/explode to get those into the main array as well.
536 if ( is_array( $value ) ) {
537 // If input wasn't an array, we can skip this step
538 $newValue = array();
539 foreach ( $value as $k => $v ) {
540 if ( is_string( $v ) ) {
541 // String values should be normal `array( 'foo' )`
542 // Just append them
543 if ( !isset( $value[$v] ) ) {
544 // As a special case don't set 'foo' if a
545 // separate 'foo' => true/false exists in the array
546 // keys should be authoritative
547 $newValue[] = $v;
548 }
549 } elseif ( $v ) {
550 // If the value is truthy but not a string this is likely
551 // an array( 'foo' => true ), falsy values don't add strings
552 $newValue[] = $k;
553 }
554 }
555 $value = implode( ' ', $newValue );
556 }
557 $value = explode( ' ', $value );
558
559 // Normalize spacing by fixing up cases where people used
560 // more than 1 space and/or a trailing/leading space
561 $value = array_diff( $value, array( '', ' ' ) );
562
563 // Remove duplicates and create the string
564 $value = implode( ' ', array_unique( $value ) );
565 } elseif ( is_array( $value ) ) {
566 throw new MWException( "HTML attribute $key can not contain a list of values" );
567 }
568
569 // See the "Attributes" section in the HTML syntax part of HTML5,
570 // 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
571 // marks omitted, but not all. (Although a literal " is not
572 // permitted, we don't check for that, since it will be escaped
573 // anyway.)
574
575 // See also research done on further characters that need to be
576 // escaped: http://code.google.com/p/html5lib/issues/detail?id=93
577 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
578 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
579 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
580 if ( $wgWellFormedXml || $value === '' || preg_match( "![$badChars]!u", $value ) ) {
581 $quote = '"';
582 } else {
583 $quote = '';
584 }
585
586 if ( in_array( $key, self::$boolAttribs ) ) {
587 // In HTML5, we can leave the value empty. If we don't need
588 // well-formed XML, we can omit the = entirely.
589 if ( !$wgWellFormedXml ) {
590 $ret .= " $key";
591 } else {
592 $ret .= " $key=\"\"";
593 }
594 } else {
595 // Apparently we need to entity-encode \n, \r, \t, although the
596 // spec doesn't mention that. Since we're doing strtr() anyway,
597 // we may as well not call htmlspecialchars().
598 // @todo FIXME: Verify that we actually need to
599 // escape \n\r\t here, and explain why, exactly.
600 #
601 // We could call Sanitizer::encodeAttribute() for this, but we
602 // don't because we're stubborn and like our marginal savings on
603 // byte size from not having to encode unnecessary quotes.
604 // The only difference between this transform and the one by
605 // Sanitizer::encodeAttribute() is '<' is only encoded here if
606 // $wgWellFormedXml is set, and ' is not encoded.
607 $map = array(
608 '&' => '&amp;',
609 '"' => '&quot;',
610 '>' => '&gt;',
611 "\n" => '&#10;',
612 "\r" => '&#13;',
613 "\t" => '&#9;'
614 );
615 if ( $wgWellFormedXml ) {
616 // This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
617 // But reportedly it breaks some XML tools?
618 // @todo FIXME: Is this really true?
619 $map['<'] = '&lt;';
620 }
621 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
622 }
623 }
624 return $ret;
625 }
626
627 /**
628 * Output a "<script>" tag with the given contents.
629 *
630 * @todo do some useful escaping as well, like if $contents contains
631 * literal "</script>" or (for XML) literal "]]>".
632 *
633 * @param string $contents JavaScript
634 * @return string Raw HTML
635 */
636 public static function inlineScript( $contents ) {
637 global $wgWellFormedXml;
638
639 $attrs = array();
640
641 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
642 $contents = "/*<![CDATA[*/$contents/*]]>*/";
643 }
644
645 return self::rawElement( 'script', $attrs, $contents );
646 }
647
648 /**
649 * Output a "<script>" tag linking to the given URL, e.g.,
650 * "<script src=foo.js></script>".
651 *
652 * @param string $url
653 * @return string Raw HTML
654 */
655 public static function linkedScript( $url ) {
656 $attrs = array( 'src' => $url );
657
658 return self::element( 'script', $attrs );
659 }
660
661 /**
662 * Output a "<style>" tag with the given contents for the given media type
663 * (if any). TODO: do some useful escaping as well, like if $contents
664 * contains literal "</style>" (admittedly unlikely).
665 *
666 * @param string $contents CSS
667 * @param string $media A media type string, like 'screen'
668 * @return string Raw HTML
669 */
670 public static function inlineStyle( $contents, $media = 'all' ) {
671 global $wgWellFormedXml;
672
673 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
674 $contents = "/*<![CDATA[*/$contents/*]]>*/";
675 }
676
677 return self::rawElement( 'style', array(
678 'type' => 'text/css',
679 'media' => $media,
680 ), $contents );
681 }
682
683 /**
684 * Output a "<link rel=stylesheet>" linking to the given URL for the given
685 * media type (if any).
686 *
687 * @param string $url
688 * @param string $media A media type string, like 'screen'
689 * @return string Raw HTML
690 */
691 public static function linkedStyle( $url, $media = 'all' ) {
692 return self::element( 'link', array(
693 'rel' => 'stylesheet',
694 'href' => $url,
695 'type' => 'text/css',
696 'media' => $media,
697 ) );
698 }
699
700 /**
701 * Convenience function to produce an "<input>" element. This supports the
702 * new HTML5 input types and attributes.
703 *
704 * @param string $name Name attribute
705 * @param string $value Value attribute
706 * @param string $type Type attribute
707 * @param array $attribs Associative array of miscellaneous extra
708 * attributes, passed to Html::element()
709 * @return string Raw HTML
710 */
711 public static function input( $name, $value = '', $type = 'text', array $attribs = array() ) {
712 $attribs['type'] = $type;
713 $attribs['value'] = $value;
714 $attribs['name'] = $name;
715 if ( in_array( $type, array( 'text', 'search', 'email', 'password', 'number' ) ) ) {
716 $attribs = self::getTextInputAttributes( $attribs );
717 }
718 if ( in_array( $type, array( 'button', 'reset', 'submit' ) ) ) {
719 $attribs = self::buttonAttributes( $attribs );
720 }
721 return self::element( 'input', $attribs );
722 }
723
724 /**
725 * Convenience function to produce a checkbox (input element with type=checkbox)
726 *
727 * @param string $name Name attribute
728 * @param bool $checked Whether the checkbox is checked or not
729 * @param array $attribs Array of additional attributes
730 * @return string Raw HTML
731 */
732 public static function check( $name, $checked = false, array $attribs = array() ) {
733 if ( isset( $attribs['value'] ) ) {
734 $value = $attribs['value'];
735 unset( $attribs['value'] );
736 } else {
737 $value = 1;
738 }
739
740 if ( $checked ) {
741 $attribs[] = 'checked';
742 }
743
744 return self::input( $name, $value, 'checkbox', $attribs );
745 }
746
747 /**
748 * Convenience function to produce a checkbox (input element with type=checkbox)
749 *
750 * @param string $name Name attribute
751 * @param bool $checked Whether the checkbox is checked or not
752 * @param array $attribs Array of additional attributes
753 * @return string Raw HTML
754 */
755 public static function radio( $name, $checked = false, array $attribs = array() ) {
756 if ( isset( $attribs['value'] ) ) {
757 $value = $attribs['value'];
758 unset( $attribs['value'] );
759 } else {
760 $value = 1;
761 }
762
763 if ( $checked ) {
764 $attribs[] = 'checked';
765 }
766
767 return self::input( $name, $value, 'radio', $attribs );
768 }
769
770 /**
771 * Convenience function for generating a label for inputs.
772 *
773 * @param string $label Contents of the label
774 * @param string $id ID of the element being labeled
775 * @param array $attribs Additional attributes
776 * @return string Raw HTML
777 */
778 public static function label( $label, $id, array $attribs = array() ) {
779 $attribs += array(
780 'for' => $id
781 );
782 return self::element( 'label', $attribs, $label );
783 }
784
785 /**
786 * Convenience function to produce an input element with type=hidden
787 *
788 * @param string $name Name attribute
789 * @param string $value Value attribute
790 * @param array $attribs Associative array of miscellaneous extra
791 * attributes, passed to Html::element()
792 * @return string Raw HTML
793 */
794 public static function hidden( $name, $value, array $attribs = array() ) {
795 return self::input( $name, $value, 'hidden', $attribs );
796 }
797
798 /**
799 * Convenience function to produce a <textarea> element.
800 *
801 * This supports leaving out the cols= and rows= which Xml requires and are
802 * required by HTML4/XHTML but not required by HTML5.
803 *
804 * @param string $name Name attribute
805 * @param string $value Value attribute
806 * @param array $attribs Associative array of miscellaneous extra
807 * attributes, passed to Html::element()
808 * @return string Raw HTML
809 */
810 public static function textarea( $name, $value = '', array $attribs = array() ) {
811 $attribs['name'] = $name;
812
813 if ( substr( $value, 0, 1 ) == "\n" ) {
814 // Workaround for bug 12130: browsers eat the initial newline
815 // assuming that it's just for show, but they do keep the later
816 // newlines, which we may want to preserve during editing.
817 // Prepending a single newline
818 $spacedValue = "\n" . $value;
819 } else {
820 $spacedValue = $value;
821 }
822 return self::element( 'textarea', self::getTextInputAttributes( $attribs ), $spacedValue );
823 }
824
825 /**
826 * Build a drop-down box for selecting a namespace
827 *
828 * @param array $params Params to set.
829 * - selected: [optional] Id of namespace which should be pre-selected
830 * - all: [optional] Value of item for "all namespaces". If null or unset,
831 * no "<option>" is generated to select all namespaces.
832 * - label: text for label to add before the field.
833 * - exclude: [optional] Array of namespace ids to exclude.
834 * - disable: [optional] Array of namespace ids for which the option should
835 * be disabled in the selector.
836 * @param array $selectAttribs HTML attributes for the generated select element.
837 * - id: [optional], default: 'namespace'.
838 * - name: [optional], default: 'namespace'.
839 * @return string HTML code to select a namespace.
840 */
841 public static function namespaceSelector( array $params = array(),
842 array $selectAttribs = array()
843 ) {
844 global $wgContLang;
845
846 ksort( $selectAttribs );
847
848 // Is a namespace selected?
849 if ( isset( $params['selected'] ) ) {
850 // If string only contains digits, convert to clean int. Selected could also
851 // be "all" or "" etc. which needs to be left untouched.
852 // PHP is_numeric() has issues with large strings, PHP ctype_digit has other issues
853 // and returns false for already clean ints. Use regex instead..
854 if ( preg_match( '/^\d+$/', $params['selected'] ) ) {
855 $params['selected'] = intval( $params['selected'] );
856 }
857 // else: leaves it untouched for later processing
858 } else {
859 $params['selected'] = '';
860 }
861
862 if ( !isset( $params['exclude'] ) || !is_array( $params['exclude'] ) ) {
863 $params['exclude'] = array();
864 }
865 if ( !isset( $params['disable'] ) || !is_array( $params['disable'] ) ) {
866 $params['disable'] = array();
867 }
868
869 // Associative array between option-values and option-labels
870 $options = array();
871
872 if ( isset( $params['all'] ) ) {
873 // add an option that would let the user select all namespaces.
874 // Value is provided by user, the name shown is localized for the user.
875 $options[$params['all']] = wfMessage( 'namespacesall' )->text();
876 }
877 // Add all namespaces as options (in the content language)
878 $options += $wgContLang->getFormattedNamespaces();
879
880 // Convert $options to HTML and filter out namespaces below 0
881 $optionsHtml = array();
882 foreach ( $options as $nsId => $nsName ) {
883 if ( $nsId < NS_MAIN || in_array( $nsId, $params['exclude'] ) ) {
884 continue;
885 }
886 if ( $nsId === NS_MAIN ) {
887 // For other namespaces use the namespace prefix as label, but for
888 // main we don't use "" but the user message describing it (e.g. "(Main)" or "(Article)")
889 $nsName = wfMessage( 'blanknamespace' )->text();
890 } elseif ( is_int( $nsId ) ) {
891 $nsName = $wgContLang->convertNamespace( $nsId );
892 }
893 $optionsHtml[] = self::element(
894 'option', array(
895 'disabled' => in_array( $nsId, $params['disable'] ),
896 'value' => $nsId,
897 'selected' => $nsId === $params['selected'],
898 ), $nsName
899 );
900 }
901
902 if ( !array_key_exists( 'id', $selectAttribs ) ) {
903 $selectAttribs['id'] = 'namespace';
904 }
905
906 if ( !array_key_exists( 'name', $selectAttribs ) ) {
907 $selectAttribs['name'] = 'namespace';
908 }
909
910 $ret = '';
911 if ( isset( $params['label'] ) ) {
912 $ret .= self::element(
913 'label', array(
914 'for' => isset( $selectAttribs['id'] ) ? $selectAttribs['id'] : null,
915 ), $params['label']
916 ) . '&#160;';
917 }
918
919 // Wrap options in a <select>
920 $ret .= self::openElement( 'select', $selectAttribs )
921 . "\n"
922 . implode( "\n", $optionsHtml )
923 . "\n"
924 . self::closeElement( 'select' );
925
926 return $ret;
927 }
928
929 /**
930 * Constructs the opening html-tag with necessary doctypes depending on
931 * global variables.
932 *
933 * @param array $attribs Associative array of miscellaneous extra
934 * attributes, passed to Html::element() of html tag.
935 * @return string Raw HTML
936 */
937 public static function htmlHeader( array $attribs = array() ) {
938 $ret = '';
939
940 global $wgHtml5Version, $wgMimeType, $wgXhtmlNamespaces;
941
942 $isXHTML = self::isXmlMimeType( $wgMimeType );
943
944 if ( $isXHTML ) { // XHTML5
945 // XML MIME-typed markup should have an xml header.
946 // However a DOCTYPE is not needed.
947 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
948
949 // Add the standard xmlns
950 $attribs['xmlns'] = 'http://www.w3.org/1999/xhtml';
951
952 // And support custom namespaces
953 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
954 $attribs["xmlns:$tag"] = $ns;
955 }
956 } else { // HTML5
957 // DOCTYPE
958 $ret .= "<!DOCTYPE html>\n";
959 }
960
961 if ( $wgHtml5Version ) {
962 $attribs['version'] = $wgHtml5Version;
963 }
964
965 $html = self::openElement( 'html', $attribs );
966
967 if ( $html ) {
968 $html .= "\n";
969 }
970
971 $ret .= $html;
972
973 return $ret;
974 }
975
976 /**
977 * Determines if the given MIME type is xml.
978 *
979 * @param string $mimetype MIME type
980 * @return bool
981 */
982 public static function isXmlMimeType( $mimetype ) {
983 # http://www.whatwg.org/html/infrastructure.html#xml-mime-type
984 # * text/xml
985 # * application/xml
986 # * Any MIME type with a subtype ending in +xml (this implicitly includes application/xhtml+xml)
987 return (bool)preg_match( '!^(text|application)/xml$|^.+/.+\+xml$!', $mimetype );
988 }
989
990 /**
991 * Get HTML for an info box with an icon.
992 *
993 * @param string $text Wikitext, get this with wfMessage()->plain()
994 * @param string $icon Path to icon file (used as 'src' attribute)
995 * @param string $alt Alternate text for the icon
996 * @param string $class Additional class name to add to the wrapper div
997 *
998 * @return string
999 */
1000 static function infoBox( $text, $icon, $alt, $class = '' ) {
1001 $s = self::openElement( 'div', array( 'class' => "mw-infobox $class" ) );
1002
1003 $s .= self::openElement( 'div', array( 'class' => 'mw-infobox-left' ) ) .
1004 self::element( 'img',
1005 array(
1006 'src' => $icon,
1007 'alt' => $alt,
1008 )
1009 ) .
1010 self::closeElement( 'div' );
1011
1012 $s .= self::openElement( 'div', array( 'class' => 'mw-infobox-right' ) ) .
1013 $text .
1014 self::closeElement( 'div' );
1015 $s .= self::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
1016
1017 $s .= self::closeElement( 'div' );
1018
1019 $s .= self::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
1020
1021 return $s;
1022 }
1023
1024 /**
1025 * Generate a srcset attribute value.
1026 *
1027 * Generates a srcset attribute value from an array mapping pixel densities
1028 * to URLs. A trailing 'x' in pixel density values is optional.
1029 *
1030 * @note srcset width and height values are not supported.
1031 *
1032 * @see http://www.whatwg.org/html/embedded-content-1.html#attr-img-srcset
1033 *
1034 * @par Example:
1035 * @code
1036 * Html::srcSet( array(
1037 * '1x' => 'standard.jpeg',
1038 * '1.5x' => 'large.jpeg',
1039 * '3x' => 'extra-large.jpeg',
1040 * ) );
1041 * // gives 'standard.jpeg 1x, large.jpeg 1.5x, extra-large.jpeg 2x'
1042 * @endcode
1043 *
1044 * @param string[] $urls
1045 * @return string
1046 */
1047 static function srcSet( array $urls ) {
1048 $candidates = array();
1049 foreach ( $urls as $density => $url ) {
1050 // Cast density to float to strip 'x'.
1051 $candidates[] = $url . ' ' . (float)$density . 'x';
1052 }
1053 return implode( ", ", $candidates );
1054 }
1055 }