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