Move more <input> logic from input() to element()
[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 # A nested associative array of element => content attribute => default
87 # value. Attributes that have the default value will be omitted, since
88 # they're pointless. Currently the list hasn't been systematically
89 # populated.
90 private static $attribDefaults = array(
91 'input' => array(
92 'value' => '',
93 'type' => 'text',
94 ),
95 );
96
97 /**
98 * Returns an HTML element in a string. The major advantage here over
99 * manually typing out the HTML is that it will escape all attribute
100 * values. If you're hardcoding all the attributes, or there are none, you
101 * should probably type out the string yourself.
102 *
103 * This is quite similar to Xml::tags(), but it implements some useful
104 * HTML-specific logic. For instance, there is no $allowShortTag
105 * parameter: the closing tag is magically omitted if $element has an empty
106 * content model. If $wgWellFormedXml is false, then a few bytes will be
107 * shaved off the HTML output as well. In the future, other HTML-specific
108 * features might be added, like allowing arrays for the values of
109 * attributes like class= and media=.
110 *
111 * @param $element string The element's name, e.g., 'a'
112 * @param $attribs array Associative array of attributes, e.g., array(
113 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
114 * A value of false means to omit the attribute.
115 * @param $contents string The raw HTML contents of the element: *not*
116 * escaped!
117 * @return string Raw HTML
118 */
119 public static function rawElement( $element, $attribs = array(), $contents = '' ) {
120 global $wgHtml5, $wgWellFormedXml;
121 # This is not required in HTML 5, but let's do it anyway, for
122 # consistency and better compression.
123 $element = strtolower( $element );
124
125 # Element-specific hacks to slim down output and ensure validity
126 if ( $element == 'input' ) {
127 if ( !$wgHtml5 ) {
128 # With $wgHtml5 off we want to validate as XHTML 1, so we
129 # strip out any fancy HTML 5-only input types for now.
130 #
131 # Whitelist of valid types:
132 $validTypes = array(
133 'hidden',
134 'text',
135 'password',
136 'checkbox',
137 'radio',
138 'file',
139 'submit',
140 'image',
141 'reset',
142 'button',
143 );
144 if ( isset( $attribs['type'] )
145 && !in_array( $attribs['type'], $validTypes ) ) {
146 # Fall back to type=text, the default
147 unset( $attribs['type'] );
148 }
149 # Here we're blacklisting some HTML5-only attributes...
150 $html5attribs = array(
151 'autocomplete',
152 'autofocus',
153 'max',
154 'min',
155 'multiple',
156 'pattern',
157 'placeholder',
158 'required',
159 'step',
160 );
161 foreach ( $html5attribs as $badAttr ) {
162 unset( $attribs[$badAttr] );
163 }
164 }
165 }
166
167 # Don't bother outputting the default values for attributes
168 foreach ( $attribs as $attrib => $value ) {
169 $lcattrib = strtolower( $attrib );
170 if ( isset( self::$attribDefaults[$element][$lcattrib] ) &&
171 self::$attribDefaults[$element][$lcattrib] === $value ) {
172 unset( $attribs[$attrib] );
173 }
174 }
175
176 $start = "<$element" . self::expandAttributes( $attribs );
177 if ( in_array( $element, self::$voidElements ) ) {
178 if ( $wgWellFormedXml ) {
179 return "$start />";
180 }
181 return "$start>";
182 } else {
183 return "$start>$contents</$element>";
184 }
185 }
186
187 /**
188 * Identical to rawElement(), but HTML-escapes $contents (like
189 * Xml::element()).
190 */
191 public static function element( $element, $attribs = array(), $contents = '' ) {
192 return self::rawElement( $element, $attribs, strtr( $contents, array(
193 # There's no point in escaping quotes, >, etc. in the contents of
194 # elements.
195 '&' => '&amp;',
196 '<' => '&lt;'
197 ) ) );
198 }
199
200 /**
201 * Given an associative array of element attributes, generate a string
202 * to stick after the element name in HTML output. Like array( 'href' =>
203 * 'http://www.mediawiki.org/' ) becomes something like
204 * ' href="http://www.mediawiki.org"'. Again, this is like
205 * Xml::expandAttributes(), but it implements some HTML-specific logic.
206 * For instance, it will omit quotation marks if $wgWellFormedXml is false,
207 * and will treat boolean attributes specially.
208 *
209 * @param $attribs array Associative array of attributes, e.g., array(
210 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
211 * A value of false means to omit the attribute.
212 * @return string HTML fragment that goes between element name and '>'
213 * (starting with a space if at least one attribute is output)
214 */
215 public static function expandAttributes( $attribs ) {
216 global $wgHtml5, $wgWellFormedXml;
217
218 $ret = '';
219 foreach ( $attribs as $key => $value ) {
220 if ( $value === false ) {
221 continue;
222 }
223
224 # For boolean attributes, support array( 'foo' ) instead of
225 # requiring array( 'foo' => 'meaningless' ).
226 if ( is_int( $key )
227 && in_array( strtolower( $value ), self::$boolAttribs ) ) {
228 $key = $value;
229 }
230
231 # Not technically required in HTML 5, but required in XHTML 1.0,
232 # and we'd like consistency and better compression anyway.
233 $key = strtolower( $key );
234
235 # See the "Attributes" section in the HTML syntax part of HTML 5,
236 # 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
237 # marks omitted, but not all. (Although a literal " is not
238 # permitted, we don't check for that, since it will be escaped
239 # anyway.)
240 if ( $wgWellFormedXml || $value == ''
241 || preg_match( "/[ '=<>]/", $value ) ) {
242 $quote = '"';
243 } else {
244 $quote = '';
245 }
246
247 if ( in_array( $key, self::$boolAttribs ) ) {
248 # In XHTML 1.0 Transitional, the value needs to be equal to the
249 # key. In HTML 5, we can leave the value empty instead. If we
250 # don't need well-formed XML, we can omit the = entirely.
251 if ( !$wgWellFormedXml ) {
252 $ret .= " $key";
253 } elseif ( $wgHtml5 ) {
254 $ret .= " $key=\"\"";
255 } else {
256 $ret .= " $key=\"$key\"";
257 }
258 } else {
259 # Apparently we need to entity-encode \n, \r, \t, although the
260 # spec doesn't mention that. Since we're doing strtr() anyway,
261 # and we don't need <> escaped here, we may as well not call
262 # htmlspecialchars(). FIXME: verify that we actually need to
263 # escape \n\r\t here, and explain why, exactly.
264 $ret .= " $key=$quote" . strtr( $value, array(
265 '&' => '&amp;',
266 '"' => '&quot;',
267 "\n" => '&#10;',
268 "\r" => '&#13;',
269 "\t" => '&#9;'
270 ) ) . $quote;
271 }
272 }
273 return $ret;
274 }
275
276 /**
277 * Output a <script> tag with the given contents. TODO: do some useful
278 * escaping as well, like if $contents contains literal '</script>' or (for
279 * XML) literal "]]>".
280 *
281 * @param $contents string JavaScript
282 * @return string Raw HTML
283 */
284 public static function inlineScript( $contents ) {
285 global $wgHtml5, $wgJsMimeType, $wgWellFormedXml;
286
287 $attrs = array();
288 if ( !$wgHtml5 ) {
289 $attrs['type'] = $wgJsMimeType;
290 }
291 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
292 $contents = "/*<![CDATA[*/$contents/*]]>*/";
293 }
294 return self::rawElement( 'script', $attrs, $contents );
295 }
296
297 /**
298 * Output a <script> tag linking to the given URL, e.g.,
299 * <script src=foo.js></script>.
300 *
301 * @param $url string
302 * @return string Raw HTML
303 */
304 public static function linkedScript( $url ) {
305 global $wgHtml5, $wgJsMimeType;
306
307 $attrs = array( 'src' => $url );
308 if ( !$wgHtml5 ) {
309 $attrs['type'] = $wgJsMimeType;
310 }
311 return self::element( 'script', $attrs );
312 }
313
314 /**
315 * Output a <style> tag with the given contents for the given media type
316 * (if any). TODO: do some useful escaping as well, like if $contents
317 * contains literal '</style>' (admittedly unlikely).
318 *
319 * @param $contents string CSS
320 * @param $media mixed A media type string, like 'screen', or null for all
321 * media
322 * @return string Raw HTML
323 */
324 public static function inlineStyle( $contents, $media = null ) {
325 global $wgHtml5, $wgWellFormedXml;
326
327 $attrs = array();
328 if ( !$wgHtml5 ) {
329 $attrs['type'] = 'text/css';
330 }
331 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
332 $contents = "/*<![CDATA[*/$contents/*]]>*/";
333 }
334 if ( $media !== null ) {
335 $attrs['media'] = $media;
336 }
337 return self::rawElement( 'style', $attrs, $contents );
338 }
339
340 /**
341 * Output a <link rel=stylesheet> linking to the given URL for the given
342 * media type (if any).
343 *
344 * @param $url string
345 * @param $media mixed A media type string, like 'screen', or null for all
346 * media
347 * @return string Raw HTML
348 */
349 public static function linkedStyle( $url, $media = null ) {
350 global $wgHtml5;
351
352 $attrs = array( 'rel' => 'stylesheet', 'href' => $url );
353 if ( !$wgHtml5 ) {
354 $attrs['type'] = 'text/css';
355 }
356 if ( $media !== null ) {
357 $attrs['media'] = $media;
358 }
359 return self::element( 'link', $attrs );
360 }
361
362 /**
363 * Convenience function to produce an <input> element. This supports the
364 * new HTML 5 input types and attributes, and will silently strip them if
365 * $wgHtml5 is false.
366 *
367 * @param $name string name attribute
368 * @param $value mixed value attribute (null = omit)
369 * @param $type string type attribute
370 * @param $attribs array Associative array of miscellaneous extra
371 * attributes, passed to Html::element()
372 * @return string Raw HTML
373 */
374 public static function input( $name, $value = null, $type = 'text', $attribs = array() ) {
375 $attribs['type'] = $type;
376 if ( $value !== null ) {
377 $attribs['value'] = $value;
378 }
379 $attribs['name'] = $name;
380
381 return self::element( 'input', $attribs );
382 }
383
384 /**
385 * Convenience function to produce an input element with type=hidden, like
386 * Xml::hidden.
387 *
388 * @param $name string name attribute
389 * @param $value string value attribute
390 * @param $attribs array Associative array of miscellaneous extra
391 * attributes, passed to Html::element()
392 * @return string Raw HTML
393 */
394 public static function hidden( $name, $value, $attribs = array() ) {
395 return self::input( $name, $value, 'hidden', $attribs );
396 }
397 }