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