Add a new searchmenu-new-nocreate message
[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 2009-08-10.
65 private static $boolAttribs = array(
66 'async',
67 'autobuffer',
68 'autofocus',
69 'autoplay',
70 'checked',
71 'controls',
72 'defer',
73 'disabled',
74 'formnovalidate',
75 'hidden',
76 'ismap',
77 'loop',
78 'multiple',
79 'novalidate',
80 'open',
81 'readonly',
82 'required',
83 'reversed',
84 'scoped',
85 'seamless',
86 );
87
88 /**
89 * Returns an HTML element in a string. The major advantage here over
90 * manually typing out the HTML is that it will escape all attribute
91 * values. If you're hardcoding all the attributes, or there are none, you
92 * should probably type out the string yourself.
93 *
94 * This is quite similar to Xml::tags(), but it implements some useful
95 * HTML-specific logic. For instance, there is no $allowShortTag
96 * parameter: the closing tag is magically omitted if $element has an empty
97 * content model. If $wgWellFormedXml is false, then a few bytes will be
98 * shaved off the HTML output as well. In the future, other HTML-specific
99 * features might be added, like allowing arrays for the values of
100 * attributes like class= and media=.
101 *
102 * @param $element string The element's name, e.g., 'a'
103 * @param $attribs array Associative array of attributes, e.g., array(
104 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
105 * further documentation.
106 * @param $contents string The raw HTML contents of the element: *not*
107 * escaped!
108 * @return string Raw HTML
109 */
110 public static function rawElement( $element, $attribs = array(), $contents = '' ) {
111 global $wgWellFormedXml;
112 $start = self::openElement( $element, $attribs );
113 if ( in_array( $element, self::$voidElements ) ) {
114 if ( $wgWellFormedXml ) {
115 # Silly XML.
116 return substr( $start, 0, -1 ) . ' />';
117 }
118 return $start;
119 } else {
120 return "$start$contents" . self::closeElement( $element );
121 }
122 }
123
124 /**
125 * Identical to rawElement(), but HTML-escapes $contents (like
126 * Xml::element()).
127 */
128 public static function element( $element, $attribs = array(), $contents = '' ) {
129 return self::rawElement( $element, $attribs, strtr( $contents, array(
130 # There's no point in escaping quotes, >, etc. in the contents of
131 # elements.
132 '&' => '&amp;',
133 '<' => '&lt;'
134 ) ) );
135 }
136
137 /**
138 * Identical to rawElement(), but has no third parameter and omits the end
139 * tag (and the self-closing '/' in XML mode for empty elements).
140 */
141 public static function openElement( $element, $attribs = array() ) {
142 global $wgHtml5, $wgWellFormedXml;
143 $attribs = (array)$attribs;
144 # This is not required in HTML5, but let's do it anyway, for
145 # consistency and better compression.
146 $element = strtolower( $element );
147
148 # In text/html, initial <html> and <head> tags can be omitted under
149 # pretty much any sane circumstances, if they have no attributes. See:
150 # <http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags>
151 if ( !$wgWellFormedXml && !$attribs
152 && in_array( $element, array( 'html', 'head' ) ) ) {
153 return '';
154 }
155
156 # Remove HTML5-only attributes if we aren't doing HTML5
157 if ( !$wgHtml5 ) {
158 if ( $element == 'input' ) {
159 # Whitelist of valid XHTML1 types
160 $validTypes = array(
161 'hidden',
162 'text',
163 'password',
164 'checkbox',
165 'radio',
166 'file',
167 'submit',
168 'image',
169 'reset',
170 'button',
171 );
172 if ( isset( $attribs['type'] )
173 && !in_array( $attribs['type'], $validTypes ) ) {
174 # Fall back to type=text, the default
175 unset( $attribs['type'] );
176 }
177 }
178 if ( $element == 'textarea' && isset( $attribs['maxlength'] ) ) {
179 unset( $attribs['maxlength'] );
180 }
181 # Here we're blacklisting some HTML5-only attributes...
182 $html5attribs = array(
183 'autocomplete',
184 'autofocus',
185 'max',
186 'min',
187 'multiple',
188 'pattern',
189 'placeholder',
190 'required',
191 'step',
192 'spellcheck',
193 );
194 foreach ( $html5attribs as $badAttr ) {
195 unset( $attribs[$badAttr] );
196 }
197 }
198
199 return "<$element" . self::expandAttributes(
200 self::dropDefaults( $element, $attribs ) ) . '>';
201 }
202
203 /**
204 * Returns "</$element>", except if $wgWellFormedXml is off, in which case
205 * it returns the empty string when that's guaranteed to be safe.
206 *
207 * @param $element string Name of the element, e.g., 'a'
208 * @return string A closing tag, if required
209 */
210 public static function closeElement( $element ) {
211 global $wgWellFormedXml;
212
213 $element = strtolower( $element );
214
215 # Reference:
216 # http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags
217 if ( !$wgWellFormedXml && in_array( $element, array(
218 'html',
219 'head',
220 'body',
221 'li',
222 'dt',
223 'dd',
224 'tr',
225 'td',
226 'th',
227 ) ) ) {
228 return '';
229 }
230 return "</$element>";
231 }
232
233 /**
234 * Given an element name and an associative array of element attributes,
235 * return an array that is functionally identical to the input array, but
236 * possibly smaller. In particular, attributes might be stripped if they
237 * are given their default values.
238 *
239 * This method is not guaranteed to remove all redundant attributes, only
240 * some common ones and some others selected arbitrarily at random. It
241 * only guarantees that the output array should be functionally identical
242 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
243 *
244 * @param $element string Name of the element, e.g., 'a'
245 * @param $attribs array Associative array of attributes, e.g., array(
246 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
247 * further documentation.
248 * @return array An array of attributes functionally identical to $attribs
249 */
250 private static function dropDefaults( $element, $attribs ) {
251 # Don't bother doing anything if we aren't outputting HTML5; it's too
252 # much of a pain to maintain two sets of defaults.
253 global $wgHtml5;
254 if ( !$wgHtml5 ) {
255 return $attribs;
256 }
257
258 static $attribDefaults = array(
259 'area' => array( 'shape' => 'rect' ),
260 'button' => array(
261 'formaction' => 'GET',
262 'formenctype' => 'application/x-www-form-urlencoded',
263 'type' => 'submit',
264 ),
265 'canvas' => array(
266 'height' => '150',
267 'width' => '300',
268 ),
269 'command' => array( 'type' => 'command' ),
270 'form' => array(
271 'action' => 'GET',
272 'autocomplete' => 'on',
273 'enctype' => 'application/x-www-form-urlencoded',
274 ),
275 'input' => array(
276 'formaction' => 'GET',
277 'type' => 'text',
278 'value' => '',
279 ),
280 'keygen' => array( 'keytype' => 'rsa' ),
281 'link' => array( 'media' => 'all' ),
282 'menu' => array( 'type' => 'list' ),
283 # Note: the use of text/javascript here instead of other JavaScript
284 # MIME types follows the HTML5 spec.
285 'script' => array( 'type' => 'text/javascript' ),
286 'style' => array(
287 'media' => 'all',
288 'type' => 'text/css',
289 ),
290 'textarea' => array( 'wrap' => 'soft' ),
291 );
292
293 $element = strtolower( $element );
294
295 foreach ( $attribs as $attrib => $value ) {
296 $lcattrib = strtolower( $attrib );
297 $value = strval( $value );
298
299 # Simple checks using $attribDefaults
300 if ( isset( $attribDefaults[$element][$lcattrib] ) &&
301 $attribDefaults[$element][$lcattrib] == $value ) {
302 unset( $attribs[$attrib] );
303 }
304
305 if ( $lcattrib == 'class' && $value == '' ) {
306 unset( $attribs[$attrib] );
307 }
308 }
309
310 # More subtle checks
311 if ( $element === 'link' && isset( $attribs['type'] )
312 && strval( $attribs['type'] ) == 'text/css' ) {
313 unset( $attribs['type'] );
314 }
315 if ( $element === 'select' && isset( $attribs['size'] ) ) {
316 if ( in_array( 'multiple', $attribs )
317 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
318 ) {
319 # A multi-select
320 if ( strval( $attribs['size'] ) == '4' ) {
321 unset( $attribs['size'] );
322 }
323 } else {
324 # Single select
325 if ( strval( $attribs['size'] ) == '1' ) {
326 unset( $attribs['size'] );
327 }
328 }
329 }
330
331 return $attribs;
332 }
333
334 /**
335 * Given an associative array of element attributes, generate a string
336 * to stick after the element name in HTML output. Like array( 'href' =>
337 * 'http://www.mediawiki.org/' ) becomes something like
338 * ' href="http://www.mediawiki.org"'. Again, this is like
339 * Xml::expandAttributes(), but it implements some HTML-specific logic.
340 * For instance, it will omit quotation marks if $wgWellFormedXml is false,
341 * and will treat boolean attributes specially.
342 *
343 * @param $attribs array Associative array of attributes, e.g., array(
344 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
345 * A value of false means to omit the attribute. For boolean attributes,
346 * you can omit the key, e.g., array( 'checked' ) instead of
347 * array( 'checked' => 'checked' ) or such.
348 * @return string HTML fragment that goes between element name and '>'
349 * (starting with a space if at least one attribute is output)
350 */
351 public static function expandAttributes( $attribs ) {
352 global $wgHtml5, $wgWellFormedXml;
353
354 $ret = '';
355 $attribs = (array)$attribs;
356 foreach ( $attribs as $key => $value ) {
357 if ( $value === false ) {
358 continue;
359 }
360
361 # For boolean attributes, support array( 'foo' ) instead of
362 # requiring array( 'foo' => 'meaningless' ).
363 if ( is_int( $key )
364 && in_array( strtolower( $value ), self::$boolAttribs ) ) {
365 $key = $value;
366 }
367
368 # Not technically required in HTML5, but required in XHTML 1.0,
369 # and we'd like consistency and better compression anyway.
370 $key = strtolower( $key );
371
372 # See the "Attributes" section in the HTML syntax part of HTML5,
373 # 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
374 # marks omitted, but not all. (Although a literal " is not
375 # permitted, we don't check for that, since it will be escaped
376 # anyway.)
377 #
378 # See also research done on further characters that need to be
379 # escaped: http://code.google.com/p/html5lib/issues/detail?id=93
380 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
381 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
382 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
383 if ( $wgWellFormedXml || $value === ''
384 || preg_match( "![$badChars]!u", $value ) ) {
385 $quote = '"';
386 } else {
387 $quote = '';
388 }
389
390 if ( in_array( $key, self::$boolAttribs ) ) {
391 # In XHTML 1.0 Transitional, the value needs to be equal to the
392 # key. In HTML5, we can leave the value empty instead. If we
393 # don't need well-formed XML, we can omit the = entirely.
394 if ( !$wgWellFormedXml ) {
395 $ret .= " $key";
396 } elseif ( $wgHtml5 ) {
397 $ret .= " $key=\"\"";
398 } else {
399 $ret .= " $key=\"$key\"";
400 }
401 } else {
402 # Apparently we need to entity-encode \n, \r, \t, although the
403 # spec doesn't mention that. Since we're doing strtr() anyway,
404 # and we don't need <> escaped here, we may as well not call
405 # htmlspecialchars(). FIXME: verify that we actually need to
406 # escape \n\r\t here, and explain why, exactly.
407 #
408 # We could call Sanitizer::encodeAttribute() for this, but we
409 # don't because we're stubborn and like our marginal savings on
410 # byte size from not having to encode unnecessary quotes.
411 $map = array(
412 '&' => '&amp;',
413 '"' => '&quot;',
414 "\n" => '&#10;',
415 "\r" => '&#13;',
416 "\t" => '&#9;'
417 );
418 if ( $wgWellFormedXml ) {
419 # This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
420 # But reportedly it breaks some XML tools? FIXME: is this
421 # really true?
422 $map['<'] = '&lt;';
423 }
424 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
425 }
426 }
427 return $ret;
428 }
429
430 /**
431 * Output a <script> tag with the given contents. TODO: do some useful
432 * escaping as well, like if $contents contains literal '</script>' or (for
433 * XML) literal "]]>".
434 *
435 * @param $contents string JavaScript
436 * @return string Raw HTML
437 */
438 public static function inlineScript( $contents ) {
439 global $wgHtml5, $wgJsMimeType, $wgWellFormedXml;
440
441 $attrs = array();
442 if ( !$wgHtml5 ) {
443 $attrs['type'] = $wgJsMimeType;
444 }
445 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
446 $contents = "/*<![CDATA[*/$contents/*]]>*/";
447 }
448 return self::rawElement( 'script', $attrs, $contents );
449 }
450
451 /**
452 * Output a <script> tag linking to the given URL, e.g.,
453 * <script src=foo.js></script>.
454 *
455 * @param $url string
456 * @return string Raw HTML
457 */
458 public static function linkedScript( $url ) {
459 global $wgHtml5, $wgJsMimeType;
460
461 $attrs = array( 'src' => $url );
462 if ( !$wgHtml5 ) {
463 $attrs['type'] = $wgJsMimeType;
464 }
465 return self::element( 'script', $attrs );
466 }
467
468 /**
469 * Output a <style> tag with the given contents for the given media type
470 * (if any). TODO: do some useful escaping as well, like if $contents
471 * contains literal '</style>' (admittedly unlikely).
472 *
473 * @param $contents string CSS
474 * @param $media mixed A media type string, like 'screen'
475 * @return string Raw HTML
476 */
477 public static function inlineStyle( $contents, $media = 'all' ) {
478 global $wgWellFormedXml;
479
480 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
481 $contents = "/*<![CDATA[*/$contents/*]]>*/";
482 }
483 return self::rawElement( 'style', array(
484 'type' => 'text/css',
485 'media' => $media,
486 ), $contents );
487 }
488
489 /**
490 * Output a <link rel=stylesheet> linking to the given URL for the given
491 * media type (if any).
492 *
493 * @param $url string
494 * @param $media mixed A media type string, like 'screen'
495 * @return string Raw HTML
496 */
497 public static function linkedStyle( $url, $media = 'all' ) {
498 return self::element( 'link', array(
499 'rel' => 'stylesheet',
500 'href' => $url,
501 'type' => 'text/css',
502 'media' => $media,
503 ) );
504 }
505
506 /**
507 * Convenience function to produce an <input> element. This supports the
508 * new HTML5 input types and attributes, and will silently strip them if
509 * $wgHtml5 is false.
510 *
511 * @param $name string name attribute
512 * @param $value mixed value attribute
513 * @param $type string type attribute
514 * @param $attribs array Associative array of miscellaneous extra
515 * attributes, passed to Html::element()
516 * @return string Raw HTML
517 */
518 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
519 $attribs['type'] = $type;
520 $attribs['value'] = $value;
521 $attribs['name'] = $name;
522
523 return self::element( 'input', $attribs );
524 }
525
526 /**
527 * Convenience function to produce an input element with type=hidden, like
528 * Xml::hidden.
529 *
530 * @param $name string name attribute
531 * @param $value string value attribute
532 * @param $attribs array Associative array of miscellaneous extra
533 * attributes, passed to Html::element()
534 * @return string Raw HTML
535 */
536 public static function hidden( $name, $value, $attribs = array() ) {
537 return self::input( $name, $value, 'hidden', $attribs );
538 }
539
540 /**
541 * Convenience function to produce an <input> element. This supports leaving
542 * out the cols= and rows= which Xml requires and are required by HTML4/XHTML
543 * but not required by HTML5 and will silently set cols="" and rows="" if
544 * $wgHtml5 is false and cols and rows are omitted (HTML4 validates present
545 * but empty cols="" and rows="" as valid).
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 textarea( $name, $value = '', $attribs = array() ) {
554 global $wgHtml5;
555 $attribs['name'] = $name;
556 if ( !$wgHtml5 ) {
557 if ( !isset( $attribs['cols'] ) )
558 $attribs['cols'] = "";
559 if ( !isset( $attribs['rows'] ) )
560 $attribs['rows'] = "";
561 }
562 return self::element( 'textarea', $attribs, $value );
563 }
564 }