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