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