bf72dffae04e622c0d78f6ffebd46eedd09c9d3c
[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 9.1.2 as of 2009-08-10
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 );
68
69 # Boolean attributes, which may have the value omitted entirely. Manually
70 # collected from the HTML5 spec as of 2010-06-07.
71 private static $boolAttribs = array(
72 'async',
73 'autofocus',
74 'autoplay',
75 'checked',
76 'controls',
77 'defer',
78 'disabled',
79 'formnovalidate',
80 'hidden',
81 'ismap',
82 'itemscope',
83 'loop',
84 'multiple',
85 'novalidate',
86 'open',
87 'pubdate',
88 'readonly',
89 'required',
90 'reversed',
91 'scoped',
92 'seamless',
93 'selected',
94 );
95
96 /**
97 * Returns an HTML element in a string. The major advantage here over
98 * manually typing out the HTML is that it will escape all attribute
99 * values. If you're hardcoding all the attributes, or there are none, you
100 * should probably type out the string yourself.
101 *
102 * This is quite similar to Xml::tags(), but it implements some useful
103 * HTML-specific logic. For instance, there is no $allowShortTag
104 * parameter: the closing tag is magically omitted if $element has an empty
105 * content model. If $wgWellFormedXml is false, then a few bytes will be
106 * shaved off the HTML output as well. In the future, other HTML-specific
107 * features might be added, like allowing arrays for the values of
108 * attributes like class= and media=.
109 *
110 * @param $element string The element's name, e.g., 'a'
111 * @param $attribs array Associative array of attributes, e.g., array(
112 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
113 * further documentation.
114 * @param $contents string The raw HTML contents of the element: *not*
115 * escaped!
116 * @return string Raw HTML
117 */
118 public static function rawElement( $element, $attribs = array(), $contents = '' ) {
119 global $wgWellFormedXml;
120 $start = self::openElement( $element, $attribs );
121 if ( in_array( $element, self::$voidElements ) ) {
122 if ( $wgWellFormedXml ) {
123 # Silly XML.
124 return substr( $start, 0, -1 ) . ' />';
125 }
126 return $start;
127 } else {
128 return "$start$contents" . self::closeElement( $element );
129 }
130 }
131
132 /**
133 * Identical to rawElement(), but HTML-escapes $contents (like
134 * Xml::element()).
135 *
136 * @param $element string
137 * @param $attribs array
138 * @param $contents string
139 *
140 * @return string
141 */
142 public static function element( $element, $attribs = array(), $contents = '' ) {
143 return self::rawElement( $element, $attribs, strtr( $contents, array(
144 # There's no point in escaping quotes, >, etc. in the contents of
145 # elements.
146 '&' => '&amp;',
147 '<' => '&lt;'
148 ) ) );
149 }
150
151 /**
152 * Identical to rawElement(), but has no third parameter and omits the end
153 * tag (and the self-closing '/' in XML mode for empty elements).
154 *
155 * @param $element string
156 * @param $attribs array
157 *
158 * @return string
159 */
160 public static function openElement( $element, $attribs = array() ) {
161 global $wgHtml5, $wgWellFormedXml;
162 $attribs = (array)$attribs;
163 # This is not required in HTML5, but let's do it anyway, for
164 # consistency and better compression.
165 $element = strtolower( $element );
166
167 # In text/html, initial <html> and <head> tags can be omitted under
168 # pretty much any sane circumstances, if they have no attributes. See:
169 # <http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags>
170 if ( !$wgWellFormedXml && !$attribs
171 && in_array( $element, array( 'html', 'head' ) ) ) {
172 return '';
173 }
174
175 # Remove HTML5-only attributes if we aren't doing HTML5, and disable
176 # form validation regardless (see bug 23769 and the more detailed
177 # comment in expandAttributes())
178 if ( $element == 'input' ) {
179 # Whitelist of types that don't cause validation. All except
180 # 'search' are valid in XHTML1.
181 $validTypes = array(
182 'hidden',
183 'text',
184 'password',
185 'checkbox',
186 'radio',
187 'file',
188 'submit',
189 'image',
190 'reset',
191 'button',
192 'search',
193 );
194
195 if ( isset( $attribs['type'] )
196 && !in_array( $attribs['type'], $validTypes ) ) {
197 unset( $attribs['type'] );
198 }
199
200 if ( isset( $attribs['type'] ) && $attribs['type'] == 'search'
201 && !$wgHtml5 ) {
202 unset( $attribs['type'] );
203 }
204 }
205
206 if ( !$wgHtml5 && $element == 'textarea' && isset( $attribs['maxlength'] ) ) {
207 unset( $attribs['maxlength'] );
208 }
209
210 return "<$element" . self::expandAttributes(
211 self::dropDefaults( $element, $attribs ) ) . '>';
212 }
213
214 /**
215 * Returns "</$element>", except if $wgWellFormedXml is off, in which case
216 * it returns the empty string when that's guaranteed to be safe.
217 *
218 * @since 1.17
219 * @param $element string Name of the element, e.g., 'a'
220 * @return string A closing tag, if required
221 */
222 public static function closeElement( $element ) {
223 global $wgWellFormedXml;
224
225 $element = strtolower( $element );
226
227 # Reference:
228 # http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags
229 if ( !$wgWellFormedXml && in_array( $element, array(
230 'html',
231 'head',
232 'body',
233 'li',
234 'dt',
235 'dd',
236 'tr',
237 'td',
238 'th',
239 ) ) ) {
240 return '';
241 }
242 return "</$element>";
243 }
244
245 /**
246 * Given an element name and an associative array of element attributes,
247 * return an array that is functionally identical to the input array, but
248 * possibly smaller. In particular, attributes might be stripped if they
249 * are given their default values.
250 *
251 * This method is not guaranteed to remove all redundant attributes, only
252 * some common ones and some others selected arbitrarily at random. It
253 * only guarantees that the output array should be functionally identical
254 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
255 *
256 * @param $element string Name of the element, e.g., 'a'
257 * @param $attribs array Associative array of attributes, e.g., array(
258 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
259 * further documentation.
260 * @return array An array of attributes functionally identical to $attribs
261 */
262 private static function dropDefaults( $element, $attribs ) {
263 # Don't bother doing anything if we aren't outputting HTML5; it's too
264 # much of a pain to maintain two sets of defaults.
265 global $wgHtml5;
266 if ( !$wgHtml5 ) {
267 return $attribs;
268 }
269
270 static $attribDefaults = array(
271 'area' => array( 'shape' => 'rect' ),
272 'button' => array(
273 'formaction' => 'GET',
274 'formenctype' => 'application/x-www-form-urlencoded',
275 'type' => 'submit',
276 ),
277 'canvas' => array(
278 'height' => '150',
279 'width' => '300',
280 ),
281 'command' => array( 'type' => 'command' ),
282 'form' => array(
283 'action' => 'GET',
284 'autocomplete' => 'on',
285 'enctype' => 'application/x-www-form-urlencoded',
286 ),
287 'input' => array(
288 'formaction' => 'GET',
289 'type' => 'text',
290 'value' => '',
291 ),
292 'keygen' => array( 'keytype' => 'rsa' ),
293 'link' => array( 'media' => 'all' ),
294 'menu' => array( 'type' => 'list' ),
295 # Note: the use of text/javascript here instead of other JavaScript
296 # MIME types follows the HTML5 spec.
297 'script' => array( 'type' => 'text/javascript' ),
298 'style' => array(
299 'media' => 'all',
300 'type' => 'text/css',
301 ),
302 'textarea' => array( 'wrap' => 'soft' ),
303 );
304
305 $element = strtolower( $element );
306
307 foreach ( $attribs as $attrib => $value ) {
308 $lcattrib = strtolower( $attrib );
309 $value = strval( $value );
310
311 # Simple checks using $attribDefaults
312 if ( isset( $attribDefaults[$element][$lcattrib] ) &&
313 $attribDefaults[$element][$lcattrib] == $value ) {
314 unset( $attribs[$attrib] );
315 }
316
317 if ( $lcattrib == 'class' && $value == '' ) {
318 unset( $attribs[$attrib] );
319 }
320 }
321
322 # More subtle checks
323 if ( $element === 'link' && isset( $attribs['type'] )
324 && strval( $attribs['type'] ) == 'text/css' ) {
325 unset( $attribs['type'] );
326 }
327 if ( $element === 'select' && isset( $attribs['size'] ) ) {
328 if ( in_array( 'multiple', $attribs )
329 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
330 ) {
331 # A multi-select
332 if ( strval( $attribs['size'] ) == '4' ) {
333 unset( $attribs['size'] );
334 }
335 } else {
336 # Single select
337 if ( strval( $attribs['size'] ) == '1' ) {
338 unset( $attribs['size'] );
339 }
340 }
341 }
342
343 return $attribs;
344 }
345
346 /**
347 * Given an associative array of element attributes, generate a string
348 * to stick after the element name in HTML output. Like array( 'href' =>
349 * 'http://www.mediawiki.org/' ) becomes something like
350 * ' href="http://www.mediawiki.org"'. Again, this is like
351 * Xml::expandAttributes(), but it implements some HTML-specific logic.
352 * For instance, it will omit quotation marks if $wgWellFormedXml is false,
353 * and will treat boolean attributes specially.
354 *
355 * @param $attribs array Associative array of attributes, e.g., array(
356 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
357 * A value of false means to omit the attribute. For boolean attributes,
358 * you can omit the key, e.g., array( 'checked' ) instead of
359 * array( 'checked' => 'checked' ) or such.
360 * @return string HTML fragment that goes between element name and '>'
361 * (starting with a space if at least one attribute is output)
362 */
363 public static function expandAttributes( $attribs ) {
364 global $wgHtml5, $wgWellFormedXml;
365
366 $ret = '';
367 $attribs = (array)$attribs;
368 foreach ( $attribs as $key => $value ) {
369 if ( $value === false || is_null( $value ) ) {
370 continue;
371 }
372
373 # For boolean attributes, support array( 'foo' ) instead of
374 # requiring array( 'foo' => 'meaningless' ).
375 if ( is_int( $key )
376 && in_array( strtolower( $value ), self::$boolAttribs ) ) {
377 $key = $value;
378 }
379
380 # Not technically required in HTML5, but required in XHTML 1.0,
381 # and we'd like consistency and better compression anyway.
382 $key = strtolower( $key );
383
384 # Bug 23769: Blacklist all form validation attributes for now. Current
385 # (June 2010) WebKit has no UI, so the form just refuses to submit
386 # without telling the user why, which is much worse than failing
387 # server-side validation. Opera is the only other implementation at
388 # this time, and has ugly UI, so just kill the feature entirely until
389 # we have at least one good implementation.
390 if ( in_array( $key, array( 'max', 'min', 'pattern', 'required', 'step' ) ) ) {
391 continue;
392 }
393
394 # Here we're blacklisting some HTML5-only attributes...
395 if ( !$wgHtml5 && in_array( $key, array(
396 'autocomplete',
397 'autofocus',
398 'max',
399 'min',
400 'multiple',
401 'pattern',
402 'placeholder',
403 'required',
404 'step',
405 'spellcheck',
406 ) ) ) {
407 continue;
408 }
409
410 # See the "Attributes" section in the HTML syntax part of HTML5,
411 # 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
412 # marks omitted, but not all. (Although a literal " is not
413 # permitted, we don't check for that, since it will be escaped
414 # anyway.)
415 #
416 # See also research done on further characters that need to be
417 # escaped: http://code.google.com/p/html5lib/issues/detail?id=93
418 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
419 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
420 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
421 if ( $wgWellFormedXml || $value === ''
422 || preg_match( "![$badChars]!u", $value ) ) {
423 $quote = '"';
424 } else {
425 $quote = '';
426 }
427
428 if ( in_array( $key, self::$boolAttribs ) ) {
429 # In XHTML 1.0 Transitional, the value needs to be equal to the
430 # key. In HTML5, we can leave the value empty instead. If we
431 # don't need well-formed XML, we can omit the = entirely.
432 if ( !$wgWellFormedXml ) {
433 $ret .= " $key";
434 } elseif ( $wgHtml5 ) {
435 $ret .= " $key=\"\"";
436 } else {
437 $ret .= " $key=\"$key\"";
438 }
439 } else {
440 # Apparently we need to entity-encode \n, \r, \t, although the
441 # spec doesn't mention that. Since we're doing strtr() anyway,
442 # and we don't need <> escaped here, we may as well not call
443 # htmlspecialchars().
444 # @todo FIXME: Verify that we actually need to
445 # escape \n\r\t here, and explain why, exactly.
446 #
447 # We could call Sanitizer::encodeAttribute() for this, but we
448 # don't because we're stubborn and like our marginal savings on
449 # byte size from not having to encode unnecessary quotes.
450 $map = array(
451 '&' => '&amp;',
452 '"' => '&quot;',
453 "\n" => '&#10;',
454 "\r" => '&#13;',
455 "\t" => '&#9;'
456 );
457 if ( $wgWellFormedXml ) {
458 # This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
459 # But reportedly it breaks some XML tools?
460 # @todo FIXME: Is this really true?
461 $map['<'] = '&lt;';
462 }
463 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
464 }
465 }
466 return $ret;
467 }
468
469 /**
470 * Output a <script> tag with the given contents. TODO: do some useful
471 * escaping as well, like if $contents contains literal '</script>' or (for
472 * XML) literal "]]>".
473 *
474 * @param $contents string JavaScript
475 * @return string Raw HTML
476 */
477 public static function inlineScript( $contents ) {
478 global $wgHtml5, $wgJsMimeType, $wgWellFormedXml;
479
480 $attrs = array();
481
482 if ( !$wgHtml5 ) {
483 $attrs['type'] = $wgJsMimeType;
484 }
485
486 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
487 $contents = "/*<![CDATA[*/$contents/*]]>*/";
488 }
489
490 return self::rawElement( 'script', $attrs, $contents );
491 }
492
493 /**
494 * Output a <script> tag linking to the given URL, e.g.,
495 * <script src=foo.js></script>.
496 *
497 * @param $url string
498 * @return string Raw HTML
499 */
500 public static function linkedScript( $url ) {
501 global $wgHtml5, $wgJsMimeType;
502
503 $attrs = array( 'src' => $url );
504
505 if ( !$wgHtml5 ) {
506 $attrs['type'] = $wgJsMimeType;
507 }
508
509 return self::element( 'script', $attrs );
510 }
511
512 /**
513 * Output a <style> tag with the given contents for the given media type
514 * (if any). TODO: do some useful escaping as well, like if $contents
515 * contains literal '</style>' (admittedly unlikely).
516 *
517 * @param $contents string CSS
518 * @param $media mixed A media type string, like 'screen'
519 * @return string Raw HTML
520 */
521 public static function inlineStyle( $contents, $media = 'all' ) {
522 global $wgWellFormedXml;
523
524 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
525 $contents = "/*<![CDATA[*/$contents/*]]>*/";
526 }
527
528 return self::rawElement( 'style', array(
529 'type' => 'text/css',
530 'media' => $media,
531 ), $contents );
532 }
533
534 /**
535 * Output a <link rel=stylesheet> linking to the given URL for the given
536 * media type (if any).
537 *
538 * @param $url string
539 * @param $media mixed A media type string, like 'screen'
540 * @return string Raw HTML
541 */
542 public static function linkedStyle( $url, $media = 'all' ) {
543 return self::element( 'link', array(
544 'rel' => 'stylesheet',
545 'href' => $url,
546 'type' => 'text/css',
547 'media' => $media,
548 ) );
549 }
550
551 /**
552 * Convenience function to produce an <input> element. This supports the
553 * new HTML5 input types and attributes, and will silently strip them if
554 * $wgHtml5 is false.
555 *
556 * @param $name string name attribute
557 * @param $value mixed value attribute
558 * @param $type string type attribute
559 * @param $attribs array Associative array of miscellaneous extra
560 * attributes, passed to Html::element()
561 * @return string Raw HTML
562 */
563 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
564 $attribs['type'] = $type;
565 $attribs['value'] = $value;
566 $attribs['name'] = $name;
567
568 return self::element( 'input', $attribs );
569 }
570
571 /**
572 * Convenience function to produce an input element with type=hidden
573 *
574 * @param $name string name attribute
575 * @param $value string value attribute
576 * @param $attribs array Associative array of miscellaneous extra
577 * attributes, passed to Html::element()
578 * @return string Raw HTML
579 */
580 public static function hidden( $name, $value, $attribs = array() ) {
581 return self::input( $name, $value, 'hidden', $attribs );
582 }
583
584 /**
585 * Convenience function to produce an <input> element. This supports leaving
586 * out the cols= and rows= which Xml requires and are required by HTML4/XHTML
587 * but not required by HTML5 and will silently set cols="" and rows="" if
588 * $wgHtml5 is false and cols and rows are omitted (HTML4 validates present
589 * but empty cols="" and rows="" as valid).
590 *
591 * @param $name string name attribute
592 * @param $value string value attribute
593 * @param $attribs array Associative array of miscellaneous extra
594 * attributes, passed to Html::element()
595 * @return string Raw HTML
596 */
597 public static function textarea( $name, $value = '', $attribs = array() ) {
598 global $wgHtml5;
599
600 $attribs['name'] = $name;
601
602 if ( !$wgHtml5 ) {
603 if ( !isset( $attribs['cols'] ) ) {
604 $attribs['cols'] = "";
605 }
606
607 if ( !isset( $attribs['rows'] ) ) {
608 $attribs['rows'] = "";
609 }
610 }
611
612 return self::element( 'textarea', $attribs, $value );
613 }
614
615 /**
616 * Constructs the opening html-tag with necessary doctypes depending on
617 * global variables.
618 *
619 * @param $attribs array Associative array of miscellaneous extra
620 * attributes, passed to Html::element() of html tag.
621 * @return string Raw HTML
622 */
623 public static function htmlHeader( $attribs = array() ) {
624 $ret = '';
625
626 global $wgMimeType;
627
628 if ( self::isXmlMimeType( $wgMimeType ) ) {
629 $ret .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?" . ">\n";
630 }
631
632 global $wgHtml5, $wgHtml5Version, $wgDocType, $wgDTD;
633 global $wgXhtmlNamespaces, $wgXhtmlDefaultNamespace;
634
635 if ( $wgHtml5 ) {
636 $ret .= "<!DOCTYPE html>\n";
637
638 if ( $wgHtml5Version ) {
639 $attribs['version'] = $wgHtml5Version;
640 }
641 } else {
642 $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
643 $attribs['xmlns'] = $wgXhtmlDefaultNamespace;
644
645 foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
646 $attribs["xmlns:$tag"] = $ns;
647 }
648 }
649
650 $html = Html::openElement( 'html', $attribs );
651
652 if ( $html ) {
653 $html .= "\n";
654 }
655
656 $ret .= $html;
657
658 return $ret;
659 }
660
661 /**
662 * Determines if the given mime type is xml.
663 *
664 * @param $mimetype string MimeType
665 * @return Boolean
666 */
667 public static function isXmlMimeType( $mimetype ) {
668 switch ( $mimetype ) {
669 case 'text/xml':
670 case 'application/xhtml+xml':
671 case 'application/xml':
672 return true;
673 default:
674 return false;
675 }
676 }
677
678 /**
679 * Get HTML for an info box with an icon.
680 *
681 * @param $text String: wikitext, get this with wfMsgNoTrans()
682 * @param $icon String: icon name, file in skins/common/images
683 * @param $alt String: alternate text for the icon
684 * @param $class String: additional class name to add to the wrapper div
685 * @param $useStylePath
686 *
687 * @return string
688 */
689 static function infoBox( $text, $icon, $alt, $class = false, $useStylePath = true ) {
690 global $wgStylePath;
691
692 if ( $useStylePath ) {
693 $icon = $wgStylePath.'/common/images/'.$icon;
694 }
695
696 $s = Html::openElement( 'div', array( 'class' => "mw-infobox $class") );
697
698 $s .= Html::openElement( 'div', array( 'class' => 'mw-infobox-left' ) ).
699 Html::element( 'img',
700 array(
701 'src' => $icon,
702 'alt' => $alt,
703 )
704 ).
705 Html::closeElement( 'div' );
706
707 $s .= Html::openElement( 'div', array( 'class' => 'mw-infobox-right' ) ).
708 $text.
709 Html::closeElement( 'div' );
710 $s .= Html::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
711
712 $s .= Html::closeElement( 'div' );
713
714 $s .= Html::element( 'div', array( 'style' => 'clear: left;' ), ' ' );
715
716 return $s;
717 }
718 }