Fix fir r62482: PHP Notice: Undefined index: token in /www/w/includes/api/ApiMain...
[mediawiki.git] / includes / Sanitizer.php
blob8533990a92b9b617c5b4f6202cab27c1c0d7a261
1 <?php
2 /**
3 * XHTML sanitizer for MediaWiki
5 * Copyright (C) 2002-2005 Brion Vibber <brion@pobox.com> et al
6 * http://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @file
24 * @ingroup Parser
27 /**
28 * Regular expression to match various types of character references in
29 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
31 define( 'MW_CHAR_REFS_REGEX',
32 '/&([A-Za-z0-9\x80-\xff]+);
33 |&\#([0-9]+);
34 |&\#x([0-9A-Za-z]+);
35 |&\#X([0-9A-Za-z]+);
36 |(&)/x' );
38 /**
39 * Regular expression to match HTML/XML attribute pairs within a tag.
40 * Allows some... latitude.
41 * Used in Sanitizer::fixTagAttributes and Sanitizer::decodeTagAttributes
43 $attrib = '[A-Za-z0-9]';
44 $space = '[\x09\x0a\x0d\x20]';
45 define( 'MW_ATTRIBS_REGEX',
46 "/(?:^|$space)((?:xml:|xmlns:)?$attrib+)
47 ($space*=$space*
48 (?:
49 # The attribute value: quoted or alone
50 \"([^<\"]*)\"
51 | '([^<']*)'
52 | ([a-zA-Z0-9!#$%&()*,\\-.\\/:;<>?@[\\]^_`{|}~]+)
53 | (\#[0-9a-fA-F]+) # Technically wrong, but lots of
54 # colors are specified like this.
55 # We'll be normalizing it.
57 )?(?=$space|\$)/sx" );
59 /**
60 * Regular expression to match URIs that could trigger script execution
62 define( 'MW_EVIL_URI_PATTERN', '!(^|\s|\*/\s*)(javascript|vbscript)([^\w]|$)!i' );
64 /**
65 * Regular expression to match namespace attributes
67 define( 'MW_XMLNS_ATTRIBUTE_PATTRN', "/^xmlns:$attrib+$/" );
69 /**
70 * List of all named character entities defined in HTML 4.01
71 * http://www.w3.org/TR/html4/sgml/entities.html
72 * @private
74 global $wgHtmlEntities;
75 $wgHtmlEntities = array(
76 'Aacute' => 193,
77 'aacute' => 225,
78 'Acirc' => 194,
79 'acirc' => 226,
80 'acute' => 180,
81 'AElig' => 198,
82 'aelig' => 230,
83 'Agrave' => 192,
84 'agrave' => 224,
85 'alefsym' => 8501,
86 'Alpha' => 913,
87 'alpha' => 945,
88 'amp' => 38,
89 'and' => 8743,
90 'ang' => 8736,
91 'Aring' => 197,
92 'aring' => 229,
93 'asymp' => 8776,
94 'Atilde' => 195,
95 'atilde' => 227,
96 'Auml' => 196,
97 'auml' => 228,
98 'bdquo' => 8222,
99 'Beta' => 914,
100 'beta' => 946,
101 'brvbar' => 166,
102 'bull' => 8226,
103 'cap' => 8745,
104 'Ccedil' => 199,
105 'ccedil' => 231,
106 'cedil' => 184,
107 'cent' => 162,
108 'Chi' => 935,
109 'chi' => 967,
110 'circ' => 710,
111 'clubs' => 9827,
112 'cong' => 8773,
113 'copy' => 169,
114 'crarr' => 8629,
115 'cup' => 8746,
116 'curren' => 164,
117 'dagger' => 8224,
118 'Dagger' => 8225,
119 'darr' => 8595,
120 'dArr' => 8659,
121 'deg' => 176,
122 'Delta' => 916,
123 'delta' => 948,
124 'diams' => 9830,
125 'divide' => 247,
126 'Eacute' => 201,
127 'eacute' => 233,
128 'Ecirc' => 202,
129 'ecirc' => 234,
130 'Egrave' => 200,
131 'egrave' => 232,
132 'empty' => 8709,
133 'emsp' => 8195,
134 'ensp' => 8194,
135 'Epsilon' => 917,
136 'epsilon' => 949,
137 'equiv' => 8801,
138 'Eta' => 919,
139 'eta' => 951,
140 'ETH' => 208,
141 'eth' => 240,
142 'Euml' => 203,
143 'euml' => 235,
144 'euro' => 8364,
145 'exist' => 8707,
146 'fnof' => 402,
147 'forall' => 8704,
148 'frac12' => 189,
149 'frac14' => 188,
150 'frac34' => 190,
151 'frasl' => 8260,
152 'Gamma' => 915,
153 'gamma' => 947,
154 'ge' => 8805,
155 'gt' => 62,
156 'harr' => 8596,
157 'hArr' => 8660,
158 'hearts' => 9829,
159 'hellip' => 8230,
160 'Iacute' => 205,
161 'iacute' => 237,
162 'Icirc' => 206,
163 'icirc' => 238,
164 'iexcl' => 161,
165 'Igrave' => 204,
166 'igrave' => 236,
167 'image' => 8465,
168 'infin' => 8734,
169 'int' => 8747,
170 'Iota' => 921,
171 'iota' => 953,
172 'iquest' => 191,
173 'isin' => 8712,
174 'Iuml' => 207,
175 'iuml' => 239,
176 'Kappa' => 922,
177 'kappa' => 954,
178 'Lambda' => 923,
179 'lambda' => 955,
180 'lang' => 9001,
181 'laquo' => 171,
182 'larr' => 8592,
183 'lArr' => 8656,
184 'lceil' => 8968,
185 'ldquo' => 8220,
186 'le' => 8804,
187 'lfloor' => 8970,
188 'lowast' => 8727,
189 'loz' => 9674,
190 'lrm' => 8206,
191 'lsaquo' => 8249,
192 'lsquo' => 8216,
193 'lt' => 60,
194 'macr' => 175,
195 'mdash' => 8212,
196 'micro' => 181,
197 'middot' => 183,
198 'minus' => 8722,
199 'Mu' => 924,
200 'mu' => 956,
201 'nabla' => 8711,
202 'nbsp' => 160,
203 'ndash' => 8211,
204 'ne' => 8800,
205 'ni' => 8715,
206 'not' => 172,
207 'notin' => 8713,
208 'nsub' => 8836,
209 'Ntilde' => 209,
210 'ntilde' => 241,
211 'Nu' => 925,
212 'nu' => 957,
213 'Oacute' => 211,
214 'oacute' => 243,
215 'Ocirc' => 212,
216 'ocirc' => 244,
217 'OElig' => 338,
218 'oelig' => 339,
219 'Ograve' => 210,
220 'ograve' => 242,
221 'oline' => 8254,
222 'Omega' => 937,
223 'omega' => 969,
224 'Omicron' => 927,
225 'omicron' => 959,
226 'oplus' => 8853,
227 'or' => 8744,
228 'ordf' => 170,
229 'ordm' => 186,
230 'Oslash' => 216,
231 'oslash' => 248,
232 'Otilde' => 213,
233 'otilde' => 245,
234 'otimes' => 8855,
235 'Ouml' => 214,
236 'ouml' => 246,
237 'para' => 182,
238 'part' => 8706,
239 'permil' => 8240,
240 'perp' => 8869,
241 'Phi' => 934,
242 'phi' => 966,
243 'Pi' => 928,
244 'pi' => 960,
245 'piv' => 982,
246 'plusmn' => 177,
247 'pound' => 163,
248 'prime' => 8242,
249 'Prime' => 8243,
250 'prod' => 8719,
251 'prop' => 8733,
252 'Psi' => 936,
253 'psi' => 968,
254 'quot' => 34,
255 'radic' => 8730,
256 'rang' => 9002,
257 'raquo' => 187,
258 'rarr' => 8594,
259 'rArr' => 8658,
260 'rceil' => 8969,
261 'rdquo' => 8221,
262 'real' => 8476,
263 'reg' => 174,
264 'rfloor' => 8971,
265 'Rho' => 929,
266 'rho' => 961,
267 'rlm' => 8207,
268 'rsaquo' => 8250,
269 'rsquo' => 8217,
270 'sbquo' => 8218,
271 'Scaron' => 352,
272 'scaron' => 353,
273 'sdot' => 8901,
274 'sect' => 167,
275 'shy' => 173,
276 'Sigma' => 931,
277 'sigma' => 963,
278 'sigmaf' => 962,
279 'sim' => 8764,
280 'spades' => 9824,
281 'sub' => 8834,
282 'sube' => 8838,
283 'sum' => 8721,
284 'sup' => 8835,
285 'sup1' => 185,
286 'sup2' => 178,
287 'sup3' => 179,
288 'supe' => 8839,
289 'szlig' => 223,
290 'Tau' => 932,
291 'tau' => 964,
292 'there4' => 8756,
293 'Theta' => 920,
294 'theta' => 952,
295 'thetasym' => 977,
296 'thinsp' => 8201,
297 'THORN' => 222,
298 'thorn' => 254,
299 'tilde' => 732,
300 'times' => 215,
301 'trade' => 8482,
302 'Uacute' => 218,
303 'uacute' => 250,
304 'uarr' => 8593,
305 'uArr' => 8657,
306 'Ucirc' => 219,
307 'ucirc' => 251,
308 'Ugrave' => 217,
309 'ugrave' => 249,
310 'uml' => 168,
311 'upsih' => 978,
312 'Upsilon' => 933,
313 'upsilon' => 965,
314 'Uuml' => 220,
315 'uuml' => 252,
316 'weierp' => 8472,
317 'Xi' => 926,
318 'xi' => 958,
319 'Yacute' => 221,
320 'yacute' => 253,
321 'yen' => 165,
322 'Yuml' => 376,
323 'yuml' => 255,
324 'Zeta' => 918,
325 'zeta' => 950,
326 'zwj' => 8205,
327 'zwnj' => 8204 );
330 * Character entity aliases accepted by MediaWiki
332 global $wgHtmlEntityAliases;
333 $wgHtmlEntityAliases = array(
334 'רלמ' => 'rlm',
335 'رلم' => 'rlm',
340 * XHTML sanitizer for MediaWiki
341 * @ingroup Parser
343 class Sanitizer {
345 * Cleans up HTML, removes dangerous tags and attributes, and
346 * removes HTML comments
347 * @private
348 * @param $text String
349 * @param $processCallback Callback to do any variable or parameter replacements in HTML attribute values
350 * @param $args Array for the processing callback
351 * @param $extratags Array for any extra tags to include
352 * @param $removetags Array for any tags (default or extra) to exclude
353 * @return string
355 static function removeHTMLtags( $text, $processCallback = null, $args = array(), $extratags = array(), $removetags = array() ) {
356 global $wgUseTidy;
358 static $htmlpairsStatic, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
359 $htmllist, $listtags, $htmlsingleallowed, $htmlelementsStatic, $staticInitialised;
361 wfProfileIn( __METHOD__ );
363 if ( !$staticInitialised ) {
365 $htmlpairsStatic = array( # Tags that must be closed
366 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
367 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
368 'strike', 'strong', 'tt', 'var', 'div', 'center',
369 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
370 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span', 'u', 'abbr'
372 $htmlsingle = array(
373 'br', 'hr', 'li', 'dt', 'dd'
375 $htmlsingleonly = array( # Elements that cannot have close tags
376 'br', 'hr'
378 $htmlnest = array( # Tags that can be nested--??
379 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
380 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
382 $tabletags = array( # Can only appear inside table, we will close them
383 'td', 'th', 'tr',
385 $htmllist = array( # Tags used by list
386 'ul','ol',
388 $listtags = array( # Tags that can appear in a list
389 'li',
392 $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
393 $htmlelementsStatic = array_unique( array_merge( $htmlsingle, $htmlpairsStatic, $htmlnest ) );
395 # Convert them all to hashtables for faster lookup
396 $vars = array( 'htmlpairsStatic', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
397 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelementsStatic' );
398 foreach ( $vars as $var ) {
399 $$var = array_flip( $$var );
401 $staticInitialised = true;
403 # Populate $htmlpairs and $htmlelements with the $extratags and $removetags arrays
404 $extratags = array_flip( $extratags );
405 $removetags = array_flip( $removetags );
406 $htmlpairs = array_merge( $extratags, $htmlpairsStatic );
407 $htmlelements = array_diff_key( array_merge( $extratags, $htmlelementsStatic ) , $removetags );
409 # Remove HTML comments
410 $text = Sanitizer::removeHTMLcomments( $text );
411 $bits = explode( '<', $text );
412 $text = str_replace( '>', '&gt;', array_shift( $bits ) );
413 if ( !$wgUseTidy ) {
414 $tagstack = $tablestack = array();
415 foreach ( $bits as $x ) {
416 $regs = array();
417 # $slash: Does the current element start with a '/'?
418 # $t: Current element name
419 # $params: String between element name and >
420 # $brace: Ending '>' or '/>'
421 # $rest: Everything until the next element of $bits
422 if( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
423 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
424 } else {
425 $slash = $t = $params = $brace = $rest = null;
428 $badtag = false;
429 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
430 # Check our stack
431 if ( $slash && isset( $htmlsingleonly[$t] ) ) {
432 $badtag = true;
433 } elseif ( $slash ) {
434 # Closing a tag... is it the one we just opened?
435 $ot = @array_pop( $tagstack );
436 if ( $ot != $t ) {
437 if ( isset( $htmlsingleallowed[$ot] ) ) {
438 # Pop all elements with an optional close tag
439 # and see if we find a match below them
440 $optstack = array();
441 array_push( $optstack, $ot );
442 $ot = @array_pop( $tagstack );
443 while ( $ot != $t && isset( $htmlsingleallowed[$ot] ) ) {
444 array_push( $optstack, $ot );
445 $ot = @array_pop( $tagstack );
447 if ( $t != $ot ) {
448 # No match. Push the optional elements back again
449 $badtag = true;
450 while ( $ot = @array_pop( $optstack ) ) {
451 array_push( $tagstack, $ot );
454 } else {
455 @array_push( $tagstack, $ot );
456 # <li> can be nested in <ul> or <ol>, skip those cases:
457 if ( !isset( $htmllist[$ot] ) || !isset( $listtags[$t] ) ) {
458 $badtag = true;
461 } else {
462 if ( $t == 'table' ) {
463 $tagstack = array_pop( $tablestack );
466 $newparams = '';
467 } else {
468 # Keep track for later
469 if ( isset( $tabletags[$t] ) &&
470 !in_array( 'table', $tagstack ) ) {
471 $badtag = true;
472 } elseif ( in_array( $t, $tagstack ) &&
473 !isset( $htmlnest [$t ] ) ) {
474 $badtag = true;
475 # Is it a self closed htmlpair ? (bug 5487)
476 } elseif ( $brace == '/>' &&
477 isset( $htmlpairs[$t] ) ) {
478 $badtag = true;
479 } elseif ( isset( $htmlsingleonly[$t] ) ) {
480 # Hack to force empty tag for uncloseable elements
481 $brace = '/>';
482 } elseif ( isset( $htmlsingle[$t] ) ) {
483 # Hack to not close $htmlsingle tags
484 $brace = null;
485 } elseif ( isset( $tabletags[$t] )
486 && in_array( $t, $tagstack ) ) {
487 // New table tag but forgot to close the previous one
488 $text .= "</$t>";
489 } else {
490 if ( $t == 'table' ) {
491 array_push( $tablestack, $tagstack );
492 $tagstack = array();
494 array_push( $tagstack, $t );
497 # Replace any variables or template parameters with
498 # plaintext results.
499 if( is_callable( $processCallback ) ) {
500 call_user_func_array( $processCallback, array( &$params, $args ) );
503 # Strip non-approved attributes from the tag
504 $newparams = Sanitizer::fixTagAttributes( $params, $t );
506 if ( !$badtag ) {
507 $rest = str_replace( '>', '&gt;', $rest );
508 $close = ( $brace == '/>' && !$slash ) ? ' /' : '';
509 $text .= "<$slash$t$newparams$close>$rest";
510 continue;
513 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
515 # Close off any remaining tags
516 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
517 $text .= "</$t>\n";
518 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
520 } else {
521 # this might be possible using tidy itself
522 foreach ( $bits as $x ) {
523 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
524 $x, $regs );
525 @list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
526 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
527 if( is_callable( $processCallback ) ) {
528 call_user_func_array( $processCallback, array( &$params, $args ) );
530 $newparams = Sanitizer::fixTagAttributes( $params, $t );
531 $rest = str_replace( '>', '&gt;', $rest );
532 $text .= "<$slash$t$newparams$brace$rest";
533 } else {
534 $text .= '&lt;' . str_replace( '>', '&gt;', $x);
538 wfProfileOut( __METHOD__ );
539 return $text;
543 * Remove '<!--', '-->', and everything between.
544 * To avoid leaving blank lines, when a comment is both preceded
545 * and followed by a newline (ignoring spaces), trim leading and
546 * trailing spaces and one of the newlines.
548 * @private
549 * @param $text String
550 * @return string
552 static function removeHTMLcomments( $text ) {
553 wfProfileIn( __METHOD__ );
554 while (($start = strpos($text, '<!--')) !== false) {
555 $end = strpos($text, '-->', $start + 4);
556 if ($end === false) {
557 # Unterminated comment; bail out
558 break;
561 $end += 3;
563 # Trim space and newline if the comment is both
564 # preceded and followed by a newline
565 $spaceStart = max($start - 1, 0);
566 $spaceLen = $end - $spaceStart;
567 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
568 $spaceStart--;
569 $spaceLen++;
571 while (substr($text, $spaceStart + $spaceLen, 1) === ' ')
572 $spaceLen++;
573 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart + $spaceLen, 1) === "\n") {
574 # Remove the comment, leading and trailing
575 # spaces, and leave only one newline.
576 $text = substr_replace($text, "\n", $spaceStart, $spaceLen + 1);
578 else {
579 # Remove just the comment.
580 $text = substr_replace($text, '', $start, $end - $start);
583 wfProfileOut( __METHOD__ );
584 return $text;
588 * Take an array of attribute names and values and normalize or discard
589 * illegal values for the given element type.
591 * - Discards attributes not on a whitelist for the given element
592 * - Unsafe style attributes are discarded
593 * - Invalid id attributes are reencoded
595 * @param $attribs Array
596 * @param $element String
597 * @return Array
599 * @todo Check for legal values where the DTD limits things.
600 * @todo Check for unique id attribute :P
602 static function validateTagAttributes( $attribs, $element ) {
603 return Sanitizer::validateAttributes( $attribs,
604 Sanitizer::attributeWhitelist( $element ) );
608 * Take an array of attribute names and values and normalize or discard
609 * illegal values for the given whitelist.
611 * - Discards attributes not the given whitelist
612 * - Unsafe style attributes are discarded
613 * - Invalid id attributes are reencoded
615 * @param $attribs Array
616 * @param $whitelist Array: list of allowed attribute names
617 * @return Array
619 * @todo Check for legal values where the DTD limits things.
620 * @todo Check for unique id attribute :P
622 static function validateAttributes( $attribs, $whitelist ) {
623 global $wgAllowRdfaAttributes, $wgAllowMicrodataAttributes;
625 $whitelist = array_flip( $whitelist );
626 $hrefExp = '/^(' . wfUrlProtocols() . ')[^\s]+$/';
628 $out = array();
629 foreach( $attribs as $attribute => $value ) {
630 #allow XML namespace declaration if RDFa is enabled
631 if ( $wgAllowRdfaAttributes && preg_match( MW_XMLNS_ATTRIBUTE_PATTRN, $attribute ) ) {
632 if ( !preg_match( MW_EVIL_URI_PATTERN, $value ) ) {
633 $out[$attribute] = $value;
636 continue;
639 if( !isset( $whitelist[$attribute] ) ) {
640 continue;
643 # Strip javascript "expression" from stylesheets.
644 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
645 if( $attribute == 'style' ) {
646 $value = Sanitizer::checkCss( $value );
647 if( $value === false ) {
648 # haxx0r
649 continue;
653 if ( $attribute === 'id' ) {
654 $value = Sanitizer::escapeId( $value, 'noninitial' );
657 //RDFa and microdata properties allow URLs, URIs and/or CURIs. check them for sanity
658 if ( $attribute === 'rel' || $attribute === 'rev' ||
659 $attribute === 'about' || $attribute === 'property' || $attribute === 'resource' || #RDFa
660 $attribute === 'datatype' || $attribute === 'typeof' || #RDFa
661 $attribute === 'itemid' || $attribute === 'itemprop' || $attribute === 'itemref' || #HTML5 microdata
662 $attribute === 'itemscope' || $attribute === 'itemtype' ) { #HTML5 microdata
664 //Paranoia. Allow "simple" values but suppress javascript
665 if ( preg_match( MW_EVIL_URI_PATTERN, $value ) ) {
666 continue;
670 # NOTE: even though elements using href/src are not allowed directly, supply
671 # validation code that can be used by tag hook handlers, etc
672 if ( $attribute === 'href' || $attribute === 'src' ) {
673 if ( !preg_match( $hrefExp, $value ) ) {
674 continue; //drop any href or src attributes not using an allowed protocol.
675 //NOTE: this also drops all relative URLs
679 // If this attribute was previously set, override it.
680 // Output should only have one attribute of each name.
681 $out[$attribute] = $value;
684 if ( $wgAllowMicrodataAttributes ) {
685 # There are some complicated validity constraints we need to
686 # enforce here. First of all, we don't want to allow non-standard
687 # itemtypes.
688 $allowedTypes = array(
689 'http://microformats.org/profile/hcard',
690 'http://microformats.org/profile/hcalendar#vevent',
691 'http://n.whatwg.org/work',
693 if ( isset( $out['itemtype'] ) && !in_array( $out['itemtype'],
694 $allowedTypes ) ) {
695 # Kill everything
696 unset( $out['itemscope'] );
698 # itemtype, itemid, itemref don't make sense without itemscope
699 if ( !array_key_exists( 'itemscope', $out ) ) {
700 unset( $out['itemtype'] );
701 unset( $out['itemid'] );
702 unset( $out['itemref'] );
704 # TODO: Strip itemprop if we aren't descendants of an itemscope.
706 return $out;
710 * Merge two sets of HTML attributes. Conflicting items in the second set
711 * will override those in the first, except for 'class' attributes which
712 * will be combined (if they're both strings).
714 * @todo implement merging for other attributes such as style
715 * @param $a Array
716 * @param $b Array
717 * @return array
719 static function mergeAttributes( $a, $b ) {
720 $out = array_merge( $a, $b );
721 if( isset( $a['class'] ) && isset( $b['class'] )
722 && is_string( $a['class'] ) && is_string( $b['class'] )
723 && $a['class'] !== $b['class'] ) {
724 $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
725 -1, PREG_SPLIT_NO_EMPTY );
726 $out['class'] = implode( ' ', array_unique( $classes ) );
728 return $out;
732 * Pick apart some CSS and check it for forbidden or unsafe structures.
733 * Returns a sanitized string, or false if it was just too evil.
735 * Currently URL references, 'expression', 'tps' are forbidden.
737 * @param $value String
738 * @return Mixed
740 static function checkCss( $value ) {
741 $stripped = Sanitizer::decodeCharReferences( $value );
743 // Remove any comments; IE gets token splitting wrong
744 $stripped = StringUtils::delimiterReplace( '/*', '*/', ' ', $stripped );
746 $value = $stripped;
748 // ... and continue checks
749 $stripped = preg_replace( '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!e',
750 'codepointToUtf8(hexdec("$1"))', $stripped );
751 $stripped = str_replace( '\\', '', $stripped );
752 if( preg_match( '/(?:expression|tps*:\/\/|url\\s*\().*/is',
753 $stripped ) ) {
754 # haxx0r
755 return false;
758 return $value;
762 * Take a tag soup fragment listing an HTML element's attributes
763 * and normalize it to well-formed XML, discarding unwanted attributes.
764 * Output is safe for further wikitext processing, with escaping of
765 * values that could trigger problems.
767 * - Normalizes attribute names to lowercase
768 * - Discards attributes not on a whitelist for the given element
769 * - Turns broken or invalid entities into plaintext
770 * - Double-quotes all attribute values
771 * - Attributes without values are given the name as attribute
772 * - Double attributes are discarded
773 * - Unsafe style attributes are discarded
774 * - Prepends space if there are attributes.
776 * @param $text String
777 * @param $element String
778 * @return String
780 static function fixTagAttributes( $text, $element ) {
781 if( trim( $text ) == '' ) {
782 return '';
785 $stripped = Sanitizer::validateTagAttributes(
786 Sanitizer::decodeTagAttributes( $text ), $element );
788 $attribs = array();
789 foreach( $stripped as $attribute => $value ) {
790 $encAttribute = htmlspecialchars( $attribute );
791 $encValue = Sanitizer::safeEncodeAttribute( $value );
793 $attribs[] = "$encAttribute=\"$encValue\"";
795 return count( $attribs ) ? ' ' . implode( ' ', $attribs ) : '';
799 * Encode an attribute value for HTML output.
800 * @param $text String
801 * @return HTML-encoded text fragment
803 static function encodeAttribute( $text ) {
804 $encValue = htmlspecialchars( $text, ENT_QUOTES );
806 // Whitespace is normalized during attribute decoding,
807 // so if we've been passed non-spaces we must encode them
808 // ahead of time or they won't be preserved.
809 $encValue = strtr( $encValue, array(
810 "\n" => '&#10;',
811 "\r" => '&#13;',
812 "\t" => '&#9;',
813 ) );
815 return $encValue;
819 * Encode an attribute value for HTML tags, with extra armoring
820 * against further wiki processing.
821 * @param $text String
822 * @return HTML-encoded text fragment
824 static function safeEncodeAttribute( $text ) {
825 $encValue = Sanitizer::encodeAttribute( $text );
827 # Templates and links may be expanded in later parsing,
828 # creating invalid or dangerous output. Suppress this.
829 $encValue = strtr( $encValue, array(
830 '<' => '&lt;', // This should never happen,
831 '>' => '&gt;', // we've received invalid input
832 '"' => '&quot;', // which should have been escaped.
833 '{' => '&#123;',
834 '[' => '&#91;',
835 "''" => '&#39;&#39;',
836 'ISBN' => '&#73;SBN',
837 'RFC' => '&#82;FC',
838 'PMID' => '&#80;MID',
839 '|' => '&#124;',
840 '__' => '&#95;_',
841 ) );
843 # Stupid hack
844 $encValue = preg_replace_callback(
845 '/(' . wfUrlProtocols() . ')/',
846 array( 'Sanitizer', 'armorLinksCallback' ),
847 $encValue );
848 return $encValue;
852 * Given a value, escape it so that it can be used in an id attribute and
853 * return it. This will use HTML5 validation if $wgExperimentalHtmlIds is
854 * true, allowing anything but ASCII whitespace. Otherwise it will use
855 * HTML 4 rules, which means a narrow subset of ASCII, with bad characters
856 * escaped with lots of dots.
858 * To ensure we don't have to bother escaping anything, we also strip ', ",
859 * & even if $wgExperimentalIds is true. TODO: Is this the best tactic?
860 * We also strip # because it upsets IE6.
862 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
863 * in the id and
864 * name attributes
865 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
866 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#the-id-attribute
867 * HTML5 definition of id attribute
869 * @param $id String: id to escape
870 * @param $options Mixed: string or array of strings (default is array()):
871 * 'noninitial': This is a non-initial fragment of an id, not a full id,
872 * so don't pay attention if the first character isn't valid at the
873 * beginning of an id. Only matters if $wgExperimentalHtmlIds is
874 * false.
875 * 'legacy': Behave the way the old HTML 4-based ID escaping worked even
876 * if $wgExperimentalHtmlIds is used, so we can generate extra
877 * anchors and links won't break.
878 * @return String
880 static function escapeId( $id, $options = array() ) {
881 global $wgHtml5, $wgExperimentalHtmlIds;
882 $options = (array)$options;
884 if ( $wgHtml5 && $wgExperimentalHtmlIds && !in_array( 'legacy', $options ) ) {
885 $id = Sanitizer::decodeCharReferences( $id );
886 $id = preg_replace( '/[ \t\n\r\f_\'"&#]+/', '_', $id );
887 $id = trim( $id, '_' );
888 if ( $id === '' ) {
889 # Must have been all whitespace to start with.
890 return '_';
891 } else {
892 return $id;
896 # HTML4-style escaping
897 static $replace = array(
898 '%3A' => ':',
899 '%' => '.'
902 $id = urlencode( Sanitizer::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
903 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
905 if ( !preg_match( '/^[a-zA-Z]/', $id )
906 && !in_array( 'noninitial', $options ) ) {
907 // Initial character must be a letter!
908 $id = "x$id";
910 return $id;
914 * Given a value, escape it so that it can be used as a CSS class and
915 * return it.
917 * @todo For extra validity, input should be validated UTF-8.
919 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
921 * @param $class String
922 * @return String
924 static function escapeClass( $class ) {
925 // Convert ugly stuff to underscores and kill underscores in ugly places
926 return rtrim(preg_replace(
927 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
928 '_',
929 $class ), '_');
933 * Given HTML input, escape with htmlspecialchars but un-escape entites.
934 * This allows (generally harmless) entities like &nbsp; to survive.
936 * @param $html String to escape
937 * @return String: escaped input
939 static function escapeHtmlAllowEntities( $html ) {
940 # It seems wise to escape ' as well as ", as a matter of course. Can't
941 # hurt.
942 $html = htmlspecialchars( $html, ENT_QUOTES );
943 $html = str_replace( '&amp;', '&', $html );
944 $html = Sanitizer::normalizeCharReferences( $html );
945 return $html;
949 * Regex replace callback for armoring links against further processing.
950 * @param $matches Array
951 * @return string
953 private static function armorLinksCallback( $matches ) {
954 return str_replace( ':', '&#58;', $matches[1] );
958 * Return an associative array of attribute names and values from
959 * a partial tag string. Attribute names are forces to lowercase,
960 * character references are decoded to UTF-8 text.
962 * @param $text String
963 * @return Array
965 public static function decodeTagAttributes( $text ) {
966 if( trim( $text ) == '' ) {
967 return array();
970 $attribs = array();
971 $pairs = array();
972 if( !preg_match_all(
973 MW_ATTRIBS_REGEX,
974 $text,
975 $pairs,
976 PREG_SET_ORDER ) ) {
977 return $attribs;
980 foreach( $pairs as $set ) {
981 $attribute = strtolower( $set[1] );
982 $value = Sanitizer::getTagAttributeCallback( $set );
984 // Normalize whitespace
985 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
986 $value = trim( $value );
988 // Decode character references
989 $attribs[$attribute] = Sanitizer::decodeCharReferences( $value );
991 return $attribs;
995 * Pick the appropriate attribute value from a match set from the
996 * MW_ATTRIBS_REGEX matches.
998 * @param $set Array
999 * @return String
1001 private static function getTagAttributeCallback( $set ) {
1002 if( isset( $set[6] ) ) {
1003 # Illegal #XXXXXX color with no quotes.
1004 return $set[6];
1005 } elseif( isset( $set[5] ) ) {
1006 # No quotes.
1007 return $set[5];
1008 } elseif( isset( $set[4] ) ) {
1009 # Single-quoted
1010 return $set[4];
1011 } elseif( isset( $set[3] ) ) {
1012 # Double-quoted
1013 return $set[3];
1014 } elseif( !isset( $set[2] ) ) {
1015 # In XHTML, attributes must have a value.
1016 # For 'reduced' form, return explicitly the attribute name here.
1017 return $set[1];
1018 } else {
1019 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
1024 * Normalize whitespace and character references in an XML source-
1025 * encoded text for an attribute value.
1027 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
1028 * but note that we're not returning the value, but are returning
1029 * XML source fragments that will be slapped into output.
1031 * @param $text String
1032 * @return String
1034 private static function normalizeAttributeValue( $text ) {
1035 return str_replace( '"', '&quot;',
1036 self::normalizeWhitespace(
1037 Sanitizer::normalizeCharReferences( $text ) ) );
1040 private static function normalizeWhitespace( $text ) {
1041 return preg_replace(
1042 '/\r\n|[\x20\x0d\x0a\x09]/',
1043 ' ',
1044 $text );
1048 * Ensure that any entities and character references are legal
1049 * for XML and XHTML specifically. Any stray bits will be
1050 * &amp;-escaped to result in a valid text fragment.
1052 * a. any named char refs must be known in XHTML
1053 * b. any numeric char refs must be legal chars, not invalid or forbidden
1054 * c. use &#x, not &#X
1055 * d. fix or reject non-valid attributes
1057 * @param $text String
1058 * @return String
1059 * @private
1061 static function normalizeCharReferences( $text ) {
1062 return preg_replace_callback(
1063 MW_CHAR_REFS_REGEX,
1064 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
1065 $text );
1068 * @param $matches String
1069 * @return String
1071 static function normalizeCharReferencesCallback( $matches ) {
1072 $ret = null;
1073 if( $matches[1] != '' ) {
1074 $ret = Sanitizer::normalizeEntity( $matches[1] );
1075 } elseif( $matches[2] != '' ) {
1076 $ret = Sanitizer::decCharReference( $matches[2] );
1077 } elseif( $matches[3] != '' ) {
1078 $ret = Sanitizer::hexCharReference( $matches[3] );
1079 } elseif( $matches[4] != '' ) {
1080 $ret = Sanitizer::hexCharReference( $matches[4] );
1082 if( is_null( $ret ) ) {
1083 return htmlspecialchars( $matches[0] );
1084 } else {
1085 return $ret;
1090 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1091 * return the named entity reference as is. If the entity is a
1092 * MediaWiki-specific alias, returns the HTML equivalent. Otherwise,
1093 * returns HTML-escaped text of pseudo-entity source (eg &amp;foo;)
1095 * @param $name String
1096 * @return String
1098 static function normalizeEntity( $name ) {
1099 global $wgHtmlEntities, $wgHtmlEntityAliases;
1100 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1101 return "&{$wgHtmlEntityAliases[$name]};";
1102 } elseif( isset( $wgHtmlEntities[$name] ) ) {
1103 return "&$name;";
1104 } else {
1105 return "&amp;$name;";
1109 static function decCharReference( $codepoint ) {
1110 $point = intval( $codepoint );
1111 if( Sanitizer::validateCodepoint( $point ) ) {
1112 return sprintf( '&#%d;', $point );
1113 } else {
1114 return null;
1118 static function hexCharReference( $codepoint ) {
1119 $point = hexdec( $codepoint );
1120 if( Sanitizer::validateCodepoint( $point ) ) {
1121 return sprintf( '&#x%x;', $point );
1122 } else {
1123 return null;
1128 * Returns true if a given Unicode codepoint is a valid character in XML.
1129 * @param $codepoint Integer
1130 * @return Boolean
1132 private static function validateCodepoint( $codepoint ) {
1133 return ($codepoint == 0x09)
1134 || ($codepoint == 0x0a)
1135 || ($codepoint == 0x0d)
1136 || ($codepoint >= 0x20 && $codepoint <= 0xd7ff)
1137 || ($codepoint >= 0xe000 && $codepoint <= 0xfffd)
1138 || ($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
1142 * Decode any character references, numeric or named entities,
1143 * in the text and return a UTF-8 string.
1145 * @param $text String
1146 * @return String
1148 public static function decodeCharReferences( $text ) {
1149 return preg_replace_callback(
1150 MW_CHAR_REFS_REGEX,
1151 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1152 $text );
1156 * @param $matches String
1157 * @return String
1159 static function decodeCharReferencesCallback( $matches ) {
1160 if( $matches[1] != '' ) {
1161 return Sanitizer::decodeEntity( $matches[1] );
1162 } elseif( $matches[2] != '' ) {
1163 return Sanitizer::decodeChar( intval( $matches[2] ) );
1164 } elseif( $matches[3] != '' ) {
1165 return Sanitizer::decodeChar( hexdec( $matches[3] ) );
1166 } elseif( $matches[4] != '' ) {
1167 return Sanitizer::decodeChar( hexdec( $matches[4] ) );
1169 # Last case should be an ampersand by itself
1170 return $matches[0];
1174 * Return UTF-8 string for a codepoint if that is a valid
1175 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1176 * @param $codepoint Integer
1177 * @return String
1178 * @private
1180 static function decodeChar( $codepoint ) {
1181 if( Sanitizer::validateCodepoint( $codepoint ) ) {
1182 return codepointToUtf8( $codepoint );
1183 } else {
1184 return UTF8_REPLACEMENT;
1189 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1190 * return the UTF-8 encoding of that character. Otherwise, returns
1191 * pseudo-entity source (eg &foo;)
1193 * @param $name Strings
1194 * @return String
1196 static function decodeEntity( $name ) {
1197 global $wgHtmlEntities, $wgHtmlEntityAliases;
1198 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1199 $name = $wgHtmlEntityAliases[$name];
1201 if( isset( $wgHtmlEntities[$name] ) ) {
1202 return codepointToUtf8( $wgHtmlEntities[$name] );
1203 } else {
1204 return "&$name;";
1209 * Fetch the whitelist of acceptable attributes for a given element name.
1211 * @param $element String
1212 * @return Array
1214 static function attributeWhitelist( $element ) {
1215 static $list;
1216 if( !isset( $list ) ) {
1217 $list = Sanitizer::setupAttributeWhitelist();
1219 return isset( $list[$element] )
1220 ? $list[$element]
1221 : array();
1225 * Foreach array key (an allowed HTML element), return an array
1226 * of allowed attributes
1227 * @return Array
1229 static function setupAttributeWhitelist() {
1230 global $wgAllowRdfaAttributes, $wgHtml5, $wgAllowMicrodataAttributes;
1232 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style', 'xml:lang' );
1234 if ( $wgAllowRdfaAttributes ) {
1235 #RDFa attributes as specified in section 9 of http://www.w3.org/TR/2008/REC-rdfa-syntax-20081014
1236 $common = array_merge( $common, array(
1237 'about', 'property', 'resource', 'datatype', 'typeof',
1238 ) );
1241 if ( $wgHtml5 && $wgAllowMicrodataAttributes ) {
1242 # add HTML5 microdata tages as pecified by http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html#the-microdata-model
1243 $common = array_merge( $common, array(
1244 'itemid', 'itemprop', 'itemref', 'itemscope', 'itemtype'
1245 ) );
1248 $block = array_merge( $common, array( 'align' ) );
1249 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1250 $tablecell = array( 'abbr',
1251 'axis',
1252 'headers',
1253 'scope',
1254 'rowspan',
1255 'colspan',
1256 'nowrap', # deprecated
1257 'width', # deprecated
1258 'height', # deprecated
1259 'bgcolor' # deprecated
1262 # Numbers refer to sections in HTML 4.01 standard describing the element.
1263 # See: http://www.w3.org/TR/html4/
1264 $whitelist = array (
1265 # 7.5.4
1266 'div' => $block,
1267 'center' => $common, # deprecated
1268 'span' => $block, # ??
1270 # 7.5.5
1271 'h1' => $block,
1272 'h2' => $block,
1273 'h3' => $block,
1274 'h4' => $block,
1275 'h5' => $block,
1276 'h6' => $block,
1278 # 7.5.6
1279 # address
1281 # 8.2.4
1282 # bdo
1284 # 9.2.1
1285 'em' => $common,
1286 'strong' => $common,
1287 'cite' => $common,
1288 # dfn
1289 'code' => $common,
1290 # samp
1291 # kbd
1292 'var' => $common,
1293 'abbr' => $common,
1294 # acronym
1296 # 9.2.2
1297 'blockquote' => array_merge( $common, array( 'cite' ) ),
1300 # 9.2.3
1301 'sub' => $common,
1302 'sup' => $common,
1304 # 9.3.1
1305 'p' => $block,
1307 # 9.3.2
1308 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1310 # 9.3.4
1311 'pre' => array_merge( $common, array( 'width' ) ),
1313 # 9.4
1314 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1315 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1317 # 10.2
1318 'ul' => array_merge( $common, array( 'type' ) ),
1319 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1320 'li' => array_merge( $common, array( 'type', 'value' ) ),
1322 # 10.3
1323 'dl' => $common,
1324 'dd' => $common,
1325 'dt' => $common,
1327 # 11.2.1
1328 'table' => array_merge( $common,
1329 array( 'summary', 'width', 'border', 'frame',
1330 'rules', 'cellspacing', 'cellpadding',
1331 'align', 'bgcolor',
1332 ) ),
1334 # 11.2.2
1335 'caption' => array_merge( $common, array( 'align' ) ),
1337 # 11.2.3
1338 'thead' => array_merge( $common, $tablealign ),
1339 'tfoot' => array_merge( $common, $tablealign ),
1340 'tbody' => array_merge( $common, $tablealign ),
1342 # 11.2.4
1343 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1344 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1346 # 11.2.5
1347 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1349 # 11.2.6
1350 'td' => array_merge( $common, $tablecell, $tablealign ),
1351 'th' => array_merge( $common, $tablecell, $tablealign ),
1353 # 12.2 # NOTE: <a> is not allowed directly, but the attrib whitelist is used from the Parser object
1354 'a' => array_merge( $common, array( 'href', 'rel', 'rev' ) ), # rel/rev esp. for RDFa
1356 # 13.2
1357 # Not usually allowed, but may be used for extension-style hooks
1358 # such as <math> when it is rasterized
1359 'img' => array_merge( $common, array( 'alt' ) ),
1361 # 15.2.1
1362 'tt' => $common,
1363 'b' => $common,
1364 'i' => $common,
1365 'big' => $common,
1366 'small' => $common,
1367 'strike' => $common,
1368 's' => $common,
1369 'u' => $common,
1371 # 15.2.2
1372 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1373 # basefont
1375 # 15.3
1376 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1378 # XHTML Ruby annotation text module, simple ruby only.
1379 # http://www.w3c.org/TR/ruby/
1380 'ruby' => $common,
1381 # rbc
1382 # rtc
1383 'rb' => $common,
1384 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1385 'rp' => $common,
1387 # MathML root element, where used for extensions
1388 # 'title' may not be 100% valid here; it's XHTML
1389 # http://www.w3.org/TR/REC-MathML/
1390 'math' => array( 'class', 'style', 'id', 'title' ),
1392 return $whitelist;
1396 * Take a fragment of (potentially invalid) HTML and return
1397 * a version with any tags removed, encoded as plain text.
1399 * Warning: this return value must be further escaped for literal
1400 * inclusion in HTML output as of 1.10!
1402 * @param $text String: HTML fragment
1403 * @return String
1405 static function stripAllTags( $text ) {
1406 # Actual <tags>
1407 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
1409 # Normalize &entities and whitespace
1410 $text = self::decodeCharReferences( $text );
1411 $text = self::normalizeWhitespace( $text );
1413 return $text;
1417 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1418 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1419 * PHP 5.1 doesn't.
1421 * Use for passing XHTML fragments to PHP's XML parsing functions
1423 * @return String
1425 static function hackDocType() {
1426 global $wgHtmlEntities;
1427 $out = "<!DOCTYPE html [\n";
1428 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1429 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1431 $out .= "]>\n";
1432 return $out;
1435 static function cleanUrl( $url ) {
1436 # Normalize any HTML entities in input. They will be
1437 # re-escaped by makeExternalLink().
1438 $url = Sanitizer::decodeCharReferences( $url );
1440 # Escape any control characters introduced by the above step
1441 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1443 # Validate hostname portion
1444 $matches = array();
1445 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1446 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1448 // Characters that will be ignored in IDNs.
1449 // http://tools.ietf.org/html/3454#section-3.1
1450 // Strip them before further processing so blacklists and such work.
1451 $strip = "/
1452 \\s| # general whitespace
1453 \xc2\xad| # 00ad SOFT HYPHEN
1454 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1455 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1456 \xe2\x81\xa0| # 2060 WORD JOINER
1457 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1458 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1459 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1460 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1461 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1462 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1463 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1464 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1465 /xuD";
1467 $host = preg_replace( $strip, '', $host );
1469 // @todo Fixme: validate hostnames here
1471 return $protocol . $host . $rest;
1472 } else {
1473 return $url;