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