]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/Html.php
MediaWiki 1.16.0
[autoinstallsdev/mediawiki.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 HTML5, 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 HTML5, 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 HTML5 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/' ).  See expandAttributes() for
103          *   further documentation.
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 $wgWellFormedXml;
110                 $start = self::openElement( $element, $attribs );
111                 if ( in_array( $element, self::$voidElements ) ) {
112                         if ( $wgWellFormedXml ) {
113                                 # Silly XML.
114                                 return substr( $start, 0, -1 ) . ' />';
115                         }
116                         return $start;
117                 } else {
118                         return "$start$contents</$element>";
119                 }
120         }
121
122         /**
123          * Identical to rawElement(), but HTML-escapes $contents (like
124          * Xml::element()).
125          */
126         public static function element( $element, $attribs = array(), $contents = '' ) {
127                 return self::rawElement( $element, $attribs, strtr( $contents, array(
128                         # There's no point in escaping quotes, >, etc. in the contents of
129                         # elements.
130                         '&' => '&amp;',
131                         '<' => '&lt;'
132                 ) ) );
133         }
134
135         /**
136          * Identical to rawElement(), but has no third parameter and omits the end
137          * tag (and the self-closing / in XML mode for empty elements).
138          */
139         public static function openElement( $element, $attribs = array() ) {
140                 global $wgHtml5;
141                 $attribs = (array)$attribs;
142                 # This is not required in HTML5, but let's do it anyway, for
143                 # consistency and better compression.
144                 $element = strtolower( $element );
145
146                 # Remove HTML5-only attributes if we aren't doing HTML5, and disable
147                 # form validation regardless (see bug 23769 and the more detailed
148                 # comment in expandAttributes())
149                 if ( $element == 'input' ) {
150                         # Whitelist of types that don't cause validation.  All except
151                         # 'search' are valid in XHTML1.
152                         $validTypes = array(
153                                 'hidden',
154                                 'text',
155                                 'password',
156                                 'checkbox',
157                                 'radio',
158                                 'file',
159                                 'submit',
160                                 'image',
161                                 'reset',
162                                 'button',
163                                 'search',
164                         );
165                         if ( isset( $attribs['type'] )
166                         && !in_array( $attribs['type'], $validTypes ) ) {
167                                 unset( $attribs['type'] );
168                         }
169                         if ( isset( $attribs['type'] ) && $attribs['type'] == 'search'
170                         && !$wgHtml5 ) {
171                                 unset( $attribs['type'] );
172                         }
173                         # Here we're blacklisting some HTML5-only attributes...
174                         $html5attribs = array(
175                                 'autocomplete',
176                                 'autofocus',
177                                 'max',
178                                 'min',
179                                 'multiple',
180                                 'pattern',
181                                 'placeholder',
182                                 'required',
183                                 'step',
184                                 'spellcheck',
185                         );
186                         foreach ( $html5attribs as $badAttr ) {
187                                 unset( $attribs[$badAttr] );
188                         }
189                 }
190                 if ( !$wgHtml5 && $element == 'textarea' && isset( $attribs['maxlength'] ) ) {
191                         unset( $attribs['maxlength'] );
192                 }
193
194                 return "<$element" . self::expandAttributes(
195                         self::dropDefaults( $element, $attribs ) ) . '>';
196         }
197
198         /**
199          * Given an element name and an associative array of element attributes,
200          * return an array that is functionally identical to the input array, but
201          * possibly smaller.  In particular, attributes might be stripped if they
202          * are given their default values.
203          *
204          * This method is not guaranteed to remove all redundant attributes, only
205          * some common ones and some others selected arbitrarily at random.  It
206          * only guarantees that the output array should be functionally identical
207          * to the input array (currently per the HTML 5 draft as of 2009-09-06).
208          *
209          * @param $element string Name of the element, e.g., 'a'
210          * @param $attribs array  Associative array of attributes, e.g., array(
211          *   'href' => 'http://www.mediawiki.org/' ).  See expandAttributes() for
212          *   further documentation.
213          * @return array An array of attributes functionally identical to $attribs
214          */
215         private static function dropDefaults( $element, $attribs ) {
216                 # Don't bother doing anything if we aren't outputting HTML5; it's too
217                 # much of a pain to maintain two sets of defaults.
218                 global $wgHtml5;
219                 if ( !$wgHtml5 ) {
220                         return $attribs;
221                 }
222
223                 static $attribDefaults = array(
224                         'area' => array( 'shape' => 'rect' ),
225                         'button' => array(
226                                 'formaction' => 'GET',
227                                 'formenctype' => 'application/x-www-form-urlencoded',
228                                 'type' => 'submit',
229                         ),
230                         'canvas' => array(
231                                 'height' => '150',
232                                 'width' => '300',
233                         ),
234                         'command' => array( 'type' => 'command' ),
235                         'form' => array(
236                                 'action' => 'GET',
237                                 'autocomplete' => 'on',
238                                 'enctype' => 'application/x-www-form-urlencoded',
239                         ),
240                         'input' => array(
241                                 'formaction' => 'GET',
242                                 'type' => 'text',
243                                 'value' => '',
244                         ),
245                         'keygen' => array( 'keytype' => 'rsa' ),
246                         'link' => array( 'media' => 'all' ),
247                         'menu' => array( 'type' => 'list' ),
248                         # Note: the use of text/javascript here instead of other JavaScript
249                         # MIME types follows the HTML5 spec.
250                         'script' => array( 'type' => 'text/javascript' ),
251                         'style' => array(
252                                 'media' => 'all',
253                                 'type' => 'text/css',
254                         ),
255                         'textarea' => array( 'wrap' => 'soft' ),
256                 );
257
258                 $element = strtolower( $element );
259
260                 foreach ( $attribs as $attrib => $value ) {
261                         $lcattrib = strtolower( $attrib );
262                         $value = strval( $value );
263
264                         # Simple checks using $attribDefaults
265                         if ( isset( $attribDefaults[$element][$lcattrib] ) &&
266                         $attribDefaults[$element][$lcattrib] == $value ) {
267                                 unset( $attribs[$attrib] );
268                         }
269
270                         if ( $lcattrib == 'class' && $value == '' ) {
271                                 unset( $attribs[$attrib] );
272                         }
273                 }
274
275                 # More subtle checks
276                 if ( $element === 'link' && isset( $attribs['type'] )
277                 && strval( $attribs['type'] ) == 'text/css' ) {
278                         unset( $attribs['type'] );
279                 }
280                 if ( $element === 'select' && isset( $attribs['size'] ) ) {
281                         if ( in_array( 'multiple', $attribs )
282                                 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
283                         ) {
284                                 # A multi-select
285                                 if ( strval( $attribs['size'] ) == '4' ) {
286                                         unset( $attribs['size'] );
287                                 }
288                         } else {
289                                 # Single select
290                                 if ( strval( $attribs['size'] ) == '1' ) {
291                                         unset( $attribs['size'] );
292                                 }
293                         }
294                 }
295
296                 return $attribs;
297         }
298
299         /**
300          * Given an associative array of element attributes, generate a string
301          * to stick after the element name in HTML output.  Like array( 'href' =>
302          * 'http://www.mediawiki.org/' ) becomes something like
303          * ' href="http://www.mediawiki.org"'.  Again, this is like
304          * Xml::expandAttributes(), but it implements some HTML-specific logic.
305          * For instance, it will omit quotation marks if $wgWellFormedXml is false,
306          * and will treat boolean attributes specially.
307          *
308          * @param $attribs array Associative array of attributes, e.g., array(
309          *   'href' => 'http://www.mediawiki.org/' ).  Values will be HTML-escaped.
310          *   A value of false means to omit the attribute.  For boolean attributes,
311          *   you can omit the key, e.g., array( 'checked' ) instead of
312          *   array( 'checked' => 'checked' ) or such.
313          * @return string HTML fragment that goes between element name and '>'
314          *   (starting with a space if at least one attribute is output)
315          */
316         public static function expandAttributes( $attribs ) {
317                 global $wgHtml5, $wgWellFormedXml;
318
319                 $ret = '';
320                 $attribs = (array)$attribs;
321                 foreach ( $attribs as $key => $value ) {
322                         if ( $value === false ) {
323                                 continue;
324                         }
325
326                         # For boolean attributes, support array( 'foo' ) instead of
327                         # requiring array( 'foo' => 'meaningless' ).
328                         if ( is_int( $key )
329                         && in_array( strtolower( $value ), self::$boolAttribs ) ) {
330                                 $key = $value;
331                         }
332
333                         # Not technically required in HTML5, but required in XHTML 1.0,
334                         # and we'd like consistency and better compression anyway.
335                         $key = strtolower( $key );
336
337                         # Bug 23769: Blacklist all form validation attributes for now.  Current
338                         # (June 2010) WebKit has no UI, so the form just refuses to submit
339                         # without telling the user why, which is much worse than failing
340                         # server-side validation.  Opera is the only other implementation at
341                         # this time, and has ugly UI, so just kill the feature entirely until
342                         # we have at least one good implementation.
343                         if ( in_array( $key, array( 'max', 'min', 'pattern', 'required', 'step' ) ) ) {
344                                 continue;
345                         }
346
347                         # See the "Attributes" section in the HTML syntax part of HTML5,
348                         # 9.1.2.3 as of 2009-08-10.  Most attributes can have quotation
349                         # marks omitted, but not all.  (Although a literal " is not
350                         # permitted, we don't check for that, since it will be escaped
351                         # anyway.)
352                         #
353                         # See also research done on further characters that need to be
354                         # escaped: http://code.google.com/p/html5lib/issues/detail?id=93
355                         $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
356                                 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
357                                 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
358                         if ( $wgWellFormedXml || $value === ''
359                         || preg_match( "![$badChars]!u", $value ) ) {
360                                 $quote = '"';
361                         } else {
362                                 $quote = '';
363                         }
364
365                         if ( in_array( $key, self::$boolAttribs ) ) {
366                                 # In XHTML 1.0 Transitional, the value needs to be equal to the
367                                 # key.  In HTML5, we can leave the value empty instead.  If we
368                                 # don't need well-formed XML, we can omit the = entirely.
369                                 if ( !$wgWellFormedXml ) {
370                                         $ret .= " $key";
371                                 } elseif ( $wgHtml5 ) {
372                                         $ret .= " $key=\"\"";
373                                 } else {
374                                         $ret .= " $key=\"$key\"";
375                                 }
376                         } else {
377                                 # Apparently we need to entity-encode \n, \r, \t, although the
378                                 # spec doesn't mention that.  Since we're doing strtr() anyway,
379                                 # and we don't need <> escaped here, we may as well not call
380                                 # htmlspecialchars().  FIXME: verify that we actually need to
381                                 # escape \n\r\t here, and explain why, exactly.
382                                 #
383                                 # We could call Sanitizer::encodeAttribute() for this, but we
384                                 # don't because we're stubborn and like our marginal savings on
385                                 # byte size from not having to encode unnecessary quotes.
386                                 $map = array(
387                                         '&' => '&amp;',
388                                         '"' => '&quot;',
389                                         "\n" => '&#10;',
390                                         "\r" => '&#13;',
391                                         "\t" => '&#9;'
392                                 );
393                                 if ( $wgWellFormedXml ) {
394                                         # This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
395                                         # But reportedly it breaks some XML tools?  FIXME: is this
396                                         # really true?
397                                         $map['<'] = '&lt;';
398                                 }
399                                 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
400                         }
401                 }
402                 return $ret;
403         }
404
405         /**
406          * Output a <script> tag with the given contents.  TODO: do some useful
407          * escaping as well, like if $contents contains literal '</script>' or (for
408          * XML) literal "]]>".
409          *
410          * @param $contents string JavaScript
411          * @return string Raw HTML
412          */
413         public static function inlineScript( $contents ) {
414                 global $wgHtml5, $wgJsMimeType, $wgWellFormedXml;
415
416                 $attrs = array();
417                 if ( !$wgHtml5 ) {
418                         $attrs['type'] = $wgJsMimeType;
419                 }
420                 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
421                         $contents = "/*<![CDATA[*/$contents/*]]>*/";
422                 }
423                 return self::rawElement( 'script', $attrs, $contents );
424         }
425
426         /**
427          * Output a <script> tag linking to the given URL, e.g.,
428          * <script src=foo.js></script>.
429          *
430          * @param $url string
431          * @return string Raw HTML
432          */
433         public static function linkedScript( $url ) {
434                 global $wgHtml5, $wgJsMimeType;
435
436                 $attrs = array( 'src' => $url );
437                 if ( !$wgHtml5 ) {
438                         $attrs['type'] = $wgJsMimeType;
439                 }
440                 return self::element( 'script', $attrs );
441         }
442
443         /**
444          * Output a <style> tag with the given contents for the given media type
445          * (if any).  TODO: do some useful escaping as well, like if $contents
446          * contains literal '</style>' (admittedly unlikely).
447          *
448          * @param $contents string CSS
449          * @param $media mixed A media type string, like 'screen'
450          * @return string Raw HTML
451          */
452         public static function inlineStyle( $contents, $media = 'all' ) {
453                 global $wgWellFormedXml;
454
455                 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
456                         $contents = "/*<![CDATA[*/$contents/*]]>*/";
457                 }
458                 return self::rawElement( 'style', array(
459                         'type' => 'text/css',
460                         'media' => $media,
461                 ), $contents );
462         }
463
464         /**
465          * Output a <link rel=stylesheet> linking to the given URL for the given
466          * media type (if any).
467          *
468          * @param $url string
469          * @param $media mixed A media type string, like 'screen'
470          * @return string Raw HTML
471          */
472         public static function linkedStyle( $url, $media = 'all' ) {
473                 return self::element( 'link', array(
474                         'rel' => 'stylesheet',
475                         'href' => $url,
476                         'type' => 'text/css',
477                         'media' => $media,
478                 ) );
479         }
480
481         /**
482          * Convenience function to produce an <input> element.  This supports the
483          * new HTML5 input types and attributes, and will silently strip them if
484          * $wgHtml5 is false.
485          *
486          * @param $name    string name attribute
487          * @param $value   mixed  value attribute
488          * @param $type    string type attribute
489          * @param $attribs array  Associative array of miscellaneous extra
490          *   attributes, passed to Html::element()
491          * @return string Raw HTML
492          */
493         public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
494                 $attribs['type'] = $type;
495                 $attribs['value'] = $value;
496                 $attribs['name'] = $name;
497
498                 return self::element( 'input', $attribs );
499         }
500
501         /**
502          * Convenience function to produce an input element with type=hidden, like
503          * Xml::hidden.
504          *
505          * @param $name    string name attribute
506          * @param $value   string value attribute
507          * @param $attribs array  Associative array of miscellaneous extra
508          *   attributes, passed to Html::element()
509          * @return string Raw HTML
510          */
511         public static function hidden( $name, $value, $attribs = array() ) {
512                 return self::input( $name, $value, 'hidden', $attribs );
513         }
514
515         /**
516          * Convenience function to produce an <input> element.  This supports leaving
517          * out the cols= and rows= which Xml requires and are required by HTML4/XHTML
518          * but not required by HTML5 and will silently set cols="" and rows="" if
519          * $wgHtml5 is false and cols and rows are omitted (HTML4 validates present
520          * but empty cols="" and rows="" as valid).
521          *
522          * @param $name    string name attribute
523          * @param $value   string value attribute
524          * @param $attribs array  Associative array of miscellaneous extra
525          *   attributes, passed to Html::element()
526          * @return string Raw HTML
527          */
528         public static function textarea( $name, $value = '', $attribs = array() ) {
529                 global $wgHtml5;
530                 $attribs['name'] = $name;
531                 if ( !$wgHtml5 ) {
532                         if ( !isset( $attribs['cols'] ) )
533                                 $attribs['cols'] = "";
534                         if ( !isset( $attribs['rows'] ) )
535                                 $attribs['rows'] = "";
536                 }
537                 return self::element( 'textarea', $attribs, $value );
538         }
539 }