]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blobdiff - includes/Sanitizer.php
MediaWiki 1.16.3
[autoinstallsdev/mediawiki.git] / includes / Sanitizer.php
index 3816b9de03c72f31ab12fec48b1fc496dccd44fe..26837b3c3fc30214e926f4353e39433a48907f1f 100644 (file)
@@ -1,13 +1,13 @@
 <?php
 /**
- * (X)HTML sanitizer for MediaWiki
+ * XHTML sanitizer for MediaWiki
  *
  * Copyright (C) 2002-2005 Brion Vibber <brion@pobox.com> et al
  * http://www.mediawiki.org/
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or 
+ * the Free Software Foundation; either version 2 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  *
  * You should have received a copy of the GNU General Public License along
  * with this program; if not, write to the Free Software Foundation, Inc.,
- * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  * http://www.gnu.org/copyleft/gpl.html
  *
- * @package MediaWiki
- * @subpackage Parser
+ * @file
+ * @ingroup Parser
  */
 
 /**
@@ -29,7 +29,7 @@
  * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
  */
 define( 'MW_CHAR_REFS_REGEX',
-       '/&([A-Za-z0-9]+);
+       '/&([A-Za-z0-9\x80-\xff]+);
         |&\#([0-9]+);
         |&\#x([0-9A-Za-z]+);
         |&\#X([0-9A-Za-z]+);
@@ -40,10 +40,10 @@ define( 'MW_CHAR_REFS_REGEX',
  * Allows some... latitude.
  * Used in Sanitizer::fixTagAttributes and Sanitizer::decodeTagAttributes
  */
-$attrib = '[A-Za-z0-9]'; 
+$attrib = '[A-Za-z0-9]';
 $space = '[\x09\x0a\x0d\x20]';
 define( 'MW_ATTRIBS_REGEX',
-       "/(?:^|$space)($attrib+)
+       "/(?:^|$space)((?:xml:|xmlns:)?$attrib+)
          ($space*=$space*
                (?:
                 # The attribute value: quoted or alone
@@ -56,10 +56,20 @@ define( 'MW_ATTRIBS_REGEX',
                )
           )?(?=$space|\$)/sx" );
 
+/**
+ * Regular expression to match URIs that could trigger script execution
+ */
+define( 'MW_EVIL_URI_PATTERN', '!(^|\s|\*/\s*)(javascript|vbscript)([^\w]|$)!i' );
+
+/**
+ * Regular expression to match namespace attributes
+ */
+define( 'MW_XMLNS_ATTRIBUTE_PATTRN', "/^xmlns:$attrib+$/" );
+
 /**
  * List of all named character entities defined in HTML 4.01
  * http://www.w3.org/TR/html4/sgml/entities.html
- * @access private
+ * @private
  */
 global $wgHtmlEntities;
 $wgHtmlEntities = array(
@@ -316,29 +326,48 @@ $wgHtmlEntities = array(
        'zwj'      => 8205,
        'zwnj'     => 8204 );
 
-/** @package MediaWiki */
+/**
+ * Character entity aliases accepted by MediaWiki
+ */
+global $wgHtmlEntityAliases;
+$wgHtmlEntityAliases = array(
+       'רלמ' => 'rlm',
+       'رلم' => 'rlm',
+);
+
+
+/**
+ * XHTML sanitizer for MediaWiki
+ * @ingroup Parser
+ */
 class Sanitizer {
        /**
         * Cleans up HTML, removes dangerous tags and attributes, and
         * removes HTML comments
-        * @access private
-        * @param string $text
-        * @param callback $processCallback to do any variable or parameter replacements in HTML attribute values
-        * @param array $args for the processing callback
+        * @private
+        * @param $text String
+        * @param $processCallback Callback to do any variable or parameter replacements in HTML attribute values
+        * @param $args Array for the processing callback
+        * @param $extratags Array for any extra tags to include
+        * @param $removetags Array for any tags (default or extra) to exclude
         * @return string
         */
-       function removeHTMLtags( $text, $processCallback = null, $args = array() ) {
-               global $wgUseTidy, $wgUserHtml;
-               $fname = 'Parser::removeHTMLtags';
-               wfProfileIn( $fname );
+       static function removeHTMLtags( $text, $processCallback = null, $args = array(), $extratags = array(), $removetags = array() ) {
+               global $wgUseTidy;
+
+               static $htmlpairsStatic, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
+                       $htmllist, $listtags, $htmlsingleallowed, $htmlelementsStatic, $staticInitialised;
+
+               wfProfileIn( __METHOD__ );
 
-               if( $wgUserHtml ) {
-                       $htmlpairs = array( # Tags that must be closed
+               if ( !$staticInitialised ) {
+
+                       $htmlpairsStatic = array( # Tags that must be closed
                                'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
                                'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
                                'strike', 'strong', 'tt', 'var', 'div', 'center',
                                'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
-                               'ruby', 'rt' , 'rb' , 'rp', 'p', 'span'
+                               'ruby', 'rt' , 'rb' , 'rp', 'p', 'span', 'u', 'abbr'
                        );
                        $htmlsingle = array(
                                'br', 'hr', 'li', 'dt', 'dd'
@@ -350,62 +379,114 @@ class Sanitizer {
                                'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
                                'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
                        );
-                       $tabletags = array( # Can only appear inside table
-                               'td', 'th', 'tr'
+                       $tabletags = array( # Can only appear inside table, we will close them
+                               'td', 'th', 'tr',
+                       );
+                       $htmllist = array( # Tags used by list
+                               'ul','ol',
+                       );
+                       $listtags = array( # Tags that can appear in a list
+                               'li',
                        );
-               } else {
-                       $htmlpairs = array();
-                       $htmlsingle = array();
-                       $htmlnest = array();
-                       $tabletags = array();
-               }
 
-               $htmlsingle = array_merge( $tabletags, $htmlsingle );
-               $htmlelements = array_merge( $htmlsingle, $htmlpairs );
+                       $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
+                       $htmlelementsStatic = array_unique( array_merge( $htmlsingle, $htmlpairsStatic, $htmlnest ) );
+
+                       # Convert them all to hashtables for faster lookup
+                       $vars = array( 'htmlpairsStatic', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
+                               'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelementsStatic' );
+                       foreach ( $vars as $var ) {
+                               $$var = array_flip( $$var );
+                       }
+                       $staticInitialised = true;
+               }
+               # Populate $htmlpairs and $htmlelements with the $extratags and $removetags arrays
+               $extratags = array_flip( $extratags );
+               $removetags = array_flip( $removetags );
+               $htmlpairs = array_merge( $extratags, $htmlpairsStatic );
+               $htmlelements = array_diff_key( array_merge( $extratags, $htmlelementsStatic ) , $removetags );
 
                # Remove HTML comments
                $text = Sanitizer::removeHTMLcomments( $text );
-
                $bits = explode( '<', $text );
-               $text = array_shift( $bits );
-               if(!$wgUseTidy) {
-                       $tagstack = array(); $tablestack = array();
+               $text = str_replace( '>', '&gt;', array_shift( $bits ) );
+               if ( !$wgUseTidy ) {
+                       $tagstack = $tablestack = array();
                        foreach ( $bits as $x ) {
-                               $prev = error_reporting( E_ALL & ~( E_NOTICE | E_WARNING ) );
-                               preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
-                               $x, $regs );
-                               list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
-                               error_reporting( $prev );
+                               $regs = array();
+                               # $slash: Does the current element start with a '/'?
+                               # $t: Current element name
+                               # $params: String between element name and >
+                               # $brace: Ending '>' or '/>'
+                               # $rest: Everything until the next element of $bits
+                               if( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
+                                       list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
+                               } else {
+                                       $slash = $t = $params = $brace = $rest = null;
+                               }
 
-                               $badtag = ;
-                               if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
+                               $badtag = false;
+                               if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
                                        # Check our stack
-                                       if ( $slash ) {
-                                               # Closing a tag...
-                                               if( in_array( $t, $htmlsingleonly ) ) {
-                                                       $badtag = 1;
-                                               } elseif( !in_array( $t, $htmlsingle ) &&
-                                               ( $ot = @array_pop( $tagstack ) ) != $t ) {
-                                                       @array_push( $tagstack, $ot );
-                                                       $badtag = 1;
+                                       if ( $slash && isset( $htmlsingleonly[$t] ) ) {
+                                               $badtag = true;
+                                       } elseif ( $slash ) {
+                                               # Closing a tag... is it the one we just opened?
+                                               $ot = @array_pop( $tagstack );
+                                               if ( $ot != $t ) {
+                                                       if ( isset( $htmlsingleallowed[$ot] ) ) {
+                                                               # Pop all elements with an optional close tag
+                                                               # and see if we find a match below them
+                                                               $optstack = array();
+                                                               array_push( $optstack, $ot );
+                                                               $ot = @array_pop( $tagstack );
+                                                               while ( $ot != $t && isset( $htmlsingleallowed[$ot] ) ) {
+                                                                       array_push( $optstack, $ot );
+                                                                       $ot = @array_pop( $tagstack );
+                                                               }
+                                                               if ( $t != $ot ) {
+                                                                       # No match. Push the optional elements back again
+                                                                       $badtag = true;
+                                                                       while ( $ot = @array_pop( $optstack ) ) {
+                                                                               array_push( $tagstack, $ot );
+                                                                       }
+                                                               }
+                                                       } else {
+                                                               @array_push( $tagstack, $ot );
+                                                               # <li> can be nested in <ul> or <ol>, skip those cases:
+                                                               if ( !isset( $htmllist[$ot] ) || !isset( $listtags[$t] ) ) {
+                                                                       $badtag = true;
+                                                               }
+                                                       }
                                                } else {
                                                        if ( $t == 'table' ) {
                                                                $tagstack = array_pop( $tablestack );
                                                        }
-                                                       $newparams = '';
                                                }
+                                               $newparams = '';
                                        } else {
                                                # Keep track for later
-                                               if ( in_array( $t, $tabletags ) &&
-                                               ! in_array( 'table', $tagstack ) ) {
-                                                       $badtag = 1;
-                                               } else if ( in_array( $t, $tagstack ) &&
-                                               ! in_array ( $t , $htmlnest ) ) {
-                                                       $badtag = 1 ;
-                                               } elseif( in_array( $t, $htmlsingleonly ) ) {
+                                               if ( isset( $tabletags[$t] ) &&
+                                               !in_array( 'table', $tagstack ) ) {
+                                                       $badtag = true;
+                                               } elseif ( in_array( $t, $tagstack ) &&
+                                               !isset( $htmlnest [$t ] ) ) {
+                                                       $badtag = true;
+                                               # Is it a self closed htmlpair ? (bug 5487)
+                                               } elseif ( $brace == '/>' &&
+                                               isset( $htmlpairs[$t] ) ) {
+                                                       $badtag = true;
+                                               } elseif ( isset( $htmlsingleonly[$t] ) ) {
                                                        # Hack to force empty tag for uncloseable elements
                                                        $brace = '/>';
-                                               } else if ( ! in_array( $t, $htmlsingle ) ) {
+                                               } elseif ( isset( $htmlsingle[$t] ) ) {
+                                                       # Hack to not close $htmlsingle tags
+                                                       $brace = null;
+                                               } elseif ( isset( $tabletags[$t] )
+                                               && in_array( $t, $tagstack ) ) {
+                                                       // New table tag but forgot to close the previous one
+                                                       $text .= "</$t>";
+                                               } else {
                                                        if ( $t == 'table' ) {
                                                                array_push( $tablestack, $tagstack );
                                                                $tagstack = array();
@@ -422,9 +503,9 @@ class Sanitizer {
                                                # Strip non-approved attributes from the tag
                                                $newparams = Sanitizer::fixTagAttributes( $params, $t );
                                        }
-                                       if ( ! $badtag ) {
+                                       if ( !$badtag ) {
                                                $rest = str_replace( '>', '&gt;', $rest );
-                                               $close = ( $brace == '/>' ) ? ' /' : '';
+                                               $close = ( $brace == '/>' && !$slash ) ? ' /' : '';
                                                $text .= "<$slash$t$newparams$close>$rest";
                                                continue;
                                        }
@@ -441,8 +522,8 @@ class Sanitizer {
                        foreach ( $bits as $x ) {
                                preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
                                $x, $regs );
-                               @list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
-                               if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
+                               @list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
+                               if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
                                        if( is_callable( $processCallback ) ) {
                                                call_user_func_array( $processCallback, array( &$params, $args ) );
                                        }
@@ -454,7 +535,7 @@ class Sanitizer {
                                }
                        }
                }
-               wfProfileOut( $fname );
+               wfProfileOut( __METHOD__ );
                return $text;
        }
 
@@ -463,14 +544,13 @@ class Sanitizer {
         * To avoid leaving blank lines, when a comment is both preceded
         * and followed by a newline (ignoring spaces), trim leading and
         * trailing spaces and one of the newlines.
-        * 
-        * @access private
-        * @param string $text
+        *
+        * @private
+        * @param $text String
         * @return string
         */
-       function removeHTMLcomments( $text ) {
-               $fname='Parser::removeHTMLcomments';
-               wfProfileIn( $fname );
+       static function removeHTMLcomments( $text ) {
+               wfProfileIn( __METHOD__ );
                while (($start = strpos($text, '<!--')) !== false) {
                        $end = strpos($text, '-->', $start + 4);
                        if ($end === false) {
@@ -500,131 +580,452 @@ class Sanitizer {
                                $text = substr_replace($text, '', $start, $end - $start);
                        }
                }
-               wfProfileOut( $fname );
+               wfProfileOut( __METHOD__ );
                return $text;
        }
 
        /**
-        * Take a tag soup fragment listing an HTML element's attributes
-        * and normalize it to well-formed XML, discarding unwanted attributes.
+        * Take an array of attribute names and values and normalize or discard
+        * illegal values for the given element type.
         *
-        * - Normalizes attribute names to lowercase
         * - Discards attributes not on a whitelist for the given element
-        * - Turns broken or invalid entities into plaintext
-        * - Double-quotes all attribute values
-        * - Attributes without values are given the name as attribute
-        * - Double attributes are discarded
         * - Unsafe style attributes are discarded
-        * - Prepends space if there are attributes.
+        * - Invalid id attributes are reencoded
         *
-        * @param string $text
-        * @param string $element
-        * @return string
+        * @param $attribs Array
+        * @param $element String
+        * @return Array
         *
         * @todo Check for legal values where the DTD limits things.
         * @todo Check for unique id attribute :P
         */
-       function fixTagAttributes( $text, $element ) {
-               global $wgUrlProtocols;
-               if( trim( $text ) == '' ) {
-                       return '';
-               }
-               
-               # Unquoted attribute
-               # Since we quote this later, this can be anything distinguishable 
-               # from the end of the attribute
-               if( !preg_match_all(
-                       MW_ATTRIBS_REGEX,
-                       $text,
-                       $pairs,
-                       PREG_SET_ORDER ) ) {
-                       return '';
-               }
+       static function validateTagAttributes( $attribs, $element ) {
+               return Sanitizer::validateAttributes( $attribs,
+                       Sanitizer::attributeWhitelist( $element ) );
+       }
+
+       /**
+        * Take an array of attribute names and values and normalize or discard
+        * illegal values for the given whitelist.
+        *
+        * - Discards attributes not the given whitelist
+        * - Unsafe style attributes are discarded
+        * - Invalid id attributes are reencoded
+        *
+        * @param $attribs Array
+        * @param $whitelist Array: list of allowed attribute names
+        * @return Array
+        *
+        * @todo Check for legal values where the DTD limits things.
+        * @todo Check for unique id attribute :P
+        */
+       static function validateAttributes( $attribs, $whitelist ) {
+               global $wgAllowRdfaAttributes, $wgAllowMicrodataAttributes;
+
+               $whitelist = array_flip( $whitelist );
+               $hrefExp = '/^(' . wfUrlProtocols() . ')[^\s]+$/';
+
+               $out = array();
+               foreach( $attribs as $attribute => $value ) {
+                       #allow XML namespace declaration if RDFa is enabled
+                       if ( $wgAllowRdfaAttributes && preg_match( MW_XMLNS_ATTRIBUTE_PATTRN, $attribute ) ) {
+                               if ( !preg_match( MW_EVIL_URI_PATTERN, $value ) ) {
+                                       $out[$attribute] = $value;
+                               }
+
+                               continue;
+                       }
 
-               $whitelist = array_flip( Sanitizer::attributeWhitelist( $element ) );
-               $attribs = array();
-               foreach( $pairs as $set ) {
-                       $attribute = strtolower( $set[1] );
                        if( !isset( $whitelist[$attribute] ) ) {
                                continue;
                        }
-                       
-                       $raw   = Sanitizer::getTagAttributeCallback( $set );
-                       $value = Sanitizer::normalizeAttributeValue( $raw );
-                       
+
                        # Strip javascript "expression" from stylesheets.
                        # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
                        if( $attribute == 'style' ) {
-                               $stripped = Sanitizer::decodeCharReferences( $value );
-                               
-                               // Remove any comments; IE gets token splitting wrong
-                               $stripped = preg_replace( '!/\\*.*?\\*/!S', ' ', $stripped );
-                               $value = htmlspecialchars( $stripped );
-                               
-                               // ... and continue checks
-                               $stripped = preg_replace( '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!e',
-                                       'codepointToUtf8(hexdec("$1"))', $stripped );
-                               $stripped = str_replace( '\\', '', $stripped );
-                               if( preg_match( '/(expression|tps*:\/\/|url\\s*\().*/is',
-                                               $stripped ) ) {
-                                       # haxx0r
-                                       continue;
+                               $value = Sanitizer::checkCss( $value );
+                       }
+
+                       if ( $attribute === 'id' ) {
+                               $value = Sanitizer::escapeId( $value, 'noninitial' );
+                       }
+
+                       //RDFa and microdata properties allow URLs, URIs and/or CURIs. check them for sanity
+                       if ( $attribute === 'rel' || $attribute === 'rev' || 
+                               $attribute === 'about' || $attribute === 'property' || $attribute === 'resource' || #RDFa
+                               $attribute === 'datatype' || $attribute === 'typeof' ||                             #RDFa
+                               $attribute === 'itemid' || $attribute === 'itemprop' || $attribute === 'itemref' || #HTML5 microdata
+                               $attribute === 'itemscope' || $attribute === 'itemtype' ) {                         #HTML5 microdata
+
+                               //Paranoia. Allow "simple" values but suppress javascript
+                               if ( preg_match( MW_EVIL_URI_PATTERN, $value ) ) {
+                                       continue; 
                                }
                        }
-                       
-                       # Templates and links may be expanded in later parsing,
-                       # creating invalid or dangerous output. Suppress this.
-                       $value = strtr( $value, array(
-                               '{'    => '&#123;',
-                               '['    => '&#91;',
-                               "''"   => '&#39;&#39;',
-                               'ISBN' => '&#73;SBN',
-                               'RFC'  => '&#82;FC',
-                               'PMID' => '&#80;MID',
-                       ) );
-                       
-                       # Stupid hack
-                       $value = preg_replace_callback(
-                               '/(' . $wgUrlProtocols . ')/',
-                               array( 'Sanitizer', 'armorLinksCallback' ),
-                               $value );
-                       
+
+                       # NOTE: even though elements using href/src are not allowed directly, supply
+                       #       validation code that can be used by tag hook handlers, etc
+                       if ( $attribute === 'href' || $attribute === 'src' ) {
+                               if ( !preg_match( $hrefExp, $value ) ) {
+                                       continue; //drop any href or src attributes not using an allowed protocol.
+                                                 //NOTE: this also drops all relative URLs
+                               }
+                       }
+
                        // If this attribute was previously set, override it.
                        // Output should only have one attribute of each name.
-                       $attribs[$attribute] = "$attribute=\"$value\"";
+                       $out[$attribute] = $value;
+               }
+
+               if ( $wgAllowMicrodataAttributes ) {
+                       # There are some complicated validity constraints we need to
+                       # enforce here.  First of all, we don't want to allow non-standard
+                       # itemtypes.
+                       $allowedTypes = array(
+                               'http://microformats.org/profile/hcard',
+                               'http://microformats.org/profile/hcalendar#vevent',
+                               'http://n.whatwg.org/work',
+                       );
+                       if ( isset( $out['itemtype'] ) && !in_array( $out['itemtype'],
+                       $allowedTypes ) ) {
+                               # Kill everything
+                               unset( $out['itemscope'] );
+                       }
+                       # itemtype, itemid, itemref don't make sense without itemscope
+                       if ( !array_key_exists( 'itemscope', $out ) ) {
+                               unset( $out['itemtype'] );
+                               unset( $out['itemid'] );
+                               unset( $out['itemref'] );
+                       }
+                       # TODO: Strip itemprop if we aren't descendants of an itemscope.
+               }
+               return $out;
+       }
+
+       /**
+        * Merge two sets of HTML attributes.  Conflicting items in the second set
+        * will override those in the first, except for 'class' attributes which
+        * will be combined (if they're both strings).
+        *
+        * @todo implement merging for other attributes such as style
+        * @param $a Array
+        * @param $b Array
+        * @return array
+        */
+       static function mergeAttributes( $a, $b ) {
+               $out = array_merge( $a, $b );
+               if( isset( $a['class'] ) && isset( $b['class'] )
+               && is_string( $a['class'] ) && is_string( $b['class'] )
+               && $a['class'] !== $b['class'] ) {
+                       $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
+                               -1, PREG_SPLIT_NO_EMPTY );
+                       $out['class'] = implode( ' ', array_unique( $classes ) );
+               }
+               return $out;
+       }
+
+       /**
+        * Pick apart some CSS and check it for forbidden or unsafe structures.
+        * Returns a sanitized string. This sanitized string will have
+        * character references and escape sequences decoded, and comments
+        * stripped. If the input is just too evil, only a comment complaining
+        * about evilness will be returned.
+        *
+        * Currently URL references, 'expression', 'tps' are forbidden.
+        *
+        * NOTE: Despite the fact that character references are decoded, the
+        * returned string may contain character references given certain
+        * clever input strings. These character references must
+        * be escaped before the return value is embedded in HTML.
+        * 
+        * @param $value String
+        * @return String
+        */
+       static function checkCss( $value ) {
+               // Decode character references like &#123;
+               $value = Sanitizer::decodeCharReferences( $value );
+
+               // Decode escape sequences and line continuation
+               // See the grammar in the CSS 2 spec, appendix D.
+               // This has to be done AFTER decoding character references.
+               // This means it isn't possible for this function to return
+               // unsanitized escape sequences. It is possible to manufacture
+               // input that contains character references that decode to
+               // escape sequences that decode to character references, but
+               // it's OK for the return value to contain character references
+               // because the caller is supposed to escape those anyway.
+               static $decodeRegex;
+               if ( !$decodeRegex ) {
+                       $space = '[\\x20\\t\\r\\n\\f]';
+                       $nl = '(?:\\n|\\r\\n|\\r|\\f)';
+                       $backslash = '\\\\';
+                       $decodeRegex = "/ $backslash 
+                               (?:
+                                       ($nl) |  # 1. Line continuation
+                                       ([0-9A-Fa-f]{1,6})$space? |  # 2. character number
+                                       (.) | # 3. backslash cancelling special meaning
+                                       () | # 4. backslash at end of string
+                               )/xu";
+               }
+               $value = preg_replace_callback( $decodeRegex,
+                       array( __CLASS__, 'cssDecodeCallback' ), $value );
+               
+               // Remove any comments; IE gets token splitting wrong
+               // This must be done AFTER decoding character references and
+               // escape sequences, because those steps can introduce comments
+               // This step cannot introduce character references or escape
+               // sequences, because it replaces comments with spaces rather
+               // than removing them completely.
+               $value = StringUtils::delimiterReplace( '/*', '*/', ' ', $value );
+
+               // Remove anything after a comment-start token, to guard against
+               // incorrect client implementations.
+               $commentPos = strpos( $value, '/*' );
+               if ( $commentPos !== false ) {
+                       $value = substr( $value, 0, $commentPos );
+               }
+
+               // Reject problematic keywords and control characters
+               if ( preg_match( '/[\000-\010\016-\037\177]/', $value ) ) {
+                       return '/* invalid control char */';
+               } elseif ( preg_match( '! expression | filter\s*: | accelerator\s*: | url\s*\( !ix', $value ) ) {
+                       return '/* insecure input */';
                }
-               if( empty( $attribs ) ) {
+               return $value;
+       }
+
+       static function cssDecodeCallback( $matches ) {
+               if ( $matches[1] !== '' ) {
+                       // Line continuation
                        return '';
+               } elseif ( $matches[2] !== '' ) {
+                       $char = codepointToUtf8( hexdec( $matches[2] ) );
+               } elseif ( $matches[3] !== '' ) {
+                       $char = $matches[3];
+               } else {
+                       $char = '\\';
+               }
+               if ( $char == "\n" || $char == '"' || $char == "'" || $char == '\\' ) {
+                       // These characters need to be escaped in strings
+                       // Clean up the escape sequence to avoid parsing errors by clients
+                       return '\\' . dechex( ord( $char ) ) . ' ';
                } else {
-                       return ' ' . implode( ' ', $attribs );
+                       // Decode unnecessary escape
+                       return $char;
                }
        }
-       
+
+       /**
+        * Take a tag soup fragment listing an HTML element's attributes
+        * and normalize it to well-formed XML, discarding unwanted attributes.
+        * Output is safe for further wikitext processing, with escaping of
+        * values that could trigger problems.
+        *
+        * - Normalizes attribute names to lowercase
+        * - Discards attributes not on a whitelist for the given element
+        * - Turns broken or invalid entities into plaintext
+        * - Double-quotes all attribute values
+        * - Attributes without values are given the name as attribute
+        * - Double attributes are discarded
+        * - Unsafe style attributes are discarded
+        * - Prepends space if there are attributes.
+        *
+        * @param $text String
+        * @param $element String
+        * @return String
+        */
+       static function fixTagAttributes( $text, $element ) {
+               if( trim( $text ) == '' ) {
+                       return '';
+               }
+
+               $stripped = Sanitizer::validateTagAttributes(
+                       Sanitizer::decodeTagAttributes( $text ), $element );
+
+               $attribs = array();
+               foreach( $stripped as $attribute => $value ) {
+                       $encAttribute = htmlspecialchars( $attribute );
+                       $encValue = Sanitizer::safeEncodeAttribute( $value );
+
+                       $attribs[] = "$encAttribute=\"$encValue\"";
+               }
+               return count( $attribs ) ? ' ' . implode( ' ', $attribs ) : '';
+       }
+
+       /**
+        * Encode an attribute value for HTML output.
+        * @param $text String
+        * @return HTML-encoded text fragment
+        */
+       static function encodeAttribute( $text ) {
+               $encValue = htmlspecialchars( $text, ENT_QUOTES );
+
+               // Whitespace is normalized during attribute decoding,
+               // so if we've been passed non-spaces we must encode them
+               // ahead of time or they won't be preserved.
+               $encValue = strtr( $encValue, array(
+                       "\n" => '&#10;',
+                       "\r" => '&#13;',
+                       "\t" => '&#9;',
+               ) );
+
+               return $encValue;
+       }
+
+       /**
+        * Encode an attribute value for HTML tags, with extra armoring
+        * against further wiki processing.
+        * @param $text String
+        * @return HTML-encoded text fragment
+        */
+       static function safeEncodeAttribute( $text ) {
+               $encValue = Sanitizer::encodeAttribute( $text );
+
+               # Templates and links may be expanded in later parsing,
+               # creating invalid or dangerous output. Suppress this.
+               $encValue = strtr( $encValue, array(
+                       '<'    => '&lt;',   // This should never happen,
+                       '>'    => '&gt;',   // we've received invalid input
+                       '"'    => '&quot;', // which should have been escaped.
+                       '{'    => '&#123;',
+                       '['    => '&#91;',
+                       "''"   => '&#39;&#39;',
+                       'ISBN' => '&#73;SBN',
+                       'RFC'  => '&#82;FC',
+                       'PMID' => '&#80;MID',
+                       '|'    => '&#124;',
+                       '__'   => '&#95;_',
+               ) );
+
+               # Stupid hack
+               $encValue = preg_replace_callback(
+                       '/(' . wfUrlProtocols() . ')/',
+                       array( 'Sanitizer', 'armorLinksCallback' ),
+                       $encValue );
+               return $encValue;
+       }
+
+       /**
+        * Given a value, escape it so that it can be used in an id attribute and
+        * return it.  This will use HTML5 validation if $wgExperimentalHtmlIds is
+        * true, allowing anything but ASCII whitespace.  Otherwise it will use
+        * HTML 4 rules, which means a narrow subset of ASCII, with bad characters
+        * escaped with lots of dots.
+        *
+        * To ensure we don't have to bother escaping anything, we also strip ', ",
+        * & even if $wgExperimentalIds is true.  TODO: Is this the best tactic?
+        * We also strip # because it upsets IE6.
+        *
+        * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
+        *                                                          in the id and
+        *                                                          name attributes
+        * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
+        * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#the-id-attribute
+        *   HTML5 definition of id attribute
+        *
+        * @param $id String: id to escape
+        * @param $options Mixed: string or array of strings (default is array()):
+        *   'noninitial': This is a non-initial fragment of an id, not a full id,
+        *       so don't pay attention if the first character isn't valid at the
+        *       beginning of an id.  Only matters if $wgExperimentalHtmlIds is
+        *       false.
+        *   'legacy': Behave the way the old HTML 4-based ID escaping worked even
+        *       if $wgExperimentalHtmlIds is used, so we can generate extra
+        *       anchors and links won't break.
+        * @return String
+        */
+       static function escapeId( $id, $options = array() ) {
+               global $wgHtml5, $wgExperimentalHtmlIds;
+               $options = (array)$options;
+
+               if ( $wgHtml5 && $wgExperimentalHtmlIds && !in_array( 'legacy', $options ) ) {
+                       $id = Sanitizer::decodeCharReferences( $id );
+                       $id = preg_replace( '/[ \t\n\r\f_\'"&#]+/', '_', $id );
+                       $id = trim( $id, '_' );
+                       if ( $id === '' ) {
+                               # Must have been all whitespace to start with.
+                               return '_';
+                       } else {
+                               return $id;
+                       }
+               }
+
+               # HTML4-style escaping
+               static $replace = array(
+                       '%3A' => ':',
+                       '%' => '.'
+               );
+
+               $id = urlencode( Sanitizer::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
+               $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
+
+               if ( !preg_match( '/^[a-zA-Z]/', $id )
+               && !in_array( 'noninitial', $options ) )  {
+                       // Initial character must be a letter!
+                       $id = "x$id";
+               }
+               return $id;
+       }
+
+       /**
+        * Given a value, escape it so that it can be used as a CSS class and
+        * return it.
+        *
+        * @todo For extra validity, input should be validated UTF-8.
+        *
+        * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
+        *
+        * @param $class String
+        * @return String
+        */
+       static function escapeClass( $class ) {
+               // Convert ugly stuff to underscores and kill underscores in ugly places
+               return rtrim(preg_replace(
+                       array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
+                       '_',
+                       $class ), '_');
+       }
+
+       /**
+        * Given HTML input, escape with htmlspecialchars but un-escape entites.
+        * This allows (generally harmless) entities like &nbsp; to survive.
+        *
+        * @param $html String to escape
+        * @return String: escaped input
+        */
+       static function escapeHtmlAllowEntities( $html ) {
+               # It seems wise to escape ' as well as ", as a matter of course.  Can't
+               # hurt.
+               $html = htmlspecialchars( $html, ENT_QUOTES );
+               $html = str_replace( '&amp;', '&', $html );
+               $html = Sanitizer::normalizeCharReferences( $html );
+               return $html;
+       }
+
        /**
         * Regex replace callback for armoring links against further processing.
-        * @param array $matches
+        * @param $matches Array
         * @return string
-        * @access private
         */
-       function armorLinksCallback( $matches ) {
+       private static function armorLinksCallback( $matches ) {
                return str_replace( ':', '&#58;', $matches[1] );
        }
-       
+
        /**
         * Return an associative array of attribute names and values from
         * a partial tag string. Attribute names are forces to lowercase,
         * character references are decoded to UTF-8 text.
         *
-        * @param string
-        * @return array
+        * @param $text String
+        * @return Array
         */
-       function decodeTagAttributes( $text ) {
-               $attribs = array();
-               
+       public static function decodeTagAttributes( $text ) {
                if( trim( $text ) == '' ) {
-                       return $attribs;
+                       return array();
                }
-               
+
+               $attribs = array();
+               $pairs = array();
                if( !preg_match_all(
                        MW_ATTRIBS_REGEX,
                        $text,
@@ -636,20 +1037,25 @@ class Sanitizer {
                foreach( $pairs as $set ) {
                        $attribute = strtolower( $set[1] );
                        $value = Sanitizer::getTagAttributeCallback( $set );
+
+                       // Normalize whitespace
+                       $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
+                       $value = trim( $value );
+
+                       // Decode character references
                        $attribs[$attribute] = Sanitizer::decodeCharReferences( $value );
                }
                return $attribs;
        }
-       
+
        /**
         * Pick the appropriate attribute value from a match set from the
         * MW_ATTRIBS_REGEX matches.
         *
-        * @param array $set
-        * @return string
-        * @access private
+        * @param $set Array
+        * @return String
         */
-       function getTagAttributeCallback( $set ) {
+       private static function getTagAttributeCallback( $set ) {
                if( isset( $set[6] ) ) {
                        # Illegal #XXXXXX color with no quotes.
                        return $set[6];
@@ -667,10 +1073,10 @@ class Sanitizer {
                        # For 'reduced' form, return explicitly the attribute name here.
                        return $set[1];
                } else {
-                       wfDebugDieBacktrace( "Tag conditions not met. This should never happen and is a bug." );
+                       throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
                }
        }
-       
+
        /**
         * Normalize whitespace and character references in an XML source-
         * encoded text for an attribute value.
@@ -679,18 +1085,22 @@ class Sanitizer {
         * but note that we're not returning the value, but are returning
         * XML source fragments that will be slapped into output.
         *
-        * @param string $text
-        * @return string
-        * @access private
+        * @param $text String
+        * @return String
         */
-       function normalizeAttributeValue( $text ) {
+       private static function normalizeAttributeValue( $text ) {
                return str_replace( '"', '&quot;',
-                       preg_replace(
-                               '/\r\n|[\x20\x0d\x0a\x09]/',
-                               ' ',
+                       self::normalizeWhitespace(
                                Sanitizer::normalizeCharReferences( $text ) ) );
        }
-       
+
+       private static function normalizeWhitespace( $text ) {
+               return preg_replace(
+                       '/\r\n|[\x20\x0d\x0a\x09]/',
+                       ' ',
+                       $text );
+       }
+
        /**
         * Ensure that any entities and character references are legal
         * for XML and XHTML specifically. Any stray bits will be
@@ -701,21 +1111,21 @@ class Sanitizer {
         * c. use &#x, not &#X
         * d. fix or reject non-valid attributes
         *
-        * @param string $text
-        * @return string
-        * @access private
+        * @param $text String
+        * @return String
+        * @private
         */
-       function normalizeCharReferences( $text ) {
+       static function normalizeCharReferences( $text ) {
                return preg_replace_callback(
                        MW_CHAR_REFS_REGEX,
                        array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
                        $text );
        }
        /**
-        * @param string $matches
-        * @return string
+        * @param $matches String
+        * @return String
         */
-       function normalizeCharReferencesCallback( $matches ) {
+       static function normalizeCharReferencesCallback( $matches ) {
                $ret = null;
                if( $matches[1] != '' ) {
                        $ret = Sanitizer::normalizeEntity( $matches[1] );
@@ -732,34 +1142,37 @@ class Sanitizer {
                        return $ret;
                }
        }
-       
+
        /**
         * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
-        * return the named entity reference as is. Otherwise, returns
-        * HTML-escaped text of pseudo-entity source (eg &amp;foo;)
+        * return the named entity reference as is. If the entity is a
+        * MediaWiki-specific alias, returns the HTML equivalent. Otherwise,
+        * returns HTML-escaped text of pseudo-entity source (eg &amp;foo;)
         *
-        * @param string $name
-        * @return string
+        * @param $name String
+        * @return String
         */
-       function normalizeEntity( $name ) {
-               global $wgHtmlEntities;
-               if( isset( $wgHtmlEntities[$name] ) ) {
+       static function normalizeEntity( $name ) {
+               global $wgHtmlEntities, $wgHtmlEntityAliases;
+               if ( isset( $wgHtmlEntityAliases[$name] ) ) {
+                       return "&{$wgHtmlEntityAliases[$name]};";
+               } elseif( isset( $wgHtmlEntities[$name] ) ) {
                        return "&$name;";
                } else {
                        return "&amp;$name;";
                }
        }
-       
-       function decCharReference( $codepoint ) {
-               $point = IntVal( $codepoint );
+
+       static function decCharReference( $codepoint ) {
+               $point = intval( $codepoint );
                if( Sanitizer::validateCodepoint( $point ) ) {
                        return sprintf( '&#%d;', $point );
                } else {
                        return null;
                }
        }
-       
-       function hexCharReference( $codepoint ) {
+
+       static function hexCharReference( $codepoint ) {
                $point = hexdec( $codepoint );
                if( Sanitizer::validateCodepoint( $point ) ) {
                        return sprintf( '&#x%x;', $point );
@@ -767,13 +1180,13 @@ class Sanitizer {
                        return null;
                }
        }
-       
+
        /**
         * Returns true if a given Unicode codepoint is a valid character in XML.
-        * @param int $codepoint
-        * @return bool
+        * @param $codepoint Integer
+        * @return Boolean
         */
-       function validateCodepoint( $codepoint ) {
+       private static function validateCodepoint( $codepoint ) {
                return ($codepoint ==    0x09)
                        || ($codepoint ==    0x0a)
                        || ($codepoint ==    0x0d)
@@ -786,22 +1199,21 @@ class Sanitizer {
         * Decode any character references, numeric or named entities,
         * in the text and return a UTF-8 string.
         *
-        * @param string $text
-        * @return string
-        * @access public
+        * @param $text String
+        * @return String
         */
-       function decodeCharReferences( $text ) {
+       public static function decodeCharReferences( $text ) {
                return preg_replace_callback(
                        MW_CHAR_REFS_REGEX,
                        array( 'Sanitizer', 'decodeCharReferencesCallback' ),
                        $text );
        }
-       
+
        /**
-        * @param string $matches
-        * @return string
+        * @param $matches String
+        * @return String
         */
-       function decodeCharReferencesCallback( $matches ) {
+       static function decodeCharReferencesCallback( $matches ) {
                if( $matches[1] != '' ) {
                        return Sanitizer::decodeEntity( $matches[1] );
                } elseif( $matches[2] != '' ) {
@@ -814,47 +1226,49 @@ class Sanitizer {
                # Last case should be an ampersand by itself
                return $matches[0];
        }
-       
+
        /**
         * Return UTF-8 string for a codepoint if that is a valid
         * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
-        * @param int $codepoint
-        * @return string
-        * @access private
+        * @param $codepoint Integer
+        * @return String
+        * @private
         */
-       function decodeChar( $codepoint ) {
+       static function decodeChar( $codepoint ) {
                if( Sanitizer::validateCodepoint( $codepoint ) ) {
                        return codepointToUtf8( $codepoint );
                } else {
                        return UTF8_REPLACEMENT;
                }
        }
-       
+
        /**
         * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
         * return the UTF-8 encoding of that character. Otherwise, returns
         * pseudo-entity source (eg &foo;)
         *
-        * @param string $name
-        * @return string
+        * @param $name Strings
+        * @return String
         */
-       function decodeEntity( $name ) {
-               global $wgHtmlEntities;
+       static function decodeEntity( $name ) {
+               global $wgHtmlEntities, $wgHtmlEntityAliases;
+               if ( isset( $wgHtmlEntityAliases[$name] ) ) {
+                       $name = $wgHtmlEntityAliases[$name];
+               }
                if( isset( $wgHtmlEntities[$name] ) ) {
                        return codepointToUtf8( $wgHtmlEntities[$name] );
                } else {
                        return "&$name;";
                }
        }
-       
+
        /**
-        * Fetch the whitelist of acceptable attributes for a given
-        * element name.
+        * Fetch the whitelist of acceptable attributes for a given element name.
         *
-        * @param string $element
-        * @return array
+        * @param $element String
+        * @return Array
         */
-       function attributeWhitelist( $element ) {
+       static function attributeWhitelist( $element ) {
                static $list;
                if( !isset( $list ) ) {
                        $list = Sanitizer::setupAttributeWhitelist();
@@ -863,12 +1277,31 @@ class Sanitizer {
                        ? $list[$element]
                        : array();
        }
-       
+
        /**
-        * @return array
+        * Foreach array key (an allowed HTML element), return an array
+        * of allowed attributes
+        * @return Array
         */
-       function setupAttributeWhitelist() {
+       static function setupAttributeWhitelist() {
+               global $wgAllowRdfaAttributes, $wgHtml5, $wgAllowMicrodataAttributes;
+
                $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
+
+               if ( $wgAllowRdfaAttributes ) {
+                       #RDFa attributes as specified in section 9 of http://www.w3.org/TR/2008/REC-rdfa-syntax-20081014
+                       $common = array_merge( $common, array(
+                           'about', 'property', 'resource', 'datatype', 'typeof', 
+                       ) );
+               }
+
+               if ( $wgHtml5 && $wgAllowMicrodataAttributes ) {
+                       # add HTML5 microdata tages as pecified by http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html#the-microdata-model
+                       $common = array_merge( $common, array(
+                           'itemid', 'itemprop', 'itemref', 'itemscope', 'itemtype'
+                       ) );
+               }
+
                $block = array_merge( $common, array( 'align' ) );
                $tablealign = array( 'align', 'char', 'charoff', 'valign' );
                $tablecell = array( 'abbr',
@@ -882,7 +1315,7 @@ class Sanitizer {
                                    'height', # deprecated
                                    'bgcolor' # deprecated
                                    );
-               
+
                # Numbers refer to sections in HTML 4.01 standard describing the element.
                # See: http://www.w3.org/TR/html4/
                $whitelist = array (
@@ -890,7 +1323,7 @@ class Sanitizer {
                        'div'        => $block,
                        'center'     => $common, # deprecated
                        'span'       => $block, # ??
-               
+
                        # 7.5.5
                        'h1'         => $block,
                        'h2'         => $block,
@@ -898,13 +1331,13 @@ class Sanitizer {
                        'h4'         => $block,
                        'h5'         => $block,
                        'h6'         => $block,
-                       
+
                        # 7.5.6
                        # address
-                       
+
                        # 8.2.4
                        # bdo
-               
+
                        # 9.2.1
                        'em'         => $common,
                        'strong'     => $common,
@@ -914,66 +1347,74 @@ class Sanitizer {
                        # samp
                        # kbd
                        'var'        => $common,
-                       # abbr
+                       'abbr'       => $common,
                        # acronym
-                       
+
                        # 9.2.2
                        'blockquote' => array_merge( $common, array( 'cite' ) ),
                        # q
-                       
+
                        # 9.2.3
                        'sub'        => $common,
                        'sup'        => $common,
-                       
+
                        # 9.3.1
                        'p'          => $block,
-                       
+
                        # 9.3.2
                        'br'         => array( 'id', 'class', 'title', 'style', 'clear' ),
-                       
+
                        # 9.3.4
                        'pre'        => array_merge( $common, array( 'width' ) ),
-                       
+
                        # 9.4
                        'ins'        => array_merge( $common, array( 'cite', 'datetime' ) ),
                        'del'        => array_merge( $common, array( 'cite', 'datetime' ) ),
-                       
+
                        # 10.2
                        'ul'         => array_merge( $common, array( 'type' ) ),
                        'ol'         => array_merge( $common, array( 'type', 'start' ) ),
                        'li'         => array_merge( $common, array( 'type', 'value' ) ),
-                       
+
                        # 10.3
                        'dl'         => $common,
                        'dd'         => $common,
                        'dt'         => $common,
-               
+
                        # 11.2.1
                        'table'      => array_merge( $common,
                                                                array( 'summary', 'width', 'border', 'frame',
-                                                                                        'rules', 'cellspacing', 'cellpadding',
-                                                                                        'align', 'bgcolor', 'frame', 'rules',
-                                                                                        'border' ) ),
-                       
+                                                                               'rules', 'cellspacing', 'cellpadding',
+                                                                               'align', 'bgcolor',
+                                                               ) ),
+
                        # 11.2.2
                        'caption'    => array_merge( $common, array( 'align' ) ),
-                       
+
                        # 11.2.3
                        'thead'      => array_merge( $common, $tablealign ),
                        'tfoot'      => array_merge( $common, $tablealign ),
                        'tbody'      => array_merge( $common, $tablealign ),
-                       
+
                        # 11.2.4
                        'colgroup'   => array_merge( $common, array( 'span', 'width' ), $tablealign ),
                        'col'        => array_merge( $common, array( 'span', 'width' ), $tablealign ),
-                       
+
                        # 11.2.5
                        'tr'         => array_merge( $common, array( 'bgcolor' ), $tablealign ),
-                       
+
                        # 11.2.6
                        'td'         => array_merge( $common, $tablecell, $tablealign ),
                        'th'         => array_merge( $common, $tablecell, $tablealign ),
-                       
+
+                       # 12.2 # NOTE: <a> is not allowed directly, but the attrib whitelist is used from the Parser object
+                       'a'          => array_merge( $common, array( 'href', 'rel', 'rev' ) ), # rel/rev esp. for RDFa 
+
+                       # 13.2
+                       # Not usually allowed, but may be used for extension-style hooks
+                       # such as <math> when it is rasterized
+                       'img'        => array_merge( $common, array( 'alt' ) ),
+
                        # 15.2.1
                        'tt'         => $common,
                        'b'          => $common,
@@ -983,14 +1424,14 @@ class Sanitizer {
                        'strike'     => $common,
                        's'          => $common,
                        'u'          => $common,
-               
+
                        # 15.2.2
                        'font'       => array_merge( $common, array( 'size', 'color', 'face' ) ),
                        # basefont
-                       
+
                        # 15.3
                        'hr'         => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
-                       
+
                        # XHTML Ruby annotation text module, simple ruby only.
                        # http://www.w3c.org/TR/ruby/
                        'ruby'       => $common,
@@ -999,35 +1440,95 @@ class Sanitizer {
                        'rb'         => $common,
                        'rt'         => $common, #array_merge( $common, array( 'rbspan' ) ),
                        'rp'         => $common,
+
+                       # MathML root element, where used for extensions
+                       # 'title' may not be 100% valid here; it's XHTML
+                       # http://www.w3.org/TR/REC-MathML/
+                       'math'       => array( 'class', 'style', 'id', 'title' ),
                        );
                return $whitelist;
        }
-       
+
        /**
         * Take a fragment of (potentially invalid) HTML and return
-        * a version with any tags removed, encoded suitably for literal
-        * inclusion in an attribute value.
+        * a version with any tags removed, encoded as plain text.
         *
-        * @param string $text HTML fragment
-        * @return string
+        * Warning: this return value must be further escaped for literal
+        * inclusion in HTML output as of 1.10!
+        *
+        * @param $text String: HTML fragment
+        * @return String
         */
-       function stripAllTags( $text ) {
+       static function stripAllTags( $text ) {
                # Actual <tags>
-               $text = preg_replace( '/<[^>]*>/', '', $text );
-               
+               $text = StringUtils::delimiterReplace( '<', '>', '', $text );
+
                # Normalize &entities and whitespace
-               $text = Sanitizer::normalizeAttributeValue( $text );
-               
-               # Will be placed into "double-quoted" attributes,
-               # make sure remaining bits are safe.
-               $text = str_replace(
-                       array('<', '>', '"'),
-                       array('&lt;', '&gt;', '&quot;'),
-                       $text );
-               
+               $text = self::decodeCharReferences( $text );
+               $text = self::normalizeWhitespace( $text );
+
                return $text;
        }
 
-}
+       /**
+        * Hack up a private DOCTYPE with HTML's standard entity declarations.
+        * PHP 4 seemed to know these if you gave it an HTML doctype, but
+        * PHP 5.1 doesn't.
+        *
+        * Use for passing XHTML fragments to PHP's XML parsing functions
+        *
+        * @return String
+        */
+       static function hackDocType() {
+               global $wgHtmlEntities;
+               $out = "<!DOCTYPE html [\n";
+               foreach( $wgHtmlEntities as $entity => $codepoint ) {
+                       $out .= "<!ENTITY $entity \"&#$codepoint;\">";
+               }
+               $out .= "]>\n";
+               return $out;
+       }
+
+       static function cleanUrl( $url ) {
+               # Normalize any HTML entities in input. They will be
+               # re-escaped by makeExternalLink().
+               $url = Sanitizer::decodeCharReferences( $url );
+
+               # Escape any control characters introduced by the above step
+               $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
+
+               # Validate hostname portion
+               $matches = array();
+               if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
+                       list( /* $whole */, $protocol, $host, $rest ) = $matches;
 
-?>
+                       // Characters that will be ignored in IDNs.
+                       // http://tools.ietf.org/html/3454#section-3.1
+                       // Strip them before further processing so blacklists and such work.
+                       $strip = "/
+                               \\s|          # general whitespace
+                               \xc2\xad|     # 00ad SOFT HYPHEN
+                               \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
+                               \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
+                               \xe2\x81\xa0| # 2060 WORD JOINER
+                               \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
+                               \xcd\x8f|     # 034f COMBINING GRAPHEME JOINER
+                               \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
+                               \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
+                               \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
+                               \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
+                               \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
+                               [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
+                               /xuD";
+
+                       $host = preg_replace( $strip, '', $host );
+
+                       // @todo Fixme: validate hostnames here
+
+                       return $protocol . $host . $rest;
+               } else {
+                       return $url;
+               }
+       }
+
+}