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