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