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