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