Revert r29671, it was based on a misunderstanding of the purpose of the LoggedOut...
[lhc/web/wiklou.git] / includes / Sanitizer.php
index f2dde92..c1c8daf 100644 (file)
@@ -20,8 +20,7 @@
  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  * http://www.gnu.org/copyleft/gpl.html
  *
- * @package MediaWiki
- * @subpackage Parser
+ * @addtogroup Parser
  */
 
 /**
@@ -29,7 +28,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]+);
@@ -316,8 +315,24 @@ $wgHtmlEntities = array(
        'zwj'      => 8205,
        'zwnj'     => 8204 );
 
-/** @package MediaWiki */
+/**
+ * Character entity aliases accepted by MediaWiki
+ */
+global $wgHtmlEntityAliases;
+$wgHtmlEntityAliases = array(
+       'רלמ' => 'rlm',
+       'رلم' => 'rlm',
+);
+
+
+/**
+ * XHTML sanitizer for MediaWiki
+ * @addtogroup Parser
+ */
 class Sanitizer {
+       const NONE = 0;
+       const INITIAL_NONLETTER = 1;
+
        /**
         * Cleans up HTML, removes dangerous tags and attributes, and
         * removes HTML comments
@@ -327,19 +342,23 @@ class Sanitizer {
         * @param array $args for the processing callback
         * @return string
         */
-       static 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() ) {
+               global $wgUseTidy;
+
+               static $htmlpairs, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
+                       $htmllist, $listtags, $htmlsingleallowed, $htmlelements, $staticInitialised;
 
-               if( $wgUserHtml ) {
-                       $htmlpairs = array( # Tags that must be closed
+               wfProfileIn( __METHOD__ );
+
+               if ( !$staticInitialised ) {
+
+                       $htmlpairs = array_merge( $extratags, 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', 'u'
-                       );
+                       ) );
                        $htmlsingle = array(
                                'br', 'hr', 'li', 'dt', 'dd'
                        );
@@ -350,7 +369,7 @@ class Sanitizer {
                                'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
                                'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
                        );
-                       $tabletags = array( # Can only appear inside table
+                       $tabletags = array( # Can only appear inside table, we will close them
                                'td', 'th', 'tr',
                        );
                        $htmllist = array( # Tags used by list
@@ -360,44 +379,48 @@ class Sanitizer {
                                'li',
                        );
 
-               } else {
-                       $htmlpairs = array();
-                       $htmlsingle = array();
-                       $htmlnest = array();
-                       $tabletags = array();
-               }
+                       $htmlsingleallowed = array_merge( $htmlsingle, $tabletags );
+                       $htmlelements = array_merge( $htmlsingle, $htmlpairs, $htmlnest );
 
-               $htmlsingleallowed = array_merge( $htmlsingle, $tabletags );
-               $htmlelements = array_merge( $htmlsingle, $htmlpairs, $htmlnest );
+                       # Convert them all to hashtables for faster lookup
+                       $vars = array( 'htmlpairs', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags', 
+                               'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelements' );
+                       foreach ( $vars as $var ) {
+                               $$var = array_flip( $$var );
+                       }
+                       $staticInitialised = true;
+               }
 
                # Remove HTML comments
                $text = Sanitizer::removeHTMLcomments( $text );
                $bits = explode( '<', $text );
-               $text = array_shift( $bits );
+               $text = str_replace( '>', '&gt;', array_shift( $bits ) );
                if(!$wgUseTidy) {
-                       $tagstack = array(); $tablestack = array();
+                       $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();
+                               if( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
+                                       list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
+                               } else {
+                                       $slash = $t = $params = $brace = $rest = null;
+                               }
 
                                $badtag = 0 ;
-                               if ( in_array( $t = strtolower( $t ), $htmlelements ) ) {
+                               if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
                                        # Check our stack
                                        if ( $slash ) {
                                                # Closing a tag...
-                                               if( in_array( $t, $htmlsingleonly ) ) {
+                                               if( isset( $htmlsingleonly[$t] ) ) {
                                                        $badtag = 1;
                                                } elseif ( ( $ot = @array_pop( $tagstack ) ) != $t ) {
-                                                       if ( in_array($ot, $htmlsingleallowed) ) {
+                                                       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);
                                                                while ( ( ( $ot = @array_pop( $tagstack ) ) != $t ) &&
-                                                                                               in_array($ot, $htmlsingleallowed) ) {
+                                                                               isset( $htmlsingleallowed[$ot] ) ) 
+                                                               {
                                                                        array_push ($optstack, $ot);
                                                                }
                                                                if ( $t != $ot ) {
@@ -410,7 +433,7 @@ class Sanitizer {
                                                        } else {
                                                                @array_push( $tagstack, $ot );
                                                                # <li> can be nested in <ul> or <ol>, skip those cases:
-                                                               if(!(in_array($ot, $htmllist) && in_array($t, $listtags) )) {
+                                                               if(!(isset( $htmllist[$ot] ) && isset( $listtags[$t] ) )) {
                                                                        $badtag = 1;
                                                                }
                                                        }
@@ -422,22 +445,26 @@ class Sanitizer {
                                                $newparams = '';
                                        } else {
                                                # Keep track for later
-                                               if ( in_array( $t, $tabletags ) &&
+                                               if ( isset( $tabletags[$t] ) &&
                                                ! in_array( 'table', $tagstack ) ) {
                                                        $badtag = 1;
                                                } else if ( in_array( $t, $tagstack ) &&
-                                               ! in_array ( $t , $htmlnest ) ) {
+                                               ! isset( $htmlnest [$t ] ) ) {
                                                        $badtag = 1 ;
                                                # Is it a self closed htmlpair ? (bug 5487)
                                                } else if( $brace == '/>' &&
-                                               in_array($t, $htmlpairs) ) {
+                                               isset( $htmlpairs[$t] ) ) {
                                                        $badtag = 1;
-                                               } elseif( in_array( $t, $htmlsingleonly ) ) {
+                                               } elseif( isset( $htmlsingleonly[$t] ) ) {
                                                        # Hack to force empty tag for uncloseable elements
                                                        $brace = '/>';
-                                               } else if( in_array( $t, $htmlsingle ) ) {
+                                               } else if( isset( $htmlsingle[$t] ) ) {
                                                        # Hack to not close $htmlsingle tags
                                                        $brace = NULL;
+                                               } else if( 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 );
@@ -457,7 +484,7 @@ class Sanitizer {
                                        }
                                        if ( ! $badtag ) {
                                                $rest = str_replace( '>', '&gt;', $rest );
-                                               $close = ( $brace == '/>' ) ? ' /' : '';
+                                               $close = ( $brace == '/>' && !$slash ) ? ' /' : '';
                                                $text .= "<$slash$t$newparams$close>$rest";
                                                continue;
                                        }
@@ -474,8 +501,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 ) );
                                        }
@@ -487,7 +514,7 @@ class Sanitizer {
                                }
                        }
                }
-               wfProfileOut( $fname );
+               wfProfileOut( __METHOD__ );
                return $text;
        }
 
@@ -502,8 +529,7 @@ class Sanitizer {
         * @return string
         */
        static function removeHTMLcomments( $text ) {
-               $fname='Parser::removeHTMLcomments';
-               wfProfileIn( $fname );
+               wfProfileIn( __METHOD__ );
                while (($start = strpos($text, '<!--')) !== false) {
                        $end = strpos($text, '-->', $start + 4);
                        if ($end === false) {
@@ -533,7 +559,7 @@ class Sanitizer {
                                $text = substr_replace($text, '', $start, $end - $start);
                        }
                }
-               wfProfileOut( $fname );
+               wfProfileOut( __METHOD__ );
                return $text;
        }
 
@@ -543,6 +569,7 @@ class Sanitizer {
         *
         * - Discards attributes not on a whitelist for the given element
         * - Unsafe style attributes are discarded
+        * - Invalid id attributes are reencoded
         *
         * @param array $attribs
         * @param string $element
@@ -552,7 +579,27 @@ class Sanitizer {
         * @todo Check for unique id attribute :P
         */
        static function validateTagAttributes( $attribs, $element ) {
-               $whitelist = array_flip( Sanitizer::attributeWhitelist( $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 array $attribs
+        * @param array $whitelist 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 ) {
+               $whitelist = array_flip( $whitelist );
                $out = array();
                foreach( $attribs as $attribute => $value ) {
                        if( !isset( $whitelist[$attribute] ) ) {
@@ -578,6 +625,33 @@ class Sanitizer {
                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.
+        *
+        * @todo implement merging for other attributes such as style
+        * @param array $a
+        * @param array $b
+        * @return array
+        */
+       static function mergeAttributes( $a, $b ) {
+               $out = array_merge( $a, $b );
+               if( isset( $a['class'] )
+                       && isset( $b['class'] )
+                       && $a['class'] !== $b['class'] ) {
+                       
+                       $out['class'] = implode( ' ',
+                               array_unique(
+                                       preg_split( '/\s+/',
+                                               $a['class'] . ' ' . $b['class'],
+                                               -1,
+                                               PREG_SPLIT_NO_EMPTY ) ) );
+               }
+               return $out;
+       }
+       
        /**
         * Pick apart some CSS and check it for forbidden or unsafe structures.
         * Returns a sanitized string, or false if it was just too evil.
@@ -591,14 +665,15 @@ class Sanitizer {
                $stripped = Sanitizer::decodeCharReferences( $value );
 
                // Remove any comments; IE gets token splitting wrong
-               $stripped = preg_replace( '!/\\*.*?\\*/!S', ' ', $stripped );
+               $stripped = StringUtils::delimiterReplace( '/*', '*/', ' ', $stripped );
+               
                $value = $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',
+               if( preg_match( '/(?:expression|tps*:\/\/|url\\s*\().*/is',
                                $stripped ) ) {
                        # haxx0r
                        return false;
@@ -630,15 +705,15 @@ class Sanitizer {
                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 ) : '';
@@ -650,8 +725,8 @@ class Sanitizer {
         * @return HTML-encoded text fragment
         */
        static function encodeAttribute( $text ) {
-               $encValue = htmlspecialchars( $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.
@@ -660,10 +735,10 @@ class Sanitizer {
                        "\r" => '&#13;',
                        "\t" => '&#9;',
                ) );
-               
+
                return $encValue;
        }
-       
+
        /**
         * Encode an attribute value for HTML tags, with extra armoring
         * against further wiki processing.
@@ -672,7 +747,7 @@ class Sanitizer {
         */
        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(
@@ -701,27 +776,53 @@ class Sanitizer {
         * Given a value escape it so that it can be used in an id attribute and
         * return it, this does not validate the value however (see first link)
         *
-        * @link http://www.w3.org/TR/html401/types.html#type-name Valid characters
+        * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
         *                                                          in the id and
         *                                                          name attributes
-        * @link http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
+        * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
         *
-        * @bug 4461
-        *
-        * @static
-        *
-        * @param string $id
+        * @param string $id    Id to validate
+        * @param int    $flags Currently only two values: Sanitizer::INITIAL_NONLETTER
+        *                      (default) permits initial non-letter characters,
+        *                      such as if you're adding a prefix to them.
+        *                      Sanitizer::NONE will prepend an 'x' if the id
+        *                      would otherwise start with a nonletter.
         * @return string
         */
-       static function escapeId( $id ) {
+       static function escapeId( $id, $flags = Sanitizer::INITIAL_NONLETTER ) {
                static $replace = array(
                        '%3A' => ':',
                        '%' => '.'
                );
 
                $id = urlencode( Sanitizer::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
+               $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
+               
+               if( ~$flags & Sanitizer::INITIAL_NONLETTER
+               && !preg_match( '/[a-zA-Z]/', $id[0] ) ) {
+                       // Initial character must be a letter!
+                       $id = "x$id";
+               }
+               return $id;
+       }
 
-               return str_replace( array_keys( $replace ), array_values( $replace ), $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 string $class
+        * @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 ), '_');
        }
 
        /**
@@ -761,11 +862,11 @@ 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 );
                }
@@ -816,11 +917,16 @@ class Sanitizer {
         */
        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
@@ -866,16 +972,19 @@ class Sanitizer {
 
        /**
         * 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
         * @static
         */
        static function normalizeEntity( $name ) {
-               global $wgHtmlEntities;
-               if( isset( $wgHtmlEntities[$name] ) ) {
+               global $wgHtmlEntities, $wgHtmlEntityAliases;
+               if ( isset( $wgHtmlEntityAliases[$name] ) ) {
+                       return "&{$wgHtmlEntityAliases[$name]};";
+               } elseif( isset( $wgHtmlEntities[$name] ) ) {
                        return "&$name;";
                } else {
                        return "&amp;$name;";
@@ -972,7 +1081,10 @@ class Sanitizer {
         * @return string
         */
        static function decodeEntity( $name ) {
-               global $wgHtmlEntities;
+               global $wgHtmlEntities, $wgHtmlEntityAliases;
+               if ( isset( $wgHtmlEntityAliases[$name] ) ) {
+                       $name = $wgHtmlEntityAliases[$name];
+               }
                if( isset( $wgHtmlEntities[$name] ) ) {
                        return codepointToUtf8( $wgHtmlEntities[$name] );
                } else {
@@ -1086,7 +1198,7 @@ class Sanitizer {
                        'table'      => array_merge( $common,
                                                                array( 'summary', 'width', 'border', 'frame',
                                                                                'rules', 'cellspacing', 'cellpadding',
-                                                                               'align', 'bgcolor', 'rules',
+                                                                               'align', 'bgcolor',
                                                                ) ),
 
                        # 11.2.2
@@ -1107,6 +1219,11 @@ class Sanitizer {
                        # 11.2.6
                        'td'         => array_merge( $common, $tablecell, $tablealign ),
                        'th'         => array_merge( $common, $tablecell, $tablealign ),
+                       
+                       # 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,
@@ -1133,31 +1250,32 @@ 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.
+        *
+        * Warning: this return value must be further escaped for literal
+        * inclusion in HTML output as of 1.10!
         *
         * @param string $text HTML fragment
         * @return string
         */
        static function stripAllTags( $text ) {
                # Actual <tags>
-               $text = preg_replace( '/ < .*? > /x', '', $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;
        }
@@ -1182,6 +1300,48 @@ class Sanitizer {
                return $out;
        }
 
+       static function cleanUrl( $url, $hostname=true ) {
+               # 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 );
+
+                       // @fixme: validate hostnames here
+
+                       return $protocol . $host . $rest;
+               } else {
+                       return $url;
+               }
+       }
+
 }
 
-?>
+