]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/Html.php
MediaWiki 1.17.0
[autoinstalls/mediawiki.git] / includes / Html.php
1 <?php
2 /**
3  * Collection of methods to generate HTML content
4  *
5  * Copyright © 2009 Aryeh Gregor
6  * http://www.mediawiki.org/
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  * http://www.gnu.org/copyleft/gpl.html
22  *
23  * @file
24  */
25
26 /**
27  * This class is a collection of static functions that serve two purposes:
28  *
29  * 1) Implement any algorithms specified by HTML5, or other HTML
30  * specifications, in a convenient and self-contained way.
31  *
32  * 2) Allow HTML elements to be conveniently and safely generated, like the
33  * current Xml class but a) less confused (Xml supports HTML-specific things,
34  * but only sometimes!) and b) not necessarily confined to XML-compatible
35  * output.
36  *
37  * There are two important configuration options this class uses:
38  *
39  * $wgHtml5: If this is set to false, then all output should be valid XHTML 1.0
40  *     Transitional.
41  * $wgWellFormedXml: If this is set to true, then all output should be
42  *     well-formed XML (quotes on attributes, self-closing tags, etc.).
43  *
44  * This class is meant to be confined to utility functions that are called from
45  * trusted code paths.  It does not do enforcement of policy like not allowing
46  * <a> elements.
47  *
48  * @since 1.16
49  */
50 class Html {
51         # List of void elements from HTML5, section 9.1.2 as of 2009-08-10
52         private static $voidElements = array(
53                 'area',
54                 'base',
55                 'br',
56                 'col',
57                 'command',
58                 'embed',
59                 'hr',
60                 'img',
61                 'input',
62                 'keygen',
63                 'link',
64                 'meta',
65                 'param',
66                 'source',
67         );
68
69         # Boolean attributes, which may have the value omitted entirely.  Manually
70         # collected from the HTML5 spec as of 2010-06-07.
71         private static $boolAttribs = array(
72                 'async',
73                 'autofocus',
74                 'autoplay',
75                 'checked',
76                 'controls',
77                 'defer',
78                 'disabled',
79                 'formnovalidate',
80                 'hidden',
81                 'ismap',
82                 'itemscope',
83                 'loop',
84                 'multiple',
85                 'novalidate',
86                 'open',
87                 'pubdate',
88                 'readonly',
89                 'required',
90                 'reversed',
91                 'scoped',
92                 'seamless',
93                 'selected',
94         );
95
96         /**
97          * Returns an HTML element in a string.  The major advantage here over
98          * manually typing out the HTML is that it will escape all attribute
99          * values.  If you're hardcoding all the attributes, or there are none, you
100          * should probably type out the string yourself.
101          *
102          * This is quite similar to Xml::tags(), but it implements some useful
103          * HTML-specific logic.  For instance, there is no $allowShortTag
104          * parameter: the closing tag is magically omitted if $element has an empty
105          * content model.  If $wgWellFormedXml is false, then a few bytes will be
106          * shaved off the HTML output as well.  In the future, other HTML-specific
107          * features might be added, like allowing arrays for the values of
108          * attributes like class= and media=.
109          *
110          * @param $element  string The element's name, e.g., 'a'
111          * @param $attribs  array  Associative array of attributes, e.g., array(
112          *   'href' => 'http://www.mediawiki.org/' ).  See expandAttributes() for
113          *   further documentation.
114          * @param $contents string The raw HTML contents of the element: *not*
115          *   escaped!
116          * @return string Raw HTML
117          */
118         public static function rawElement( $element, $attribs = array(), $contents = '' ) {
119                 global $wgWellFormedXml;
120                 $start = self::openElement( $element, $attribs );
121                 if ( in_array( $element, self::$voidElements ) ) {
122                         if ( $wgWellFormedXml ) {
123                                 # Silly XML.
124                                 return substr( $start, 0, -1 ) . ' />';
125                         }
126                         return $start;
127                 } else {
128                         return "$start$contents" . self::closeElement( $element );
129                 }
130         }
131
132         /**
133          * Identical to rawElement(), but HTML-escapes $contents (like
134          * Xml::element()).
135          */
136         public static function element( $element, $attribs = array(), $contents = '' ) {
137                 return self::rawElement( $element, $attribs, strtr( $contents, array(
138                         # There's no point in escaping quotes, >, etc. in the contents of
139                         # elements.
140                         '&' => '&amp;',
141                         '<' => '&lt;'
142                 ) ) );
143         }
144
145         /**
146          * Identical to rawElement(), but has no third parameter and omits the end
147          * tag (and the self-closing '/' in XML mode for empty elements).
148          */
149         public static function openElement( $element, $attribs = array() ) {
150                 global $wgHtml5, $wgWellFormedXml;
151                 $attribs = (array)$attribs;
152                 # This is not required in HTML5, but let's do it anyway, for
153                 # consistency and better compression.
154                 $element = strtolower( $element );
155
156                 # In text/html, initial <html> and <head> tags can be omitted under
157                 # pretty much any sane circumstances, if they have no attributes.  See:
158                 # <http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags>
159                 if ( !$wgWellFormedXml && !$attribs
160                 && in_array( $element, array( 'html', 'head' ) ) ) {
161                         return '';
162                 }
163
164                 # Remove HTML5-only attributes if we aren't doing HTML5, and disable
165                 # form validation regardless (see bug 23769 and the more detailed
166                 # comment in expandAttributes())
167                 if ( $element == 'input' ) {
168                         # Whitelist of types that don't cause validation.  All except
169                         # 'search' are valid in XHTML1.
170                         $validTypes = array(
171                                 'hidden',
172                                 'text',
173                                 'password',
174                                 'checkbox',
175                                 'radio',
176                                 'file',
177                                 'submit',
178                                 'image',
179                                 'reset',
180                                 'button',
181                                 'search',
182                         );
183                         if ( isset( $attribs['type'] )
184                         && !in_array( $attribs['type'], $validTypes ) ) {
185                                 unset( $attribs['type'] );
186                         }
187                         if ( isset( $attribs['type'] ) && $attribs['type'] == 'search'
188                         && !$wgHtml5 ) {
189                                 unset( $attribs['type'] );
190                         }
191                 }
192                 if ( !$wgHtml5 && $element == 'textarea' && isset( $attribs['maxlength'] ) ) {
193                         unset( $attribs['maxlength'] );
194                 }
195
196                 return "<$element" . self::expandAttributes(
197                         self::dropDefaults( $element, $attribs ) ) . '>';
198         }
199
200         /**
201          * Returns "</$element>", except if $wgWellFormedXml is off, in which case
202          * it returns the empty string when that's guaranteed to be safe.
203          *
204          * @param $element string Name of the element, e.g., 'a'
205          * @return string A closing tag, if required
206          */
207         public static function closeElement( $element ) {
208                 global $wgWellFormedXml;
209
210                 $element = strtolower( $element );
211
212                 # Reference:
213                 # http://www.whatwg.org/specs/web-apps/current-work/multipage/syntax.html#optional-tags
214                 if ( !$wgWellFormedXml && in_array( $element, array(
215                         'html',
216                         'head',
217                         'body',
218                         'li',
219                         'dt',
220                         'dd',
221                         'tr',
222                         'td',
223                         'th',
224                 ) ) ) {
225                         return '';
226                 }
227                 return "</$element>";
228         }
229
230         /**
231          * Given an element name and an associative array of element attributes,
232          * return an array that is functionally identical to the input array, but
233          * possibly smaller.  In particular, attributes might be stripped if they
234          * are given their default values.
235          *
236          * This method is not guaranteed to remove all redundant attributes, only
237          * some common ones and some others selected arbitrarily at random.  It
238          * only guarantees that the output array should be functionally identical
239          * to the input array (currently per the HTML 5 draft as of 2009-09-06).
240          *
241          * @param $element string Name of the element, e.g., 'a'
242          * @param $attribs array  Associative array of attributes, e.g., array(
243          *   'href' => 'http://www.mediawiki.org/' ).  See expandAttributes() for
244          *   further documentation.
245          * @return array An array of attributes functionally identical to $attribs
246          */
247         private static function dropDefaults( $element, $attribs ) {
248                 # Don't bother doing anything if we aren't outputting HTML5; it's too
249                 # much of a pain to maintain two sets of defaults.
250                 global $wgHtml5;
251                 if ( !$wgHtml5 ) {
252                         return $attribs;
253                 }
254
255                 static $attribDefaults = array(
256                         'area' => array( 'shape' => 'rect' ),
257                         'button' => array(
258                                 'formaction' => 'GET',
259                                 'formenctype' => 'application/x-www-form-urlencoded',
260                                 'type' => 'submit',
261                         ),
262                         'canvas' => array(
263                                 'height' => '150',
264                                 'width' => '300',
265                         ),
266                         'command' => array( 'type' => 'command' ),
267                         'form' => array(
268                                 'action' => 'GET',
269                                 'autocomplete' => 'on',
270                                 'enctype' => 'application/x-www-form-urlencoded',
271                         ),
272                         'input' => array(
273                                 'formaction' => 'GET',
274                                 'type' => 'text',
275                                 'value' => '',
276                         ),
277                         'keygen' => array( 'keytype' => 'rsa' ),
278                         'link' => array( 'media' => 'all' ),
279                         'menu' => array( 'type' => 'list' ),
280                         # Note: the use of text/javascript here instead of other JavaScript
281                         # MIME types follows the HTML5 spec.
282                         'script' => array( 'type' => 'text/javascript' ),
283                         'style' => array(
284                                 'media' => 'all',
285                                 'type' => 'text/css',
286                         ),
287                         'textarea' => array( 'wrap' => 'soft' ),
288                 );
289
290                 $element = strtolower( $element );
291
292                 foreach ( $attribs as $attrib => $value ) {
293                         $lcattrib = strtolower( $attrib );
294                         $value = strval( $value );
295
296                         # Simple checks using $attribDefaults
297                         if ( isset( $attribDefaults[$element][$lcattrib] ) &&
298                         $attribDefaults[$element][$lcattrib] == $value ) {
299                                 unset( $attribs[$attrib] );
300                         }
301
302                         if ( $lcattrib == 'class' && $value == '' ) {
303                                 unset( $attribs[$attrib] );
304                         }
305                 }
306
307                 # More subtle checks
308                 if ( $element === 'link' && isset( $attribs['type'] )
309                 && strval( $attribs['type'] ) == 'text/css' ) {
310                         unset( $attribs['type'] );
311                 }
312                 if ( $element === 'select' && isset( $attribs['size'] ) ) {
313                         if ( in_array( 'multiple', $attribs )
314                                 || ( isset( $attribs['multiple'] ) && $attribs['multiple'] !== false )
315                         ) {
316                                 # A multi-select
317                                 if ( strval( $attribs['size'] ) == '4' ) {
318                                         unset( $attribs['size'] );
319                                 }
320                         } else {
321                                 # Single select
322                                 if ( strval( $attribs['size'] ) == '1' ) {
323                                         unset( $attribs['size'] );
324                                 }
325                         }
326                 }
327
328                 return $attribs;
329         }
330
331         /**
332          * Given an associative array of element attributes, generate a string
333          * to stick after the element name in HTML output.  Like array( 'href' =>
334          * 'http://www.mediawiki.org/' ) becomes something like
335          * ' href="http://www.mediawiki.org"'.  Again, this is like
336          * Xml::expandAttributes(), but it implements some HTML-specific logic.
337          * For instance, it will omit quotation marks if $wgWellFormedXml is false,
338          * and will treat boolean attributes specially.
339          *
340          * @param $attribs array Associative array of attributes, e.g., array(
341          *   'href' => 'http://www.mediawiki.org/' ).  Values will be HTML-escaped.
342          *   A value of false means to omit the attribute.  For boolean attributes,
343          *   you can omit the key, e.g., array( 'checked' ) instead of
344          *   array( 'checked' => 'checked' ) or such.
345          * @return string HTML fragment that goes between element name and '>'
346          *   (starting with a space if at least one attribute is output)
347          */
348         public static function expandAttributes( $attribs ) {
349                 global $wgHtml5, $wgWellFormedXml;
350
351                 $ret = '';
352                 $attribs = (array)$attribs;
353                 foreach ( $attribs as $key => $value ) {
354                         if ( $value === false ) {
355                                 continue;
356                         }
357
358                         # For boolean attributes, support array( 'foo' ) instead of
359                         # requiring array( 'foo' => 'meaningless' ).
360                         if ( is_int( $key )
361                         && in_array( strtolower( $value ), self::$boolAttribs ) ) {
362                                 $key = $value;
363                         }
364
365                         # Not technically required in HTML5, but required in XHTML 1.0,
366                         # and we'd like consistency and better compression anyway.
367                         $key = strtolower( $key );
368
369                         # Bug 23769: Blacklist all form validation attributes for now.  Current
370                         # (June 2010) WebKit has no UI, so the form just refuses to submit
371                         # without telling the user why, which is much worse than failing
372                         # server-side validation.  Opera is the only other implementation at
373                         # this time, and has ugly UI, so just kill the feature entirely until
374                         # we have at least one good implementation.
375                         if ( in_array( $key, array( 'max', 'min', 'pattern', 'required', 'step' ) ) ) {
376                                 continue;
377                         }
378
379                         # Here we're blacklisting some HTML5-only attributes...
380                         if ( !$wgHtml5 && in_array( $key, array(
381                                         'autocomplete',
382                                         'autofocus',
383                                         'max',
384                                         'min',
385                                         'multiple',
386                                         'pattern',
387                                         'placeholder',
388                                         'required',
389                                         'step',
390                                         'spellcheck',
391                         ) ) ) {
392                                 continue;
393                         }
394
395                         # See the "Attributes" section in the HTML syntax part of HTML5,
396                         # 9.1.2.3 as of 2009-08-10.  Most attributes can have quotation
397                         # marks omitted, but not all.  (Although a literal " is not
398                         # permitted, we don't check for that, since it will be escaped
399                         # anyway.)
400                         #
401                         # See also research done on further characters that need to be
402                         # escaped: http://code.google.com/p/html5lib/issues/detail?id=93
403                         $badChars = "\\x00- '=<>`/\x{00a0}\x{1680}\x{180e}\x{180F}\x{2000}\x{2001}"
404                                 . "\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}"
405                                 . "\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}";
406                         if ( $wgWellFormedXml || $value === ''
407                         || preg_match( "![$badChars]!u", $value ) ) {
408                                 $quote = '"';
409                         } else {
410                                 $quote = '';
411                         }
412
413                         if ( in_array( $key, self::$boolAttribs ) ) {
414                                 # In XHTML 1.0 Transitional, the value needs to be equal to the
415                                 # key.  In HTML5, we can leave the value empty instead.  If we
416                                 # don't need well-formed XML, we can omit the = entirely.
417                                 if ( !$wgWellFormedXml ) {
418                                         $ret .= " $key";
419                                 } elseif ( $wgHtml5 ) {
420                                         $ret .= " $key=\"\"";
421                                 } else {
422                                         $ret .= " $key=\"$key\"";
423                                 }
424                         } else {
425                                 # Apparently we need to entity-encode \n, \r, \t, although the
426                                 # spec doesn't mention that.  Since we're doing strtr() anyway,
427                                 # and we don't need <> escaped here, we may as well not call
428                                 # htmlspecialchars().  FIXME: verify that we actually need to
429                                 # escape \n\r\t here, and explain why, exactly.
430                                 #
431                                 # We could call Sanitizer::encodeAttribute() for this, but we
432                                 # don't because we're stubborn and like our marginal savings on
433                                 # byte size from not having to encode unnecessary quotes.
434                                 $map = array(
435                                         '&' => '&amp;',
436                                         '"' => '&quot;',
437                                         "\n" => '&#10;',
438                                         "\r" => '&#13;',
439                                         "\t" => '&#9;'
440                                 );
441                                 if ( $wgWellFormedXml ) {
442                                         # This is allowed per spec: <http://www.w3.org/TR/xml/#NT-AttValue>
443                                         # But reportedly it breaks some XML tools?  FIXME: is this
444                                         # really true?
445                                         $map['<'] = '&lt;';
446                                 }
447                                 $ret .= " $key=$quote" . strtr( $value, $map ) . $quote;
448                         }
449                 }
450                 return $ret;
451         }
452
453         /**
454          * Output a <script> tag with the given contents.  TODO: do some useful
455          * escaping as well, like if $contents contains literal '</script>' or (for
456          * XML) literal "]]>".
457          *
458          * @param $contents string JavaScript
459          * @return string Raw HTML
460          */
461         public static function inlineScript( $contents ) {
462                 global $wgHtml5, $wgJsMimeType, $wgWellFormedXml;
463
464                 $attrs = array();
465                 if ( !$wgHtml5 ) {
466                         $attrs['type'] = $wgJsMimeType;
467                 }
468                 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
469                         $contents = "/*<![CDATA[*/$contents/*]]>*/";
470                 }
471                 return self::rawElement( 'script', $attrs, $contents );
472         }
473
474         /**
475          * Output a <script> tag linking to the given URL, e.g.,
476          * <script src=foo.js></script>.
477          *
478          * @param $url string
479          * @return string Raw HTML
480          */
481         public static function linkedScript( $url ) {
482                 global $wgHtml5, $wgJsMimeType;
483
484                 $attrs = array( 'src' => $url );
485                 if ( !$wgHtml5 ) {
486                         $attrs['type'] = $wgJsMimeType;
487                 }
488                 return self::element( 'script', $attrs );
489         }
490
491         /**
492          * Output a <style> tag with the given contents for the given media type
493          * (if any).  TODO: do some useful escaping as well, like if $contents
494          * contains literal '</style>' (admittedly unlikely).
495          *
496          * @param $contents string CSS
497          * @param $media mixed A media type string, like 'screen'
498          * @return string Raw HTML
499          */
500         public static function inlineStyle( $contents, $media = 'all' ) {
501                 global $wgWellFormedXml;
502
503                 if ( $wgWellFormedXml && preg_match( '/[<&]/', $contents ) ) {
504                         $contents = "/*<![CDATA[*/$contents/*]]>*/";
505                 }
506                 return self::rawElement( 'style', array(
507                         'type' => 'text/css',
508                         'media' => $media,
509                 ), $contents );
510         }
511
512         /**
513          * Output a <link rel=stylesheet> linking to the given URL for the given
514          * media type (if any).
515          *
516          * @param $url string
517          * @param $media mixed A media type string, like 'screen'
518          * @return string Raw HTML
519          */
520         public static function linkedStyle( $url, $media = 'all' ) {
521                 return self::element( 'link', array(
522                         'rel' => 'stylesheet',
523                         'href' => $url,
524                         'type' => 'text/css',
525                         'media' => $media,
526                 ) );
527         }
528
529         /**
530          * Convenience function to produce an <input> element.  This supports the
531          * new HTML5 input types and attributes, and will silently strip them if
532          * $wgHtml5 is false.
533          *
534          * @param $name    string name attribute
535          * @param $value   mixed  value attribute
536          * @param $type    string type attribute
537          * @param $attribs array  Associative array of miscellaneous extra
538          *   attributes, passed to Html::element()
539          * @return string Raw HTML
540          */
541         public static function input( $name, $value = '', $type = 'text', $attribs = array() ) {
542                 $attribs['type'] = $type;
543                 $attribs['value'] = $value;
544                 $attribs['name'] = $name;
545
546                 return self::element( 'input', $attribs );
547         }
548
549         /**
550          * Convenience function to produce an input element with type=hidden
551          *
552          * @param $name    string name attribute
553          * @param $value   string value attribute
554          * @param $attribs array  Associative array of miscellaneous extra
555          *   attributes, passed to Html::element()
556          * @return string Raw HTML
557          */
558         public static function hidden( $name, $value, $attribs = array() ) {
559                 return self::input( $name, $value, 'hidden', $attribs );
560         }
561
562         /**
563          * Convenience function to produce an <input> element.  This supports leaving
564          * out the cols= and rows= which Xml requires and are required by HTML4/XHTML
565          * but not required by HTML5 and will silently set cols="" and rows="" if
566          * $wgHtml5 is false and cols and rows are omitted (HTML4 validates present
567          * but empty cols="" and rows="" as valid).
568          *
569          * @param $name    string name attribute
570          * @param $value   string value attribute
571          * @param $attribs array  Associative array of miscellaneous extra
572          *   attributes, passed to Html::element()
573          * @return string Raw HTML
574          */
575         public static function textarea( $name, $value = '', $attribs = array() ) {
576                 global $wgHtml5;
577                 $attribs['name'] = $name;
578                 if ( !$wgHtml5 ) {
579                         if ( !isset( $attribs['cols'] ) ) {
580                                 $attribs['cols'] = "";
581                         }
582                         if ( !isset( $attribs['rows'] ) ) {
583                                 $attribs['rows'] = "";
584                         }
585                 }
586                 return self::element( 'textarea', $attribs, $value );
587         }
588
589         /**
590          * Constructs the opening html-tag with necessary doctypes depending on
591          * global variables.
592          *
593          * @param $attribs array  Associative array of miscellaneous extra
594          *   attributes, passed to Html::element() of html tag.
595          * @return string  Raw HTML
596          */
597         public static function htmlHeader( $attribs = array() ) {
598                 $ret = '';
599
600                 global $wgMimeType, $wgOutputEncoding;
601                 if ( self::isXmlMimeType( $wgMimeType ) ) {
602                         $ret .= "<?xml version=\"1.0\" encoding=\"$wgOutputEncoding\" ?" . ">\n";
603                 }
604
605                 global $wgHtml5, $wgHtml5Version, $wgDocType, $wgDTD;
606                 global $wgXhtmlNamespaces, $wgXhtmlDefaultNamespace;
607                 if ( $wgHtml5 ) {
608                         $ret .= "<!DOCTYPE html>\n";
609                         if ( $wgHtml5Version ) {
610                                 $attribs['version'] = $wgHtml5Version;
611                         }
612                 } else {
613                         $ret .= "<!DOCTYPE html PUBLIC \"$wgDocType\" \"$wgDTD\">\n";
614                         $attribs['xmlns'] = $wgXhtmlDefaultNamespace;
615                         foreach ( $wgXhtmlNamespaces as $tag => $ns ) {
616                                 $attribs["xmlns:$tag"] = $ns;
617                         }
618                 }
619                 $html = Html::openElement( 'html', $attribs );
620                 if ( $html ) {
621                         $html .= "\n";
622                 }
623                 $ret .= $html;
624                 return $ret;
625         }
626
627         /**
628          * Determines if the given mime type is xml.
629          *
630          * @param $mimetype    string MimeType
631          * @return Boolean
632          */
633         public static function isXmlMimeType( $mimetype ) {
634                 switch ( $mimetype ) {
635                         case 'text/xml':
636                         case 'application/xhtml+xml':
637                         case 'application/xml':
638                                 return true;
639                         default:
640                                 return false;
641                 }
642         }
643 }