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