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