fcbe4ea1c670488261db238a84f1c11a38f4be4a
[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', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input',
46 'keygen', 'link', 'meta', 'param', 'source'
47 );
48
49 # Boolean attributes, which may have the value omitted entirely. Manually
50 # collected from the HTML 5 spec as of 2009-08-10.
51 private static $boolAttribs = array( 'async', 'autobuffer', 'autofocus',
52 'autoplay', 'checked', 'controls', 'defer', 'disabled',
53 'formnovalidate', 'hidden', 'ismap', 'loop', 'multiple', 'novalidate',
54 'open', 'readonly', 'required', 'reversed', 'scoped', 'seamless'
55 );
56
57 /**
58 * Returns an HTML element in a string. The major advantage here over
59 * manually typing out the HTML is that it will escape all attribute
60 * values. If you're hardcoding all the attributes, or there are none, you
61 * should probably type out the string yourself.
62 *
63 * This is quite similar to Xml::element(), but it implements some useful
64 * HTML-specific logic. For instance, there is no $allowShortTag
65 * parameter: the closing tag is magically omitted if $element has an empty
66 * content model. If $wgWellFormedXml is false, then a few bytes will be
67 * shaved off the HTML output as well. In the future, other HTML-specific
68 * features might be added, like allowing arrays for the values of
69 * attributes like class= and media=.
70 *
71 * One notable difference to Xml::element() is that $contents is *not*
72 * escaped. This means that Html::element() can be usefully nested, rather
73 * than using the rather clumsy Xml::openElement() and Xml::closeElement().
74 *
75 * @param $element string The element's name, e.g., 'a'
76 * @param $attribs array Associative array of attributes, e.g., array(
77 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
78 * @param $contents string The raw HTML contents of the element: *not*
79 * escaped!
80 * @return string Raw HTML
81 */
82 public static function rawElement( $element, $attribs = array(), $contents = '' ) {
83 global $wgWellFormedXml;
84 $element = strtolower( $element );
85 $start = "<$element" . self::expandAttributes( $attribs );
86 if ( in_array( $element, self::$voidElements ) ) {
87 if ( $wgWellFormedXml ) {
88 return "$start />";
89 }
90 return "$start>";
91 } else {
92 return "$start>$contents</$element>";
93 }
94 }
95
96 /**
97 * Identical to rawElement(), but HTML-escapes $contents.
98 */
99 public static function element( $element, $attribs = array(), $contents = '' ) {
100 return self::rawElement( $element, $attribs, htmlspecialchars( $contents ) );
101 }
102
103 /**
104 * Given an associative array of element attributes, generate a string
105 * to stick after the element name in HTML output. Like array( 'href' =>
106 * 'http://www.mediawiki.org/' ) becomes something like
107 * ' href="http://www.mediawiki.org"'. Again, this is like
108 * Xml::expandAttributes(), but it implements some HTML-specific logic.
109 * For instance, it will omit quotation marks if $wgWellFormedXml is false,
110 * and will treat boolean attributes specially.
111 *
112 * @param $attribs array Associative array of attributes, e.g., array(
113 * 'href' => 'http://www.mediawiki.org/' ). Values will be HTML-escaped.
114 * @return string HTML fragment that goes between element name and '>'
115 * (starting with a space if at least one attribute is output)
116 */
117 public static function expandAttributes( $attribs ) {
118 global $wgHtml5, $wgWellFormedXml;
119
120 $ret = '';
121 foreach ( $attribs as $key => $value ) {
122 # See the "Attributes" section in the HTML syntax part of HTML 5,
123 # 9.1.2.3 as of 2009-08-10. Most attributes can have quotation
124 # marks omitted, but not all. (Although a literal " is not
125 # permitted, we don't check for that, since it will be escaped
126 # anyway.)
127 if ( $wgWellFormedXml || $value == ''
128 || preg_match( "/[ '=<>]/", $value ) ) {
129 $quote = '"';
130 } else {
131 $quote = '';
132 }
133
134 if ( in_array( $key, self::$boolAttribs ) ) {
135 # In XHTML 1.0 Transitional, the value needs to be equal to the
136 # key. In HTML 5, we can leave the value empty instead. If we
137 # don't need well-formed XML, we can omit the = entirely.
138 if ( !$wgWellFormedXml ) {
139 $ret .= " $key";
140 } elseif ( $wgHtml5 ) {
141 $ret .= " $key=\"\"";
142 } else {
143 $ret .= " $key=\"$key\"";
144 }
145 } else {
146 # Apparently we need to entity-encode \n, \r, \t, although the
147 # spec doesn't mention that. Since we're doing strtr() anyway,
148 # and we don't need <> escaped here, we may as well not call
149 # htmlspecialchars(). FIXME: verify that we actually need to
150 # escape \n\r\t here, and explain why, exactly.
151 $ret .= " $key=$quote" . strtr( $value, array(
152 '&' => '&amp;',
153 '"' => '&quot;',
154 "\n" => '&#10;',
155 "\r" => '&#13;',
156 "\t" => '&#9;'
157 ) ) . $quote;
158 }
159 }
160 return $ret;
161 }
162
163 /**
164 * Output a <script> tag with the given contents. TODO: do some useful
165 * escaping as well, like if $contents contains literal '</script>' or (for
166 * XML) literal "]]>".
167 *
168 * Note that $contents will not be escaped, since JS may legitimately
169 * contain unescaped characters like "<". Make sure you don't output
170 * untrusted user input here!
171 *
172 * @param $contents string JavaScript
173 * @return string Raw HTML
174 */
175 public static function inlineScript( $contents ) {
176 global $wgHtml5, $wgJsMimeType;
177
178 $attrs = array();
179 if ( !$wgHtml5 ) {
180 $attrs['type'] = $wgJsMimeType;
181 $contents = "/*<![CDATA[*/$contents/*]]>*/";
182 }
183 return self::rawElement( 'script', $attrs, $contents );
184 }
185
186 /**
187 * Output a <script> tag linking to the given URL, e.g.,
188 * <script src=foo.js></script>.
189 *
190 * @param $url string
191 * @return string Raw HTML
192 */
193 public static function linkedScript( $url ) {
194 global $wgHtml5, $wgJsMimeType;
195
196 $attrs = array( 'src' => $url );
197 if ( !$wgHtml5 ) {
198 $attrs['type'] = $wgJsMimeType;
199 }
200 return self::element( 'script', $attrs );
201 }
202
203 /**
204 * Output a <style> tag with the given contents for the given media type
205 * (if any). TODO: do some useful escaping as well, like if $contents
206 * contains literal '</style>' (admittedly unlikely).
207 *
208 * Note that $contents will not be escaped, since CSS may legitimately
209 * contain unescaped characters like "<". Make sure you don't output
210 * untrusted user input here!
211 *
212 * @param $contents string CSS
213 * @param $media mixed A media type string, like 'screen', or null for all
214 * media
215 * @return string Raw HTML
216 */
217 public static function inlineStyle( $contents, $media = null ) {
218 global $wgHtml5;
219
220 $attrs = array();
221 if ( !$wgHtml5 ) {
222 # Technically we should probably add CDATA stuff here like with
223 # scripts, but in practice, stylesheets tend not to have
224 # problematic characters anyway.
225 $attrs['type'] = 'text/css';
226 }
227 if ( $media !== null ) {
228 $attrs['media'] = $media;
229 }
230 return self::rawElement( 'style', $attrs, $contents );
231 }
232
233 /**
234 * Output a <link rel=stylesheet> linking to the given URL for the given
235 * media type (if any).
236 *
237 * @param $url string
238 * @param $media mixed A media type string, like 'screen', or null for all
239 * media
240 * @return string Raw HTML
241 */
242 public static function linkedStyle( $url, $media = null ) {
243 global $wgHtml5;
244
245 $attrs = array( 'rel' => 'stylesheet', 'href' => $url );
246 if ( !$wgHtml5 ) {
247 $attrs['type'] = 'text/css';
248 }
249 if ( $media !== null ) {
250 $attrs['media'] = $media;
251 }
252 return self::element( 'link', $attrs );
253 }
254
255 /**
256 * Convenience function to produce an <input> element. This supports the
257 * new HTML 5 input types and attributes, and will silently strip them if
258 * $wgHtml5 is false.
259 *
260 * @param $name string name attribute
261 * @param $value mixed value attribute (null = omit)
262 * @param $type string type attribute
263 * @param $attribs array Assocative array of miscellaneous extra attributes,
264 * passed to Html::element()
265 * @return string Raw HTML
266 */
267 public static function input( $name, $value = null, $type = 'text', $attribs = array() ) {
268 global $wgHtml5;
269
270 if ( !$wgHtml5 ) {
271 if ( !in_array( $type, array( 'hidden', 'text', 'password',
272 'checkbox', 'radio', 'file', 'submit', 'image', 'reset', 'button'
273 ) ) ) {
274 $type = 'text';
275 }
276 foreach ( array( 'autocomplete', 'autofocus', 'max', 'min', 'multiple',
277 'pattern', 'placeholder', 'required', 'step' ) as $badAttr ) {
278 unset( $attribs[$badAttr] );
279 }
280 }
281 if ( $type != 'text' ) {
282 $attribs['type'] = $type;
283 }
284 if ( $value !== null ) {
285 $attribs['value'] = $value;
286 }
287 $attribs['name'] = $name;
288
289 return self::element( 'input', $attribs );
290 }
291 }