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
28 * Regular expression to match various types of character references in
29 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
31 define( 'MW_CHAR_REFS_REGEX',
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)($attrib+)
49 # The attribute value: quoted or alone
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" );
60 * List of all named character entities defined in HTML 4.01
61 * http://www.w3.org/TR/html4/sgml/entities.html
64 global $wgHtmlEntities;
65 $wgHtmlEntities = array(
319 /** @package MediaWiki */
322 * Cleans up HTML, removes dangerous tags and attributes, and
323 * removes HTML comments
325 * @param string $text
326 * @param callback $processCallback to do any variable or parameter replacements in HTML attribute values
327 * @param array $args for the processing callback
330 static function removeHTMLtags( $text, $processCallback = null, $args = array() ) {
331 global $wgUseTidy, $wgUserHtml;
333 static $htmlpairs, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
334 $htmllist, $listtags, $htmlsingleallowed, $htmlelements, $staticInitialised;
336 wfProfileIn( __METHOD__
);
338 if ( !$staticInitialised ) {
340 $htmlpairs = array( # Tags that must be closed
341 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
342 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
343 'strike', 'strong', 'tt', 'var', 'div', 'center',
344 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
345 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span', 'u'
348 'br', 'hr', 'li', 'dt', 'dd'
350 $htmlsingleonly = array( # Elements that cannot have close tags
353 $htmlnest = array( # Tags that can be nested--??
354 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
355 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
357 $tabletags = array( # Can only appear inside table
360 $htmllist = array( # Tags used by list
363 $listtags = array( # Tags that can appear in a list
368 $htmlpairs = array();
369 $htmlsingle = array();
371 $tabletags = array();
374 $htmlsingleallowed = array_merge( $htmlsingle, $tabletags );
375 $htmlelements = array_merge( $htmlsingle, $htmlpairs, $htmlnest );
377 # Convert them all to hashtables for faster lookup
378 $vars = array( 'htmlpairs', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
379 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelements' );
380 foreach ( $vars as $var ) {
381 $
$var = array_flip( $
$var );
383 $staticInitialised = true;
386 # Remove HTML comments
387 $text = Sanitizer
::removeHTMLcomments( $text );
388 $bits = explode( '<', $text );
389 $text = array_shift( $bits );
391 $tagstack = $tablestack = array();
392 foreach ( $bits as $x ) {
393 $prev = error_reporting( E_ALL
& ~
( E_NOTICE | E_WARNING
) );
394 preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs );
395 list( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
396 error_reporting( $prev );
399 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
403 if( isset( $htmlsingleonly[$t] ) ) {
405 } elseif ( ( $ot = @array_pop
( $tagstack ) ) != $t ) {
406 if ( isset( $htmlsingleallowed[$ot] ) ) {
407 # Pop all elements with an optional close tag
408 # and see if we find a match below them
410 array_push ($optstack, $ot);
411 while ( ( ( $ot = @array_pop
( $tagstack ) ) != $t ) &&
412 isset( $htmlsingleallowed[$ot] ) )
414 array_push ($optstack, $ot);
417 # No match. Push the optinal elements back again
419 while ( $ot = @array_pop
( $optstack ) ) {
420 array_push( $tagstack, $ot );
424 @array_push
( $tagstack, $ot );
425 # <li> can be nested in <ul> or <ol>, skip those cases:
426 if(!(isset( $htmllist[$ot] ) && isset( $listtags[$t] ) )) {
431 if ( $t == 'table' ) {
432 $tagstack = array_pop( $tablestack );
437 # Keep track for later
438 if ( isset( $tabletags[$t] ) &&
439 ! in_array( 'table', $tagstack ) ) {
441 } else if ( in_array( $t, $tagstack ) &&
442 ! isset( $htmlnest [$t ] ) ) {
444 #Â Is it a self closed htmlpair ? (bug 5487)
445 } else if( $brace == '/>' &&
446 isset( $htmlpairs[$t] ) ) {
448 } elseif( isset( $htmlsingleonly[$t] ) ) {
449 # Hack to force empty tag for uncloseable elements
451 } else if( isset( $htmlsingle[$t] ) ) {
452 # Hack to not close $htmlsingle tags
455 if ( $t == 'table' ) {
456 array_push( $tablestack, $tagstack );
459 array_push( $tagstack, $t );
462 # Replace any variables or template parameters with
464 if( is_callable( $processCallback ) ) {
465 call_user_func_array( $processCallback, array( &$params, $args ) );
468 # Strip non-approved attributes from the tag
469 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
472 $rest = str_replace( '>', '>', $rest );
473 $close = ( $brace == '/>' ) ?
' /' : '';
474 $text .= "<$slash$t$newparams$close>$rest";
478 $text .= '<' . str_replace( '>', '>', $x);
480 # Close off any remaining tags
481 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
483 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
486 # this might be possible using tidy itself
487 foreach ( $bits as $x ) {
488 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
490 @list
( $qbar, $slash, $t, $params, $brace, $rest ) = $regs;
491 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
492 if( is_callable( $processCallback ) ) {
493 call_user_func_array( $processCallback, array( &$params, $args ) );
495 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
496 $rest = str_replace( '>', '>', $rest );
497 $text .= "<$slash$t$newparams$brace$rest";
499 $text .= '<' . str_replace( '>', '>', $x);
503 wfProfileOut( __METHOD__
);
508 * Remove '<!--', '-->', and everything between.
509 * To avoid leaving blank lines, when a comment is both preceded
510 * and followed by a newline (ignoring spaces), trim leading and
511 * trailing spaces and one of the newlines.
514 * @param string $text
517 static function removeHTMLcomments( $text ) {
518 wfProfileIn( __METHOD__
);
519 while (($start = strpos($text, '<!--')) !== false) {
520 $end = strpos($text, '-->', $start +
4);
521 if ($end === false) {
522 # Unterminated comment; bail out
528 # Trim space and newline if the comment is both
529 # preceded and followed by a newline
530 $spaceStart = max($start - 1, 0);
531 $spaceLen = $end - $spaceStart;
532 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
536 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
538 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
539 # Remove the comment, leading and trailing
540 # spaces, and leave only one newline.
541 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
544 # Remove just the comment.
545 $text = substr_replace($text, '', $start, $end - $start);
548 wfProfileOut( __METHOD__
);
553 * Take an array of attribute names and values and normalize or discard
554 * illegal values for the given element type.
556 * - Discards attributes not on a whitelist for the given element
557 * - Unsafe style attributes are discarded
559 * @param array $attribs
560 * @param string $element
563 * @todo Check for legal values where the DTD limits things.
564 * @todo Check for unique id attribute :P
566 static function validateTagAttributes( $attribs, $element ) {
567 $whitelist = array_flip( Sanitizer
::attributeWhitelist( $element ) );
569 foreach( $attribs as $attribute => $value ) {
570 if( !isset( $whitelist[$attribute] ) ) {
573 # Strip javascript "expression" from stylesheets.
574 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
575 if( $attribute == 'style' ) {
576 $value = Sanitizer
::checkCss( $value );
577 if( $value === false ) {
583 if ( $attribute === 'id' )
584 $value = Sanitizer
::escapeId( $value );
586 // If this attribute was previously set, override it.
587 // Output should only have one attribute of each name.
588 $out[$attribute] = $value;
594 * Pick apart some CSS and check it for forbidden or unsafe structures.
595 * Returns a sanitized string, or false if it was just too evil.
597 * Currently URL references, 'expression', 'tps' are forbidden.
599 * @param string $value
602 static function checkCss( $value ) {
603 $stripped = Sanitizer
::decodeCharReferences( $value );
605 // Remove any comments; IE gets token splitting wrong
606 $stripped = StringUtils
::delimiterReplace( '/*', '*/', ' ', $stripped );
610 // ... and continue checks
611 $stripped = preg_replace( '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!e',
612 'codepointToUtf8(hexdec("$1"))', $stripped );
613 $stripped = str_replace( '\\', '', $stripped );
614 if( preg_match( '/(expression|tps*:\/\/|url\\s*\().*/is',
624 * Take a tag soup fragment listing an HTML element's attributes
625 * and normalize it to well-formed XML, discarding unwanted attributes.
626 * Output is safe for further wikitext processing, with escaping of
627 * values that could trigger problems.
629 * - Normalizes attribute names to lowercase
630 * - Discards attributes not on a whitelist for the given element
631 * - Turns broken or invalid entities into plaintext
632 * - Double-quotes all attribute values
633 * - Attributes without values are given the name as attribute
634 * - Double attributes are discarded
635 * - Unsafe style attributes are discarded
636 * - Prepends space if there are attributes.
638 * @param string $text
639 * @param string $element
642 static function fixTagAttributes( $text, $element ) {
643 if( trim( $text ) == '' ) {
647 $stripped = Sanitizer
::validateTagAttributes(
648 Sanitizer
::decodeTagAttributes( $text ), $element );
651 foreach( $stripped as $attribute => $value ) {
652 $encAttribute = htmlspecialchars( $attribute );
653 $encValue = Sanitizer
::safeEncodeAttribute( $value );
655 $attribs[] = "$encAttribute=\"$encValue\"";
657 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
661 * Encode an attribute value for HTML output.
663 * @return HTML-encoded text fragment
665 static function encodeAttribute( $text ) {
666 $encValue = htmlspecialchars( $text );
668 // Whitespace is normalized during attribute decoding,
669 // so if we've been passed non-spaces we must encode them
670 // ahead of time or they won't be preserved.
671 $encValue = strtr( $encValue, array(
681 * Encode an attribute value for HTML tags, with extra armoring
682 * against further wiki processing.
684 * @return HTML-encoded text fragment
686 static function safeEncodeAttribute( $text ) {
687 $encValue = Sanitizer
::encodeAttribute( $text );
689 # Templates and links may be expanded in later parsing,
690 # creating invalid or dangerous output. Suppress this.
691 $encValue = strtr( $encValue, array(
692 '<' => '<', // This should never happen,
693 '>' => '>', // we've received invalid input
694 '"' => '"', // which should have been escaped.
697 "''" => '''',
698 'ISBN' => 'ISBN',
700 'PMID' => 'PMID',
706 $encValue = preg_replace_callback(
707 '/(' . wfUrlProtocols() . ')/',
708 array( 'Sanitizer', 'armorLinksCallback' ),
714 * Given a value escape it so that it can be used in an id attribute and
715 * return it, this does not validate the value however (see first link)
717 * @link http://www.w3.org/TR/html401/types.html#type-name Valid characters
720 * @link http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
729 static function escapeId( $id ) {
730 static $replace = array(
735 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
737 return str_replace( array_keys( $replace ), array_values( $replace ), $id );
741 * Given a value, escape it so that it can be used as a CSS class and
744 * TODO: For extra validity, input should be validated UTF-8.
746 * @link http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
748 * @param string $class
751 static function escapeClass( $class ) {
752 // Convert ugly stuff to underscores and kill underscores in ugly places
753 return rtrim(preg_replace(
754 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
760 * Regex replace callback for armoring links against further processing.
761 * @param array $matches
765 private static function armorLinksCallback( $matches ) {
766 return str_replace( ':', ':', $matches[1] );
770 * Return an associative array of attribute names and values from
771 * a partial tag string. Attribute names are forces to lowercase,
772 * character references are decoded to UTF-8 text.
777 static function decodeTagAttributes( $text ) {
780 if( trim( $text ) == '' ) {
793 foreach( $pairs as $set ) {
794 $attribute = strtolower( $set[1] );
795 $value = Sanitizer
::getTagAttributeCallback( $set );
797 // Normalize whitespace
798 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
799 $value = trim( $value );
801 // Decode character references
802 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
808 * Pick the appropriate attribute value from a match set from the
809 * MW_ATTRIBS_REGEX matches.
815 private static function getTagAttributeCallback( $set ) {
816 if( isset( $set[6] ) ) {
817 # Illegal #XXXXXX color with no quotes.
819 } elseif( isset( $set[5] ) ) {
822 } elseif( isset( $set[4] ) ) {
825 } elseif( isset( $set[3] ) ) {
828 } elseif( !isset( $set[2] ) ) {
829 # In XHTML, attributes must have a value.
830 # For 'reduced' form, return explicitly the attribute name here.
833 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
838 * Normalize whitespace and character references in an XML source-
839 * encoded text for an attribute value.
841 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
842 * but note that we're not returning the value, but are returning
843 * XML source fragments that will be slapped into output.
845 * @param string $text
849 private static function normalizeAttributeValue( $text ) {
850 return str_replace( '"', '"',
852 '/\r\n|[\x20\x0d\x0a\x09]/',
854 Sanitizer
::normalizeCharReferences( $text ) ) );
858 * Ensure that any entities and character references are legal
859 * for XML and XHTML specifically. Any stray bits will be
860 * &-escaped to result in a valid text fragment.
862 * a. any named char refs must be known in XHTML
863 * b. any numeric char refs must be legal chars, not invalid or forbidden
864 * c. use &#x, not &#X
865 * d. fix or reject non-valid attributes
867 * @param string $text
871 static function normalizeCharReferences( $text ) {
872 return preg_replace_callback(
874 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
878 * @param string $matches
881 static function normalizeCharReferencesCallback( $matches ) {
883 if( $matches[1] != '' ) {
884 $ret = Sanitizer
::normalizeEntity( $matches[1] );
885 } elseif( $matches[2] != '' ) {
886 $ret = Sanitizer
::decCharReference( $matches[2] );
887 } elseif( $matches[3] != '' ) {
888 $ret = Sanitizer
::hexCharReference( $matches[3] );
889 } elseif( $matches[4] != '' ) {
890 $ret = Sanitizer
::hexCharReference( $matches[4] );
892 if( is_null( $ret ) ) {
893 return htmlspecialchars( $matches[0] );
900 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
901 * return the named entity reference as is. Otherwise, returns
902 * HTML-escaped text of pseudo-entity source (eg &foo;)
904 * @param string $name
908 static function normalizeEntity( $name ) {
909 global $wgHtmlEntities;
910 if( isset( $wgHtmlEntities[$name] ) ) {
913 return "&$name;";
917 static function decCharReference( $codepoint ) {
918 $point = intval( $codepoint );
919 if( Sanitizer
::validateCodepoint( $point ) ) {
920 return sprintf( '&#%d;', $point );
926 static function hexCharReference( $codepoint ) {
927 $point = hexdec( $codepoint );
928 if( Sanitizer
::validateCodepoint( $point ) ) {
929 return sprintf( '&#x%x;', $point );
936 * Returns true if a given Unicode codepoint is a valid character in XML.
937 * @param int $codepoint
940 private static function validateCodepoint( $codepoint ) {
941 return ($codepoint == 0x09)
942 ||
($codepoint == 0x0a)
943 ||
($codepoint == 0x0d)
944 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
945 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
946 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
950 * Decode any character references, numeric or named entities,
951 * in the text and return a UTF-8 string.
953 * @param string $text
958 public static function decodeCharReferences( $text ) {
959 return preg_replace_callback(
961 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
966 * @param string $matches
969 static function decodeCharReferencesCallback( $matches ) {
970 if( $matches[1] != '' ) {
971 return Sanitizer
::decodeEntity( $matches[1] );
972 } elseif( $matches[2] != '' ) {
973 return Sanitizer
::decodeChar( intval( $matches[2] ) );
974 } elseif( $matches[3] != '' ) {
975 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
976 } elseif( $matches[4] != '' ) {
977 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
979 # Last case should be an ampersand by itself
984 * Return UTF-8 string for a codepoint if that is a valid
985 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
986 * @param int $codepoint
990 static function decodeChar( $codepoint ) {
991 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
992 return codepointToUtf8( $codepoint );
994 return UTF8_REPLACEMENT
;
999 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1000 * return the UTF-8 encoding of that character. Otherwise, returns
1001 * pseudo-entity source (eg &foo;)
1003 * @param string $name
1006 static function decodeEntity( $name ) {
1007 global $wgHtmlEntities;
1008 if( isset( $wgHtmlEntities[$name] ) ) {
1009 return codepointToUtf8( $wgHtmlEntities[$name] );
1016 * Fetch the whitelist of acceptable attributes for a given
1019 * @param string $element
1022 static function attributeWhitelist( $element ) {
1024 if( !isset( $list ) ) {
1025 $list = Sanitizer
::setupAttributeWhitelist();
1027 return isset( $list[$element] )
1033 * @todo Document it a bit
1036 static function setupAttributeWhitelist() {
1037 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1038 $block = array_merge( $common, array( 'align' ) );
1039 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1040 $tablecell = array( 'abbr',
1046 'nowrap', # deprecated
1047 'width', # deprecated
1048 'height', # deprecated
1049 'bgcolor' # deprecated
1052 # Numbers refer to sections in HTML 4.01 standard describing the element.
1053 # See: http://www.w3.org/TR/html4/
1054 $whitelist = array (
1057 'center' => $common, # deprecated
1058 'span' => $block, # ??
1076 'strong' => $common,
1087 'blockquote' => array_merge( $common, array( 'cite' ) ),
1098 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1101 'pre' => array_merge( $common, array( 'width' ) ),
1104 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1105 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1108 'ul' => array_merge( $common, array( 'type' ) ),
1109 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1110 'li' => array_merge( $common, array( 'type', 'value' ) ),
1118 'table' => array_merge( $common,
1119 array( 'summary', 'width', 'border', 'frame',
1120 'rules', 'cellspacing', 'cellpadding',
1125 'caption' => array_merge( $common, array( 'align' ) ),
1128 'thead' => array_merge( $common, $tablealign ),
1129 'tfoot' => array_merge( $common, $tablealign ),
1130 'tbody' => array_merge( $common, $tablealign ),
1133 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1134 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1137 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1140 'td' => array_merge( $common, $tablecell, $tablealign ),
1141 'th' => array_merge( $common, $tablecell, $tablealign ),
1149 'strike' => $common,
1154 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1158 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1160 # XHTML Ruby annotation text module, simple ruby only.
1161 # http://www.w3c.org/TR/ruby/
1166 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1173 * Take a fragment of (potentially invalid) HTML and return
1174 * a version with any tags removed, encoded suitably for literal
1175 * inclusion in an attribute value.
1177 * @param string $text HTML fragment
1180 static function stripAllTags( $text ) {
1182 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
1184 # Normalize &entities and whitespace
1185 $text = Sanitizer
::normalizeAttributeValue( $text );
1187 # Will be placed into "double-quoted" attributes,
1188 # make sure remaining bits are safe.
1189 $text = str_replace(
1190 array('<', '>', '"'),
1191 array('<', '>', '"'),
1198 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1199 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1202 * Use for passing XHTML fragments to PHP's XML parsing functions
1207 static function hackDocType() {
1208 global $wgHtmlEntities;
1209 $out = "<!DOCTYPE html [\n";
1210 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1211 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1217 static function cleanUrl( $url, $hostname=true ) {
1218 # Normalize any HTML entities in input. They will be
1219 # re-escaped by makeExternalLink().
1220 $url = Sanitizer
::decodeCharReferences( $url );
1222 # Escape any control characters introduced by the above step
1223 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1225 # Validate hostname portion
1226 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1227 list( $whole, $protocol, $host, $rest ) = $matches;
1229 // Characters that will be ignored in IDNs.
1230 // http://tools.ietf.org/html/3454#section-3.1
1231 // Strip them before further processing so blacklists and such work.
1233 \\s| # general whitespace
1234 \xc2\xad| # 00ad SOFT HYPHEN
1235 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1236 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1237 \xe2\x81\xa0| # 2060 WORD JOINER
1238 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1239 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1240 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1241 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1242 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1243 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1244 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1245 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1248 $host = preg_replace( $strip, '', $host );
1250 // @fixme: validate hostnames here
1252 return $protocol . $host . $rest;