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