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