ebb0dcccaef409c09e330d04aabcc10853469876
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
27 * Regular expression to match various types of character references in
28 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
30 define( 'MW_CHAR_REFS_REGEX',
38 * Regular expression to match HTML/XML attribute pairs within a tag.
39 * Allows some... latitude.
40 * Used in Sanitizer::fixTagAttributes and Sanitizer::decodeTagAttributes
42 $attrib = '[A-Za-z0-9]';
43 $space = '[\x09\x0a\x0d\x20]';
44 define( 'MW_ATTRIBS_REGEX',
45 "/(?:^|$space)($attrib+)
48 # The attribute value: quoted or alone
51 | ([a-zA-Z0-9!#$%&()*,\\-.\\/:;<>?@[\\]^_`{|}~]+)
52 | (\#[0-9a-fA-F]+) # Technically wrong, but lots of
53 # colors are specified like this.
54 # We'll be normalizing it.
56 )?(?=$space|\$)/sx" );
59 * List of all named character entities defined in HTML 4.01
60 * http://www.w3.org/TR/html4/sgml/entities.html
63 global $wgHtmlEntities;
64 $wgHtmlEntities = array(
319 * XHTML sanitizer for MediaWiki
324 * Cleans up HTML, removes dangerous tags and attributes, and
325 * removes HTML comments
327 * @param string $text
328 * @param callback $processCallback to do any variable or parameter replacements in HTML attribute values
329 * @param array $args for the processing callback
332 static function removeHTMLtags( $text, $processCallback = null, $args = array() ) {
335 static $htmlpairs, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
336 $htmllist, $listtags, $htmlsingleallowed, $htmlelements, $staticInitialised;
338 wfProfileIn( __METHOD__
);
340 if ( !$staticInitialised ) {
342 $htmlpairs = array( # Tags that must be closed
343 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
344 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
345 'strike', 'strong', 'tt', 'var', 'div', 'center',
346 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
347 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span', 'u'
350 'br', 'hr', 'li', 'dt', 'dd'
352 $htmlsingleonly = array( # Elements that cannot have close tags
355 $htmlnest = array( # Tags that can be nested--??
356 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
357 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
359 $tabletags = array( # Can only appear inside table, we will close them
362 $htmllist = array( # Tags used by list
365 $listtags = array( # Tags that can appear in a list
369 $htmlsingleallowed = array_merge( $htmlsingle, $tabletags );
370 $htmlelements = array_merge( $htmlsingle, $htmlpairs, $htmlnest );
372 # Convert them all to hashtables for faster lookup
373 $vars = array( 'htmlpairs', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
374 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelements' );
375 foreach ( $vars as $var ) {
376 $
$var = array_flip( $
$var );
378 $staticInitialised = true;
381 # Remove HTML comments
382 $text = Sanitizer
::removeHTMLcomments( $text );
383 $bits = explode( '<', $text );
384 $text = str_replace( '>', '>', array_shift( $bits ) );
386 $tagstack = $tablestack = array();
387 foreach ( $bits as $x ) {
389 if( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
390 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
392 $slash = $t = $params = $brace = $rest = null;
396 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
400 if( isset( $htmlsingleonly[$t] ) ) {
402 } elseif ( ( $ot = @array_pop
( $tagstack ) ) != $t ) {
403 if ( isset( $htmlsingleallowed[$ot] ) ) {
404 # Pop all elements with an optional close tag
405 # and see if we find a match below them
407 array_push ($optstack, $ot);
408 while ( ( ( $ot = @array_pop
( $tagstack ) ) != $t ) &&
409 isset( $htmlsingleallowed[$ot] ) )
411 array_push ($optstack, $ot);
414 # No match. Push the optinal elements back again
416 while ( $ot = @array_pop
( $optstack ) ) {
417 array_push( $tagstack, $ot );
421 @array_push
( $tagstack, $ot );
422 # <li> can be nested in <ul> or <ol>, skip those cases:
423 if(!(isset( $htmllist[$ot] ) && isset( $listtags[$t] ) )) {
428 if ( $t == 'table' ) {
429 $tagstack = array_pop( $tablestack );
434 # Keep track for later
435 if ( isset( $tabletags[$t] ) &&
436 ! in_array( 'table', $tagstack ) ) {
438 } else if ( in_array( $t, $tagstack ) &&
439 ! isset( $htmlnest [$t ] ) ) {
441 #Â Is it a self closed htmlpair ? (bug 5487)
442 } else if( $brace == '/>' &&
443 isset( $htmlpairs[$t] ) ) {
445 } elseif( isset( $htmlsingleonly[$t] ) ) {
446 # Hack to force empty tag for uncloseable elements
448 } else if( isset( $htmlsingle[$t] ) ) {
449 # Hack to not close $htmlsingle tags
451 } else if( isset( $tabletags[$t] )
452 && in_array($t ,$tagstack) ) {
453 // New table tag but forgot to close the previous one
456 if ( $t == 'table' ) {
457 array_push( $tablestack, $tagstack );
460 array_push( $tagstack, $t );
463 # Replace any variables or template parameters with
465 if( is_callable( $processCallback ) ) {
466 call_user_func_array( $processCallback, array( &$params, $args ) );
469 # Strip non-approved attributes from the tag
470 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
473 $rest = str_replace( '>', '>', $rest );
474 $close = ( $brace == '/>' && !$slash ) ?
' /' : '';
475 $text .= "<$slash$t$newparams$close>$rest";
479 $text .= '<' . str_replace( '>', '>', $x);
481 # Close off any remaining tags
482 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
484 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
487 # this might be possible using tidy itself
488 foreach ( $bits as $x ) {
489 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
491 @list
( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
492 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
493 if( is_callable( $processCallback ) ) {
494 call_user_func_array( $processCallback, array( &$params, $args ) );
496 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
497 $rest = str_replace( '>', '>', $rest );
498 $text .= "<$slash$t$newparams$brace$rest";
500 $text .= '<' . str_replace( '>', '>', $x);
504 wfProfileOut( __METHOD__
);
509 * Remove '<!--', '-->', and everything between.
510 * To avoid leaving blank lines, when a comment is both preceded
511 * and followed by a newline (ignoring spaces), trim leading and
512 * trailing spaces and one of the newlines.
515 * @param string $text
518 static function removeHTMLcomments( $text ) {
519 wfProfileIn( __METHOD__
);
520 while (($start = strpos($text, '<!--')) !== false) {
521 $end = strpos($text, '-->', $start +
4);
522 if ($end === false) {
523 # Unterminated comment; bail out
529 # Trim space and newline if the comment is both
530 # preceded and followed by a newline
531 $spaceStart = max($start - 1, 0);
532 $spaceLen = $end - $spaceStart;
533 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
537 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
539 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
540 # Remove the comment, leading and trailing
541 # spaces, and leave only one newline.
542 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
545 # Remove just the comment.
546 $text = substr_replace($text, '', $start, $end - $start);
549 wfProfileOut( __METHOD__
);
554 * Take an array of attribute names and values and normalize or discard
555 * illegal values for the given element type.
557 * - Discards attributes not on a whitelist for the given element
558 * - Unsafe style attributes are discarded
560 * @param array $attribs
561 * @param string $element
564 * @todo Check for legal values where the DTD limits things.
565 * @todo Check for unique id attribute :P
567 static function validateTagAttributes( $attribs, $element ) {
568 $whitelist = array_flip( Sanitizer
::attributeWhitelist( $element ) );
570 foreach( $attribs as $attribute => $value ) {
571 if( !isset( $whitelist[$attribute] ) ) {
574 # Strip javascript "expression" from stylesheets.
575 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
576 if( $attribute == 'style' ) {
577 $value = Sanitizer
::checkCss( $value );
578 if( $value === false ) {
584 if ( $attribute === 'id' )
585 $value = Sanitizer
::escapeId( $value );
587 // If this attribute was previously set, override it.
588 // Output should only have one attribute of each name.
589 $out[$attribute] = $value;
595 * Pick apart some CSS and check it for forbidden or unsafe structures.
596 * Returns a sanitized string, or false if it was just too evil.
598 * Currently URL references, 'expression', 'tps' are forbidden.
600 * @param string $value
603 static function checkCss( $value ) {
604 $stripped = Sanitizer
::decodeCharReferences( $value );
606 // Remove any comments; IE gets token splitting wrong
607 $stripped = StringUtils
::delimiterReplace( '/*', '*/', ' ', $stripped );
611 // ... and continue checks
612 $stripped = preg_replace( '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!e',
613 'codepointToUtf8(hexdec("$1"))', $stripped );
614 $stripped = str_replace( '\\', '', $stripped );
615 if( preg_match( '/(?:expression|tps*:\/\/|url\\s*\().*/is',
625 * Take a tag soup fragment listing an HTML element's attributes
626 * and normalize it to well-formed XML, discarding unwanted attributes.
627 * Output is safe for further wikitext processing, with escaping of
628 * values that could trigger problems.
630 * - Normalizes attribute names to lowercase
631 * - Discards attributes not on a whitelist for the given element
632 * - Turns broken or invalid entities into plaintext
633 * - Double-quotes all attribute values
634 * - Attributes without values are given the name as attribute
635 * - Double attributes are discarded
636 * - Unsafe style attributes are discarded
637 * - Prepends space if there are attributes.
639 * @param string $text
640 * @param string $element
643 static function fixTagAttributes( $text, $element ) {
644 if( trim( $text ) == '' ) {
648 $stripped = Sanitizer
::validateTagAttributes(
649 Sanitizer
::decodeTagAttributes( $text ), $element );
652 foreach( $stripped as $attribute => $value ) {
653 $encAttribute = htmlspecialchars( $attribute );
654 $encValue = Sanitizer
::safeEncodeAttribute( $value );
656 $attribs[] = "$encAttribute=\"$encValue\"";
658 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
662 * Encode an attribute value for HTML output.
664 * @return HTML-encoded text fragment
666 static function encodeAttribute( $text ) {
667 $encValue = htmlspecialchars( $text );
669 // Whitespace is normalized during attribute decoding,
670 // so if we've been passed non-spaces we must encode them
671 // ahead of time or they won't be preserved.
672 $encValue = strtr( $encValue, array(
682 * Encode an attribute value for HTML tags, with extra armoring
683 * against further wiki processing.
685 * @return HTML-encoded text fragment
687 static function safeEncodeAttribute( $text ) {
688 $encValue = Sanitizer
::encodeAttribute( $text );
690 # Templates and links may be expanded in later parsing,
691 # creating invalid or dangerous output. Suppress this.
692 $encValue = strtr( $encValue, array(
693 '<' => '<', // This should never happen,
694 '>' => '>', // we've received invalid input
695 '"' => '"', // which should have been escaped.
698 "''" => '''',
699 'ISBN' => 'ISBN',
701 'PMID' => 'PMID',
707 $encValue = preg_replace_callback(
708 '/(' . wfUrlProtocols() . ')/',
709 array( 'Sanitizer', 'armorLinksCallback' ),
715 * Given a value escape it so that it can be used in an id attribute and
716 * return it, this does not validate the value however (see first link)
718 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
721 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
728 static function escapeId( $id ) {
729 static $replace = array(
734 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
736 return str_replace( array_keys( $replace ), array_values( $replace ), $id );
740 * Given a value, escape it so that it can be used as a CSS class and
743 * @todo For extra validity, input should be validated UTF-8.
745 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
747 * @param string $class
750 static function escapeClass( $class ) {
751 // Convert ugly stuff to underscores and kill underscores in ugly places
752 return rtrim(preg_replace(
753 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
759 * Regex replace callback for armoring links against further processing.
760 * @param array $matches
764 private static function armorLinksCallback( $matches ) {
765 return str_replace( ':', ':', $matches[1] );
769 * Return an associative array of attribute names and values from
770 * a partial tag string. Attribute names are forces to lowercase,
771 * character references are decoded to UTF-8 text.
776 static function decodeTagAttributes( $text ) {
779 if( trim( $text ) == '' ) {
792 foreach( $pairs as $set ) {
793 $attribute = strtolower( $set[1] );
794 $value = Sanitizer
::getTagAttributeCallback( $set );
796 // Normalize whitespace
797 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
798 $value = trim( $value );
800 // Decode character references
801 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
807 * Pick the appropriate attribute value from a match set from the
808 * MW_ATTRIBS_REGEX matches.
814 private static function getTagAttributeCallback( $set ) {
815 if( isset( $set[6] ) ) {
816 # Illegal #XXXXXX color with no quotes.
818 } elseif( isset( $set[5] ) ) {
821 } elseif( isset( $set[4] ) ) {
824 } elseif( isset( $set[3] ) ) {
827 } elseif( !isset( $set[2] ) ) {
828 # In XHTML, attributes must have a value.
829 # For 'reduced' form, return explicitly the attribute name here.
832 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
837 * Normalize whitespace and character references in an XML source-
838 * encoded text for an attribute value.
840 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
841 * but note that we're not returning the value, but are returning
842 * XML source fragments that will be slapped into output.
844 * @param string $text
848 private static function normalizeAttributeValue( $text ) {
849 return str_replace( '"', '"',
851 '/\r\n|[\x20\x0d\x0a\x09]/',
853 Sanitizer
::normalizeCharReferences( $text ) ) );
857 * Ensure that any entities and character references are legal
858 * for XML and XHTML specifically. Any stray bits will be
859 * &-escaped to result in a valid text fragment.
861 * a. any named char refs must be known in XHTML
862 * b. any numeric char refs must be legal chars, not invalid or forbidden
863 * c. use &#x, not &#X
864 * d. fix or reject non-valid attributes
866 * @param string $text
870 static function normalizeCharReferences( $text ) {
871 return preg_replace_callback(
873 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
877 * @param string $matches
880 static function normalizeCharReferencesCallback( $matches ) {
882 if( $matches[1] != '' ) {
883 $ret = Sanitizer
::normalizeEntity( $matches[1] );
884 } elseif( $matches[2] != '' ) {
885 $ret = Sanitizer
::decCharReference( $matches[2] );
886 } elseif( $matches[3] != '' ) {
887 $ret = Sanitizer
::hexCharReference( $matches[3] );
888 } elseif( $matches[4] != '' ) {
889 $ret = Sanitizer
::hexCharReference( $matches[4] );
891 if( is_null( $ret ) ) {
892 return htmlspecialchars( $matches[0] );
899 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
900 * return the named entity reference as is. Otherwise, returns
901 * HTML-escaped text of pseudo-entity source (eg &foo;)
903 * @param string $name
907 static function normalizeEntity( $name ) {
908 global $wgHtmlEntities;
909 if( isset( $wgHtmlEntities[$name] ) ) {
912 return "&$name;";
916 static function decCharReference( $codepoint ) {
917 $point = intval( $codepoint );
918 if( Sanitizer
::validateCodepoint( $point ) ) {
919 return sprintf( '&#%d;', $point );
925 static function hexCharReference( $codepoint ) {
926 $point = hexdec( $codepoint );
927 if( Sanitizer
::validateCodepoint( $point ) ) {
928 return sprintf( '&#x%x;', $point );
935 * Returns true if a given Unicode codepoint is a valid character in XML.
936 * @param int $codepoint
939 private static function validateCodepoint( $codepoint ) {
940 return ($codepoint == 0x09)
941 ||
($codepoint == 0x0a)
942 ||
($codepoint == 0x0d)
943 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
944 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
945 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
949 * Decode any character references, numeric or named entities,
950 * in the text and return a UTF-8 string.
952 * @param string $text
957 public static function decodeCharReferences( $text ) {
958 return preg_replace_callback(
960 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
965 * @param string $matches
968 static function decodeCharReferencesCallback( $matches ) {
969 if( $matches[1] != '' ) {
970 return Sanitizer
::decodeEntity( $matches[1] );
971 } elseif( $matches[2] != '' ) {
972 return Sanitizer
::decodeChar( intval( $matches[2] ) );
973 } elseif( $matches[3] != '' ) {
974 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
975 } elseif( $matches[4] != '' ) {
976 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
978 # Last case should be an ampersand by itself
983 * Return UTF-8 string for a codepoint if that is a valid
984 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
985 * @param int $codepoint
989 static function decodeChar( $codepoint ) {
990 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
991 return codepointToUtf8( $codepoint );
993 return UTF8_REPLACEMENT
;
998 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
999 * return the UTF-8 encoding of that character. Otherwise, returns
1000 * pseudo-entity source (eg &foo;)
1002 * @param string $name
1005 static function decodeEntity( $name ) {
1006 global $wgHtmlEntities;
1007 if( isset( $wgHtmlEntities[$name] ) ) {
1008 return codepointToUtf8( $wgHtmlEntities[$name] );
1015 * Fetch the whitelist of acceptable attributes for a given
1018 * @param string $element
1021 static function attributeWhitelist( $element ) {
1023 if( !isset( $list ) ) {
1024 $list = Sanitizer
::setupAttributeWhitelist();
1026 return isset( $list[$element] )
1032 * @todo Document it a bit
1035 static function setupAttributeWhitelist() {
1036 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1037 $block = array_merge( $common, array( 'align' ) );
1038 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1039 $tablecell = array( 'abbr',
1045 'nowrap', # deprecated
1046 'width', # deprecated
1047 'height', # deprecated
1048 'bgcolor' # deprecated
1051 # Numbers refer to sections in HTML 4.01 standard describing the element.
1052 # See: http://www.w3.org/TR/html4/
1053 $whitelist = array (
1056 'center' => $common, # deprecated
1057 'span' => $block, # ??
1075 'strong' => $common,
1086 'blockquote' => array_merge( $common, array( 'cite' ) ),
1097 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1100 'pre' => array_merge( $common, array( 'width' ) ),
1103 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1104 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1107 'ul' => array_merge( $common, array( 'type' ) ),
1108 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1109 'li' => array_merge( $common, array( 'type', 'value' ) ),
1117 'table' => array_merge( $common,
1118 array( 'summary', 'width', 'border', 'frame',
1119 'rules', 'cellspacing', 'cellpadding',
1124 'caption' => array_merge( $common, array( 'align' ) ),
1127 'thead' => array_merge( $common, $tablealign ),
1128 'tfoot' => array_merge( $common, $tablealign ),
1129 'tbody' => array_merge( $common, $tablealign ),
1132 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1133 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1136 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1139 'td' => array_merge( $common, $tablecell, $tablealign ),
1140 'th' => array_merge( $common, $tablecell, $tablealign ),
1148 'strike' => $common,
1153 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1157 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1159 # XHTML Ruby annotation text module, simple ruby only.
1160 # http://www.w3c.org/TR/ruby/
1165 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1172 * Take a fragment of (potentially invalid) HTML and return
1173 * a version with any tags removed, encoded suitably for literal
1174 * inclusion in an attribute value.
1176 * @param string $text HTML fragment
1179 static function stripAllTags( $text ) {
1181 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
1183 # Normalize &entities and whitespace
1184 $text = Sanitizer
::normalizeAttributeValue( $text );
1186 # Will be placed into "double-quoted" attributes,
1187 # make sure remaining bits are safe.
1188 $text = str_replace(
1189 array('<', '>', '"'),
1190 array('<', '>', '"'),
1197 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1198 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1201 * Use for passing XHTML fragments to PHP's XML parsing functions
1206 static function hackDocType() {
1207 global $wgHtmlEntities;
1208 $out = "<!DOCTYPE html [\n";
1209 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1210 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1216 static function cleanUrl( $url, $hostname=true ) {
1217 # Normalize any HTML entities in input. They will be
1218 # re-escaped by makeExternalLink().
1219 $url = Sanitizer
::decodeCharReferences( $url );
1221 # Escape any control characters introduced by the above step
1222 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1224 # 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;