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