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