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