84acf31b6347303d1f38448ed4d568d49e734ce6
[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</$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;
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 # Remove HTML5-only attributes if we aren't doing HTML5
149 if ( !$wgHtml5 ) {
150 if ( $element == 'input' ) {
151 # Whitelist of valid XHTML1 types
152 $validTypes = array(
153 'hidden',
154 'text',
155 'password',
156 'checkbox',
157 'radio',
158 'file',
159 'submit',
160 'image',
161 'reset',
162 'button',
163 );
164 if ( isset( $attribs['type'] )
165 && !in_array( $attribs['type'], $validTypes ) ) {
166 # Fall back to type=text, the default
167 unset( $attribs['type'] );
168 }
169 }
170 if ( $element == 'textarea' && isset( $attribs['maxlength'] ) ) {
171 unset( $attribs['maxlength'] );
172 }
173 # Here we're blacklisting some HTML5-only attributes...
174 $html5attribs = array(
175 'autocomplete',
176 'autofocus',
177 'max',
178 'min',
179 'multiple',
180 'pattern',
181 'placeholder',
182 'required',
183 'step',
184 'spellcheck',
185 );
186 foreach ( $html5attribs as $badAttr ) {
187 unset( $attribs[$badAttr] );
188 }
189 }
190
191 return "<$element" . self::expandAttributes(
192 self::dropDefaults( $element, $attribs ) ) . '>';
193 }
194
195 /**
196 * Given an element name and an associative array of element attributes,
197 * return an array that is functionally identical to the input array, but
198 * possibly smaller. In particular, attributes might be stripped if they
199 * are given their default values.
200 *
201 * This method is not guaranteed to remove all redundant attributes, only
202 * some common ones and some others selected arbitrarily at random. It
203 * only guarantees that the output array should be functionally identical
204 * to the input array (currently per the HTML 5 draft as of 2009-09-06).
205 *
206 * @param $element string Name of the element, e.g., 'a'
207 * @param $attribs array Associative array of attributes, e.g., array(
208 * 'href' => 'http://www.mediawiki.org/' ). See expandAttributes() for
209 * further documentation.
210 * @return array An array of attributes functionally identical to $attribs
211 */
212 private static function dropDefaults( $element, $attribs ) {
213 # Don't bother doing anything if we aren't outputting HTML5; it's too
214 # much of a pain to maintain two sets of defaults.
215 global $wgHtml5;
216 if ( !$wgHtml5 ) {
217 return $attribs;
218 }
219
220 static $attribDefaults = array(
221 'area' => array( 'shape' => 'rect' ),
222 'button' => array(
223 'formaction' => 'GET',
224 'formenctype' => 'application/x-www-form-urlencoded',
225 'type' => 'submit',
226 ),
227 'canvas' => array(
228 'height' => '150',
229 'width' => '300',
230 ),
231 'command' => array( 'type' => 'command' ),
232 'form' => array(
233 'action' => 'GET',
234 'autocomplete' => 'on',
235 'enctype' => 'application/x-www-form-urlencoded',
236 ),
237 'input' => array(
238 'formaction' => 'GET',
239 'type' => 'text',
240 'value' => '',
241 ),
242 'keygen' => array( 'keytype' => 'rsa' ),
243 'link' => array( 'media' => 'all' ),
244 'menu' => array( 'type' => 'list' ),
245 # Note: the use of text/javascript here instead of other JavaScript
246 # MIME types follows the HTML5 spec.
247 'script' => array( 'type' => 'text/javascript' ),
248 'style' => array(
249 'media' => 'all',
250 'type' => 'text/css',
251 ),
252 'textarea' => array( 'wrap' => 'soft' ),
253 );
254
255 $element = strtolower( $element );
256
257 foreach ( $attribs as $attrib => $value ) {
258 $lcattrib = strtolower( $attrib );
259 $value = strval( $value );
260
261 # Simple checks using $attribDefaults
262 if ( isset( $attribDefaults[$element][$lcattrib] ) &&
263 $attribDefaults[$element][$lcattrib] == $value ) {
264 unset( $attribs[$attrib] );
265 }
266
267 if ( $lcattrib == 'class' && $value == '' ) {
268 unset( $attribs[$attrib] );
269 }
270 }
271
272 # More subtle checks
273 if ( $element === 'link' && isset( $attribs['type'] )
274 && strval( $attribs['type'] ) == 'text/css' ) {
275 unset( $attribs['type'] );
276 }
277 if ( $element === 'select' && isset( $attribs['size'] ) ) {
278 if ( in_array( 'multiple', $attribs )
279 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
280 ) {
281 # A multi-select
282 if ( strval( $attribs['size'] ) == '4' ) {
283 unset( $attribs['size'] );
284 }
285 } else {
286 # Single select
287 if ( strval( $attribs['size'] ) == '1' ) {
288 unset( $attribs['size'] );
289 }
290 }
291 }
292
293 return $attribs;
294 }
295
296 /**
297 * Given an associative array of element attributes, generate a string
298 * to stick after the element name in HTML output. Like array( 'href' =>
299 * 'http://www.mediawiki.org/' ) becomes something like
300 * ' href="http://www.mediawiki.org"'. Again, this is like
301 * Xml::expandAttributes(), but it implements some HTML-specific logic.
302 * For instance, it will omit quotation marks if $wgWellFormedXml is false,
303 * and will treat boolean attributes specially.
304 *
305 * @param $attribs array Associative array of attributes, e.g., array(
306 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
307 * A value of false means to omit the attribute. For boolean attributes,
308 * you can omit the key, e.g., array( 'checked' ) instead of
309 * array( 'checked' => 'checked' ) or such.
310 * @return string HTML fragment that goes between element name and '>'
311 * (starting with a space if at least one attribute is output)
312 */
313 public static function expandAttributes( $attribs ) {
314 global $wgHtml5, $wgWellFormedXml;
315
316 $ret = '';
317 $attribs = (array)$attribs;
318 foreach ( $attribs as $key => $value ) {
319 if ( $value === false ) {
320 continue;
321 }
322
323 # For boolean attributes, support array( 'foo' ) instead of
324 # requiring array( 'foo' => 'meaningless' ).
325 if ( is_int( $key )
326 && in_array( strtolower( $value ), self::$boolAttribs ) ) {
327 $key = $value;
328 }
329
330 # Not technically required in HTML5, but required in XHTML 1.0,
331 # and we'd like consistency and better compression anyway.
332 $key = strtolower( $key );
333
334 # See the "Attributes" section in the HTML syntax part of HTML5,
335 # 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
336 # marks omitted, but not all. (Although a literal " is not
337 # permitted, we don't check for that, since it will be escaped
338 # anyway.)
339 #
340 # See also research done on further characters that need to be
341 # escaped: http://code.google.com/p/html5lib/issues/detail?id=93
342 $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
343 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
344 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
345 if ( $wgWellFormedXml || $value === ''
346 || preg_match( "![$badChars]!u", $value ) ) {
347 $quote = '"';
348 } else {
349 $quote = '';
350 }
351
352 if ( in_array( $key, self::$boolAttribs ) ) {
353 # In XHTML 1.0 Transitional, the value needs to be equal to the
354 # key. In HTML5, we can leave the value empty instead. If we
355 # don't need well-formed XML, we can omit the = entirely.
356 if ( !$wgWellFormedXml ) {
357 $ret .= " $key";
358 } elseif ( $wgHtml5 ) {
359 $ret .= " $key=\"\"";
360 } else {
361 $ret .= " $key=\"$key\"";
362 }
363 } else {
364 # Apparently we need to entity-encode \n, \r, \t, although the
365 # spec doesn't mention that. Since we're doing strtr() anyway,
366 # and we don't need <> escaped here, we may as well not call
367 # htmlspecialchars(). FIXME: verify that we actually need to
368 # escape \n\r\t here, and explain why, exactly.
369 #
370 # We could call Sanitizer::encodeAttribute() for this, but we
371 # don't because we're stubborn and like our marginal savings on
372 # byte size from not having to encode unnecessary quotes.
373 $map = array(
374 '&' => '&amp;',
375 '"' => '&quot;',
376 "\n" => '&#10;',
377 "\r" => '&#13;',
378 "\t" => '&#9;'
379 );
380 if ( $wgWellFormedXml ) {
381 # This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
382 # But reportedly it breaks some XML tools? FIXME: is this
383 # really true?
384 $map['<'] = '&lt;';
385 }
386 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
387 }
388 }
389 return $ret;
390 }
391
392 /**
393 * Output a <script> tag with the given contents. TODO: do some useful
394 * escaping as well, like if $contents contains literal '</script>' or (for
395 * XML) literal "]]>".
396 *
397 * @param $contents string JavaScript
398 * @return string Raw HTML
399 */
400 public static function inlineScript( $contents ) {
401 global $wgHtml5, $wgJsMimeType, $wgWellFormedXml;
402
403 $attrs = array();
404 if ( !$wgHtml5 ) {
405 $attrs['type'] = $wgJsMimeType;
406 }
407 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
408 $contents = "/*<![CDATA[*/$contents/*]]>*/";
409 }
410 return self::rawElement( 'script', $attrs, $contents );
411 }
412
413 /**
414 * Output a <script> tag linking to the given URL, e.g.,
415 * <script src=foo.js></script>.
416 *
417 * @param $url string
418 * @return string Raw HTML
419 */
420 public static function linkedScript( $url ) {
421 global $wgHtml5, $wgJsMimeType;
422
423 $attrs = array( 'src' => $url );
424 if ( !$wgHtml5 ) {
425 $attrs['type'] = $wgJsMimeType;
426 }
427 return self::element( 'script', $attrs );
428 }
429
430 /**
431 * Output a <style> tag with the given contents for the given media type
432 * (if any). TODO: do some useful escaping as well, like if $contents
433 * contains literal '</style>' (admittedly unlikely).
434 *
435 * @param $contents string CSS
436 * @param $media mixed A media type string, like 'screen'
437 * @return string Raw HTML
438 */
439 public static function inlineStyle( $contents, $media = 'all' ) {
440 global $wgWellFormedXml;
441
442 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
443 $contents = "/*<![CDATA[*/$contents/*]]>*/";
444 }
445 return self::rawElement( 'style', array(
446 'type' => 'text/css',
447 'media' => $media,
448 ), $contents );
449 }
450
451 /**
452 * Output a <link rel=stylesheet> linking to the given URL for the given
453 * media type (if any).
454 *
455 * @param $url string
456 * @param $media mixed A media type string, like 'screen'
457 * @return string Raw HTML
458 */
459 public static function linkedStyle( $url, $media = 'all' ) {
460 return self::element( 'link', array(
461 'rel' => 'stylesheet',
462 'href' => $url,
463 'type' => 'text/css',
464 'media' => $media,
465 ) );
466 }
467
468 /**
469 * Convenience function to produce an <input> element. This supports the
470 * new HTML5 input types and attributes, and will silently strip them if
471 * $wgHtml5 is false.
472 *
473 * @param $name string name attribute
474 * @param $value mixed value attribute
475 * @param $type string type attribute
476 * @param $attribs array Associative array of miscellaneous extra
477 * attributes, passed to Html::element()
478 * @return string Raw HTML
479 */
480 public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
481 $attribs['type'] = $type;
482 $attribs['value'] = $value;
483 $attribs['name'] = $name;
484
485 return self::element( 'input', $attribs );
486 }
487
488 /**
489 * Convenience function to produce an input element with type=hidden, like
490 * Xml::hidden.
491 *
492 * @param $name string name attribute
493 * @param $value string value attribute
494 * @param $attribs array Associative array of miscellaneous extra
495 * attributes, passed to Html::element()
496 * @return string Raw HTML
497 */
498 public static function hidden( $name, $value, $attribs = array() ) {
499 return self::input( $name, $value, 'hidden', $attribs );
500 }
501
502 /**
503 * Convenience function to produce an <input> element. This supports leaving
504 * out the cols= and rows= which Xml requires and are required by HTML4/XHTML
505 * but not required by HTML5 and will silently set cols="" and rows="" if
506 * $wgHtml5 is false and cols and rows are omitted (HTML4 validates present
507 * but empty cols="" and rows="" as valid).
508 *
509 * @param $name string name attribute
510 * @param $value string value attribute
511 * @param $attribs array Associative array of miscellaneous extra
512 * attributes, passed to Html::element()
513 * @return string Raw HTML
514 */
515 public static function textarea( $name, $value = '', $attribs = array() ) {
516 global $wgHtml5;
517 $attribs['name'] = $name;
518 if ( !$wgHtml5 ) {
519 if ( !isset( $attribs['cols'] ) )
520 $attribs['cols'] = "";
521 if ( !isset( $attribs['rows'] ) )
522 $attribs['rows'] = "";
523 }
524 return self::element( 'textarea', $attribs, $value );
525 }
526 }