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