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, we will close them
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 = str_replace( '>', '>', array_shift( $bits ) );
391 $tagstack = $tablestack = array();
392 foreach ( $bits as $x ) {
394 if( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
395 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
397 $slash = $t = $params = $brace = $rest = null;
401 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
405 if( isset( $htmlsingleonly[$t] ) ) {
407 } elseif ( ( $ot = @array_pop
( $tagstack ) ) != $t ) {
408 if ( isset( $htmlsingleallowed[$ot] ) ) {
409 # Pop all elements with an optional close tag
410 # and see if we find a match below them
412 array_push ($optstack, $ot);
413 while ( ( ( $ot = @array_pop
( $tagstack ) ) != $t ) &&
414 isset( $htmlsingleallowed[$ot] ) )
416 array_push ($optstack, $ot);
419 # No match. Push the optinal elements back again
421 while ( $ot = @array_pop
( $optstack ) ) {
422 array_push( $tagstack, $ot );
426 @array_push
( $tagstack, $ot );
427 # <li> can be nested in <ul> or <ol>, skip those cases:
428 if(!(isset( $htmllist[$ot] ) && isset( $listtags[$t] ) )) {
433 if ( $t == 'table' ) {
434 $tagstack = array_pop( $tablestack );
439 # Keep track for later
440 if ( isset( $tabletags[$t] ) &&
441 ! in_array( 'table', $tagstack ) ) {
443 } else if ( in_array( $t, $tagstack ) &&
444 ! isset( $htmlnest [$t ] ) ) {
446 #Â Is it a self closed htmlpair ? (bug 5487)
447 } else if( $brace == '/>' &&
448 isset( $htmlpairs[$t] ) ) {
450 } elseif( isset( $htmlsingleonly[$t] ) ) {
451 # Hack to force empty tag for uncloseable elements
453 } else if( isset( $htmlsingle[$t] ) ) {
454 # Hack to not close $htmlsingle tags
456 } else if( isset( $tabletags[$t] )
457 && in_array($t ,$tagstack) ) {
458 // New table tag but forgot to close the previous one
461 if ( $t == 'table' ) {
462 array_push( $tablestack, $tagstack );
465 array_push( $tagstack, $t );
468 # Replace any variables or template parameters with
470 if( is_callable( $processCallback ) ) {
471 call_user_func_array( $processCallback, array( &$params, $args ) );
474 # Strip non-approved attributes from the tag
475 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
478 $rest = str_replace( '>', '>', $rest );
479 $close = ( $brace == '/>' ) ?
' /' : '';
480 $text .= "<$slash$t$newparams$close>$rest";
484 $text .= '<' . str_replace( '>', '>', $x);
486 # Close off any remaining tags
487 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
489 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
492 # this might be possible using tidy itself
493 foreach ( $bits as $x ) {
494 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
496 @list
( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
497 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
498 if( is_callable( $processCallback ) ) {
499 call_user_func_array( $processCallback, array( &$params, $args ) );
501 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
502 $rest = str_replace( '>', '>', $rest );
503 $text .= "<$slash$t$newparams$brace$rest";
505 $text .= '<' . str_replace( '>', '>', $x);
509 wfProfileOut( __METHOD__
);
514 * Remove '<!--', '-->', and everything between.
515 * To avoid leaving blank lines, when a comment is both preceded
516 * and followed by a newline (ignoring spaces), trim leading and
517 * trailing spaces and one of the newlines.
520 * @param string $text
523 static function removeHTMLcomments( $text ) {
524 wfProfileIn( __METHOD__
);
525 while (($start = strpos($text, '<!--')) !== false) {
526 $end = strpos($text, '-->', $start +
4);
527 if ($end === false) {
528 # Unterminated comment; bail out
534 # Trim space and newline if the comment is both
535 # preceded and followed by a newline
536 $spaceStart = max($start - 1, 0);
537 $spaceLen = $end - $spaceStart;
538 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
542 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
544 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
545 # Remove the comment, leading and trailing
546 # spaces, and leave only one newline.
547 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
550 # Remove just the comment.
551 $text = substr_replace($text, '', $start, $end - $start);
554 wfProfileOut( __METHOD__
);
559 * Take an array of attribute names and values and normalize or discard
560 * illegal values for the given element type.
562 * - Discards attributes not on a whitelist for the given element
563 * - Unsafe style attributes are discarded
565 * @param array $attribs
566 * @param string $element
569 * @todo Check for legal values where the DTD limits things.
570 * @todo Check for unique id attribute :P
572 static function validateTagAttributes( $attribs, $element ) {
573 $whitelist = array_flip( Sanitizer
::attributeWhitelist( $element ) );
575 foreach( $attribs as $attribute => $value ) {
576 if( !isset( $whitelist[$attribute] ) ) {
579 # Strip javascript "expression" from stylesheets.
580 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
581 if( $attribute == 'style' ) {
582 $value = Sanitizer
::checkCss( $value );
583 if( $value === false ) {
589 if ( $attribute === 'id' )
590 $value = Sanitizer
::escapeId( $value );
592 // If this attribute was previously set, override it.
593 // Output should only have one attribute of each name.
594 $out[$attribute] = $value;
600 * Pick apart some CSS and check it for forbidden or unsafe structures.
601 * Returns a sanitized string, or false if it was just too evil.
603 * Currently URL references, 'expression', 'tps' are forbidden.
605 * @param string $value
608 static function checkCss( $value ) {
609 $stripped = Sanitizer
::decodeCharReferences( $value );
611 // Remove any comments; IE gets token splitting wrong
612 $stripped = StringUtils
::delimiterReplace( '/*', '*/', ' ', $stripped );
616 // ... and continue checks
617 $stripped = preg_replace( '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!e',
618 'codepointToUtf8(hexdec("$1"))', $stripped );
619 $stripped = str_replace( '\\', '', $stripped );
620 if( preg_match( '/(expression|tps*:\/\/|url\\s*\().*/is',
630 * Take a tag soup fragment listing an HTML element's attributes
631 * and normalize it to well-formed XML, discarding unwanted attributes.
632 * Output is safe for further wikitext processing, with escaping of
633 * values that could trigger problems.
635 * - Normalizes attribute names to lowercase
636 * - Discards attributes not on a whitelist for the given element
637 * - Turns broken or invalid entities into plaintext
638 * - Double-quotes all attribute values
639 * - Attributes without values are given the name as attribute
640 * - Double attributes are discarded
641 * - Unsafe style attributes are discarded
642 * - Prepends space if there are attributes.
644 * @param string $text
645 * @param string $element
648 static function fixTagAttributes( $text, $element ) {
649 if( trim( $text ) == '' ) {
653 $stripped = Sanitizer
::validateTagAttributes(
654 Sanitizer
::decodeTagAttributes( $text ), $element );
657 foreach( $stripped as $attribute => $value ) {
658 $encAttribute = htmlspecialchars( $attribute );
659 $encValue = Sanitizer
::safeEncodeAttribute( $value );
661 $attribs[] = "$encAttribute=\"$encValue\"";
663 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
667 * Encode an attribute value for HTML output.
669 * @return HTML-encoded text fragment
671 static function encodeAttribute( $text ) {
672 $encValue = htmlspecialchars( $text );
674 // Whitespace is normalized during attribute decoding,
675 // so if we've been passed non-spaces we must encode them
676 // ahead of time or they won't be preserved.
677 $encValue = strtr( $encValue, array(
687 * Encode an attribute value for HTML tags, with extra armoring
688 * against further wiki processing.
690 * @return HTML-encoded text fragment
692 static function safeEncodeAttribute( $text ) {
693 $encValue = Sanitizer
::encodeAttribute( $text );
695 # Templates and links may be expanded in later parsing,
696 # creating invalid or dangerous output. Suppress this.
697 $encValue = strtr( $encValue, array(
698 '<' => '<', // This should never happen,
699 '>' => '>', // we've received invalid input
700 '"' => '"', // which should have been escaped.
703 "''" => '''',
704 'ISBN' => 'ISBN',
706 'PMID' => 'PMID',
712 $encValue = preg_replace_callback(
713 '/(' . wfUrlProtocols() . ')/',
714 array( 'Sanitizer', 'armorLinksCallback' ),
720 * Given a value escape it so that it can be used in an id attribute and
721 * return it, this does not validate the value however (see first link)
723 * @link http://www.w3.org/TR/html401/types.html#type-name Valid characters
726 * @link http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
735 static function escapeId( $id ) {
736 static $replace = array(
741 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
743 return str_replace( array_keys( $replace ), array_values( $replace ), $id );
747 * Given a value, escape it so that it can be used as a CSS class and
750 * @todo For extra validity, input should be validated UTF-8.
752 * @link http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
754 * @param string $class
757 static function escapeClass( $class ) {
758 // Convert ugly stuff to underscores and kill underscores in ugly places
759 return rtrim(preg_replace(
760 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
766 * Regex replace callback for armoring links against further processing.
767 * @param array $matches
771 private static function armorLinksCallback( $matches ) {
772 return str_replace( ':', ':', $matches[1] );
776 * Return an associative array of attribute names and values from
777 * a partial tag string. Attribute names are forces to lowercase,
778 * character references are decoded to UTF-8 text.
783 static function decodeTagAttributes( $text ) {
786 if( trim( $text ) == '' ) {
799 foreach( $pairs as $set ) {
800 $attribute = strtolower( $set[1] );
801 $value = Sanitizer
::getTagAttributeCallback( $set );
803 // Normalize whitespace
804 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
805 $value = trim( $value );
807 // Decode character references
808 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
814 * Pick the appropriate attribute value from a match set from the
815 * MW_ATTRIBS_REGEX matches.
821 private static function getTagAttributeCallback( $set ) {
822 if( isset( $set[6] ) ) {
823 # Illegal #XXXXXX color with no quotes.
825 } elseif( isset( $set[5] ) ) {
828 } elseif( isset( $set[4] ) ) {
831 } elseif( isset( $set[3] ) ) {
834 } elseif( !isset( $set[2] ) ) {
835 # In XHTML, attributes must have a value.
836 # For 'reduced' form, return explicitly the attribute name here.
839 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
844 * Normalize whitespace and character references in an XML source-
845 * encoded text for an attribute value.
847 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
848 * but note that we're not returning the value, but are returning
849 * XML source fragments that will be slapped into output.
851 * @param string $text
855 private static function normalizeAttributeValue( $text ) {
856 return str_replace( '"', '"',
858 '/\r\n|[\x20\x0d\x0a\x09]/',
860 Sanitizer
::normalizeCharReferences( $text ) ) );
864 * Ensure that any entities and character references are legal
865 * for XML and XHTML specifically. Any stray bits will be
866 * &-escaped to result in a valid text fragment.
868 * a. any named char refs must be known in XHTML
869 * b. any numeric char refs must be legal chars, not invalid or forbidden
870 * c. use &#x, not &#X
871 * d. fix or reject non-valid attributes
873 * @param string $text
877 static function normalizeCharReferences( $text ) {
878 return preg_replace_callback(
880 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
884 * @param string $matches
887 static function normalizeCharReferencesCallback( $matches ) {
889 if( $matches[1] != '' ) {
890 $ret = Sanitizer
::normalizeEntity( $matches[1] );
891 } elseif( $matches[2] != '' ) {
892 $ret = Sanitizer
::decCharReference( $matches[2] );
893 } elseif( $matches[3] != '' ) {
894 $ret = Sanitizer
::hexCharReference( $matches[3] );
895 } elseif( $matches[4] != '' ) {
896 $ret = Sanitizer
::hexCharReference( $matches[4] );
898 if( is_null( $ret ) ) {
899 return htmlspecialchars( $matches[0] );
906 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
907 * return the named entity reference as is. Otherwise, returns
908 * HTML-escaped text of pseudo-entity source (eg &foo;)
910 * @param string $name
914 static function normalizeEntity( $name ) {
915 global $wgHtmlEntities;
916 if( isset( $wgHtmlEntities[$name] ) ) {
919 return "&$name;";
923 static function decCharReference( $codepoint ) {
924 $point = intval( $codepoint );
925 if( Sanitizer
::validateCodepoint( $point ) ) {
926 return sprintf( '&#%d;', $point );
932 static function hexCharReference( $codepoint ) {
933 $point = hexdec( $codepoint );
934 if( Sanitizer
::validateCodepoint( $point ) ) {
935 return sprintf( '&#x%x;', $point );
942 * Returns true if a given Unicode codepoint is a valid character in XML.
943 * @param int $codepoint
946 private static function validateCodepoint( $codepoint ) {
947 return ($codepoint == 0x09)
948 ||
($codepoint == 0x0a)
949 ||
($codepoint == 0x0d)
950 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
951 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
952 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
956 * Decode any character references, numeric or named entities,
957 * in the text and return a UTF-8 string.
959 * @param string $text
964 public static function decodeCharReferences( $text ) {
965 return preg_replace_callback(
967 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
972 * @param string $matches
975 static function decodeCharReferencesCallback( $matches ) {
976 if( $matches[1] != '' ) {
977 return Sanitizer
::decodeEntity( $matches[1] );
978 } elseif( $matches[2] != '' ) {
979 return Sanitizer
::decodeChar( intval( $matches[2] ) );
980 } elseif( $matches[3] != '' ) {
981 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
982 } elseif( $matches[4] != '' ) {
983 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
985 # Last case should be an ampersand by itself
990 * Return UTF-8 string for a codepoint if that is a valid
991 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
992 * @param int $codepoint
996 static function decodeChar( $codepoint ) {
997 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
998 return codepointToUtf8( $codepoint );
1000 return UTF8_REPLACEMENT
;
1005 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1006 * return the UTF-8 encoding of that character. Otherwise, returns
1007 * pseudo-entity source (eg &foo;)
1009 * @param string $name
1012 static function decodeEntity( $name ) {
1013 global $wgHtmlEntities;
1014 if( isset( $wgHtmlEntities[$name] ) ) {
1015 return codepointToUtf8( $wgHtmlEntities[$name] );
1022 * Fetch the whitelist of acceptable attributes for a given
1025 * @param string $element
1028 static function attributeWhitelist( $element ) {
1030 if( !isset( $list ) ) {
1031 $list = Sanitizer
::setupAttributeWhitelist();
1033 return isset( $list[$element] )
1039 * @todo Document it a bit
1042 static function setupAttributeWhitelist() {
1043 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1044 $block = array_merge( $common, array( 'align' ) );
1045 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1046 $tablecell = array( 'abbr',
1052 'nowrap', # deprecated
1053 'width', # deprecated
1054 'height', # deprecated
1055 'bgcolor' # deprecated
1058 # Numbers refer to sections in HTML 4.01 standard describing the element.
1059 # See: http://www.w3.org/TR/html4/
1060 $whitelist = array (
1063 'center' => $common, # deprecated
1064 'span' => $block, # ??
1082 'strong' => $common,
1093 'blockquote' => array_merge( $common, array( 'cite' ) ),
1104 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1107 'pre' => array_merge( $common, array( 'width' ) ),
1110 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1111 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1114 'ul' => array_merge( $common, array( 'type' ) ),
1115 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1116 'li' => array_merge( $common, array( 'type', 'value' ) ),
1124 'table' => array_merge( $common,
1125 array( 'summary', 'width', 'border', 'frame',
1126 'rules', 'cellspacing', 'cellpadding',
1131 'caption' => array_merge( $common, array( 'align' ) ),
1134 'thead' => array_merge( $common, $tablealign ),
1135 'tfoot' => array_merge( $common, $tablealign ),
1136 'tbody' => array_merge( $common, $tablealign ),
1139 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1140 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1143 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1146 'td' => array_merge( $common, $tablecell, $tablealign ),
1147 'th' => array_merge( $common, $tablecell, $tablealign ),
1155 'strike' => $common,
1160 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1164 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1166 # XHTML Ruby annotation text module, simple ruby only.
1167 # http://www.w3c.org/TR/ruby/
1172 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1179 * Take a fragment of (potentially invalid) HTML and return
1180 * a version with any tags removed, encoded suitably for literal
1181 * inclusion in an attribute value.
1183 * @param string $text HTML fragment
1186 static function stripAllTags( $text ) {
1188 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
1190 # Normalize &entities and whitespace
1191 $text = Sanitizer
::normalizeAttributeValue( $text );
1193 # Will be placed into "double-quoted" attributes,
1194 # make sure remaining bits are safe.
1195 $text = str_replace(
1196 array('<', '>', '"'),
1197 array('<', '>', '"'),
1204 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1205 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1208 * Use for passing XHTML fragments to PHP's XML parsing functions
1213 static function hackDocType() {
1214 global $wgHtmlEntities;
1215 $out = "<!DOCTYPE html [\n";
1216 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1217 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1223 static function cleanUrl( $url, $hostname=true ) {
1224 # Normalize any HTML entities in input. They will be
1225 # re-escaped by makeExternalLink().
1226 $url = Sanitizer
::decodeCharReferences( $url );
1228 # Escape any control characters introduced by the above step
1229 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1231 # Validate hostname portion
1233 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1234 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1236 // Characters that will be ignored in IDNs.
1237 // http://tools.ietf.org/html/3454#section-3.1
1238 // Strip them before further processing so blacklists and such work.
1240 \\s| # general whitespace
1241 \xc2\xad| # 00ad SOFT HYPHEN
1242 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1243 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1244 \xe2\x81\xa0| # 2060 WORD JOINER
1245 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1246 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1247 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1248 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1249 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1250 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1251 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1252 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1255 $host = preg_replace( $strip, '', $host );
1257 // @fixme: validate hostnames here
1259 return $protocol . $host . $rest;