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',
32 '/&([A-Za-z0-9\x80-\xff]+);
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 * Regular expression to match URIs that could trigger script execution
62 define( 'MW_SCRIPT_URL_PATTERN', '/(^|\s)(javascript|vbscript)[^\w]/i' );
65 * List of all named character entities defined in HTML 4.01
66 * http://www.w3.org/TR/html4/sgml/entities.html
69 global $wgHtmlEntities;
70 $wgHtmlEntities = array(
325 * Character entity aliases accepted by MediaWiki
327 global $wgHtmlEntityAliases;
328 $wgHtmlEntityAliases = array(
335 * XHTML sanitizer for MediaWiki
340 * Cleans up HTML, removes dangerous tags and attributes, and
341 * removes HTML comments
343 * @param $text String
344 * @param $processCallback Callback to do any variable or parameter replacements in HTML attribute values
345 * @param $args Array for the processing callback
346 * @param $extratags Array for any extra tags to include
347 * @param $removetags Array for any tags (default or extra) to exclude
350 static function removeHTMLtags( $text, $processCallback = null, $args = array(), $extratags = array(), $removetags = array() ) {
353 static $htmlpairsStatic, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
354 $htmllist, $listtags, $htmlsingleallowed, $htmlelementsStatic, $staticInitialised;
356 wfProfileIn( __METHOD__
);
358 if ( !$staticInitialised ) {
360 $htmlpairsStatic = array( # Tags that must be closed
361 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
362 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
363 'strike', 'strong', 'tt', 'var', 'div', 'center',
364 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
365 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span', 'u', 'abbr'
368 'br', 'hr', 'li', 'dt', 'dd'
370 $htmlsingleonly = array( # Elements that cannot have close tags
373 $htmlnest = array( # Tags that can be nested--??
374 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
375 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
377 $tabletags = array( # Can only appear inside table, we will close them
380 $htmllist = array( # Tags used by list
383 $listtags = array( # Tags that can appear in a list
387 $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
388 $htmlelementsStatic = array_unique( array_merge( $htmlsingle, $htmlpairsStatic, $htmlnest ) );
390 # Convert them all to hashtables for faster lookup
391 $vars = array( 'htmlpairsStatic', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
392 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelementsStatic' );
393 foreach ( $vars as $var ) {
394 $
$var = array_flip( $
$var );
396 $staticInitialised = true;
398 # Populate $htmlpairs and $htmlelements with the $extratags and $removetags arrays
399 $extratags = array_flip( $extratags );
400 $removetags = array_flip( $removetags );
401 $htmlpairs = array_merge( $extratags, $htmlpairsStatic );
402 $htmlelements = array_diff_key( array_merge( $extratags, $htmlelementsStatic ) , $removetags );
404 # Remove HTML comments
405 $text = Sanitizer
::removeHTMLcomments( $text );
406 $bits = explode( '<', $text );
407 $text = str_replace( '>', '>', array_shift( $bits ) );
409 $tagstack = $tablestack = array();
410 foreach ( $bits as $x ) {
412 if( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
413 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
415 $slash = $t = $params = $brace = $rest = null;
419 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
423 if( isset( $htmlsingleonly[$t] ) ) {
425 } elseif ( ( $ot = @array_pop
( $tagstack ) ) != $t ) {
426 if ( isset( $htmlsingleallowed[$ot] ) ) {
427 # Pop all elements with an optional close tag
428 # and see if we find a match below them
430 array_push ($optstack, $ot);
431 while ( ( ( $ot = @array_pop
( $tagstack ) ) != $t ) &&
432 isset( $htmlsingleallowed[$ot] ) )
434 array_push ($optstack, $ot);
437 # No match. Push the optinal elements back again
439 while ( $ot = @array_pop
( $optstack ) ) {
440 array_push( $tagstack, $ot );
444 @array_push
( $tagstack, $ot );
445 # <li> can be nested in <ul> or <ol>, skip those cases:
446 if(!(isset( $htmllist[$ot] ) && isset( $listtags[$t] ) )) {
451 if ( $t == 'table' ) {
452 $tagstack = array_pop( $tablestack );
457 # Keep track for later
458 if ( isset( $tabletags[$t] ) &&
459 ! in_array( 'table', $tagstack ) ) {
461 } else if ( in_array( $t, $tagstack ) &&
462 ! isset( $htmlnest [$t ] ) ) {
464 #Â Is it a self closed htmlpair ? (bug 5487)
465 } else if( $brace == '/>' &&
466 isset( $htmlpairs[$t] ) ) {
468 } elseif( isset( $htmlsingleonly[$t] ) ) {
469 # Hack to force empty tag for uncloseable elements
471 } else if( isset( $htmlsingle[$t] ) ) {
472 # Hack to not close $htmlsingle tags
474 } else if( isset( $tabletags[$t] )
475 && in_array($t ,$tagstack) ) {
476 // New table tag but forgot to close the previous one
479 if ( $t == 'table' ) {
480 array_push( $tablestack, $tagstack );
483 array_push( $tagstack, $t );
486 # Replace any variables or template parameters with
488 if( is_callable( $processCallback ) ) {
489 call_user_func_array( $processCallback, array( &$params, $args ) );
492 # Strip non-approved attributes from the tag
493 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
496 $rest = str_replace( '>', '>', $rest );
497 $close = ( $brace == '/>' && !$slash ) ?
' /' : '';
498 $text .= "<$slash$t$newparams$close>$rest";
502 $text .= '<' . str_replace( '>', '>', $x);
504 # Close off any remaining tags
505 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
507 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
510 # this might be possible using tidy itself
511 foreach ( $bits as $x ) {
512 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
514 @list
( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
515 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
516 if( is_callable( $processCallback ) ) {
517 call_user_func_array( $processCallback, array( &$params, $args ) );
519 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
520 $rest = str_replace( '>', '>', $rest );
521 $text .= "<$slash$t$newparams$brace$rest";
523 $text .= '<' . str_replace( '>', '>', $x);
527 wfProfileOut( __METHOD__
);
532 * Remove '<!--', '-->', and everything between.
533 * To avoid leaving blank lines, when a comment is both preceded
534 * and followed by a newline (ignoring spaces), trim leading and
535 * trailing spaces and one of the newlines.
538 * @param $text String
541 static function removeHTMLcomments( $text ) {
542 wfProfileIn( __METHOD__
);
543 while (($start = strpos($text, '<!--')) !== false) {
544 $end = strpos($text, '-->', $start +
4);
545 if ($end === false) {
546 # Unterminated comment; bail out
552 # Trim space and newline if the comment is both
553 # preceded and followed by a newline
554 $spaceStart = max($start - 1, 0);
555 $spaceLen = $end - $spaceStart;
556 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
560 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
562 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
563 # Remove the comment, leading and trailing
564 # spaces, and leave only one newline.
565 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
568 # Remove just the comment.
569 $text = substr_replace($text, '', $start, $end - $start);
572 wfProfileOut( __METHOD__
);
577 * Take an array of attribute names and values and normalize or discard
578 * illegal values for the given element type.
580 * - Discards attributes not on a whitelist for the given element
581 * - Unsafe style attributes are discarded
582 * - Invalid id attributes are reencoded
584 * @param $attribs Array
585 * @param $element String
588 * @todo Check for legal values where the DTD limits things.
589 * @todo Check for unique id attribute :P
591 static function validateTagAttributes( $attribs, $element ) {
592 return Sanitizer
::validateAttributes( $attribs,
593 Sanitizer
::attributeWhitelist( $element ) );
597 * Take an array of attribute names and values and normalize or discard
598 * illegal values for the given whitelist.
600 * - Discards attributes not the given whitelist
601 * - Unsafe style attributes are discarded
602 * - Invalid id attributes are reencoded
604 * @param $attribs Array
605 * @param $whitelist Array: list of allowed attribute names
608 * @todo Check for legal values where the DTD limits things.
609 * @todo Check for unique id attribute :P
611 static function validateAttributes( $attribs, $whitelist ) {
612 $whitelist = array_flip( $whitelist );
614 foreach( $attribs as $attribute => $value ) {
615 if( !isset( $whitelist[$attribute] ) ) {
618 # Strip javascript "expression" from stylesheets.
619 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
620 if( $attribute == 'style' ) {
621 $value = Sanitizer
::checkCss( $value );
622 if( $value === false ) {
628 if ( $attribute === 'id' ) {
629 global $wgEnforceHtmlIds;
630 $value = Sanitizer
::escapeId( $value,
631 $wgEnforceHtmlIds ?
'noninitial' : 'xml' );
634 //RDFa properties allow URIs. check them
635 if ( $attribute === 'rel' ||
$attribute === 'rev' ||
636 $attribute === 'about' ||
$attribute === 'property' ||
$attribute === 'resource' ||
637 $attribute === 'datatype' ||
$attribute === 'typeof' ) {
638 //Paranoia. Allow "simple" values but suppress javascript
639 if ( preg_match( MW_SCRIPT_URL_PATTERN
, $value ) ) {
644 // If this attribute was previously set, override it.
645 // Output should only have one attribute of each name.
646 $out[$attribute] = $value;
652 * Merge two sets of HTML attributes. Conflicting items in the second set
653 * will override those in the first, except for 'class' attributes which
654 * will be combined (if they're both strings).
656 * @todo implement merging for other attributes such as style
661 static function mergeAttributes( $a, $b ) {
662 $out = array_merge( $a, $b );
663 if( isset( $a['class'] ) && isset( $b['class'] )
664 && is_string( $a['class'] ) && is_string( $b['class'] )
665 && $a['class'] !== $b['class'] ) {
666 $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
667 -1, PREG_SPLIT_NO_EMPTY
);
668 $out['class'] = implode( ' ', array_unique( $classes ) );
674 * Pick apart some CSS and check it for forbidden or unsafe structures.
675 * Returns a sanitized string, or false if it was just too evil.
677 * Currently URL references, 'expression', 'tps' are forbidden.
679 * @param $value String
682 static function checkCss( $value ) {
683 $stripped = Sanitizer
::decodeCharReferences( $value );
685 // Remove any comments; IE gets token splitting wrong
686 $stripped = StringUtils
::delimiterReplace( '/*', '*/', ' ', $stripped );
690 // ... and continue checks
691 $stripped = preg_replace( '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!e',
692 'codepointToUtf8(hexdec("$1"))', $stripped );
693 $stripped = str_replace( '\\', '', $stripped );
694 if( preg_match( '/(?:expression|tps*:\/\/|url\\s*\().*/is',
704 * Take a tag soup fragment listing an HTML element's attributes
705 * and normalize it to well-formed XML, discarding unwanted attributes.
706 * Output is safe for further wikitext processing, with escaping of
707 * values that could trigger problems.
709 * - Normalizes attribute names to lowercase
710 * - Discards attributes not on a whitelist for the given element
711 * - Turns broken or invalid entities into plaintext
712 * - Double-quotes all attribute values
713 * - Attributes without values are given the name as attribute
714 * - Double attributes are discarded
715 * - Unsafe style attributes are discarded
716 * - Prepends space if there are attributes.
718 * @param $text String
719 * @param $element String
722 static function fixTagAttributes( $text, $element ) {
723 if( trim( $text ) == '' ) {
727 $stripped = Sanitizer
::validateTagAttributes(
728 Sanitizer
::decodeTagAttributes( $text ), $element );
731 foreach( $stripped as $attribute => $value ) {
732 $encAttribute = htmlspecialchars( $attribute );
733 $encValue = Sanitizer
::safeEncodeAttribute( $value );
735 $attribs[] = "$encAttribute=\"$encValue\"";
737 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
741 * Encode an attribute value for HTML output.
742 * @param $text String
743 * @return HTML-encoded text fragment
745 static function encodeAttribute( $text ) {
746 $encValue = htmlspecialchars( $text, ENT_QUOTES
);
748 // Whitespace is normalized during attribute decoding,
749 // so if we've been passed non-spaces we must encode them
750 // ahead of time or they won't be preserved.
751 $encValue = strtr( $encValue, array(
761 * Encode an attribute value for HTML tags, with extra armoring
762 * against further wiki processing.
763 * @param $text String
764 * @return HTML-encoded text fragment
766 static function safeEncodeAttribute( $text ) {
767 $encValue = Sanitizer
::encodeAttribute( $text );
769 # Templates and links may be expanded in later parsing,
770 # creating invalid or dangerous output. Suppress this.
771 $encValue = strtr( $encValue, array(
772 '<' => '<', // This should never happen,
773 '>' => '>', // we've received invalid input
774 '"' => '"', // which should have been escaped.
777 "''" => '''',
778 'ISBN' => 'ISBN',
780 'PMID' => 'PMID',
786 $encValue = preg_replace_callback(
787 '/(' . wfUrlProtocols() . ')/',
788 array( 'Sanitizer', 'armorLinksCallback' ),
794 * Given a value escape it so that it can be used in an id attribute and
795 * return it, this does not validate the value however (see first link)
797 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
800 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
802 * @param $id String: id to validate
803 * @param $options Mixed: string or array of strings (default is array()):
804 * 'noninitial': This is a non-initial fragment of an id, not a full id,
805 * so don't pay attention if the first character isn't valid at the
806 * beginning of an id.
807 * 'xml': Don't restrict the id to be HTML4-compatible. This option
808 * allows any alphabetic character to be used, per the XML standard.
809 * Therefore, it also completely changes the type of escaping: instead
810 * of weird dot-encoding, runs of invalid characters (mostly
811 * whitespace) are just compressed into a single underscore.
814 static function escapeId( $id, $options = array() ) {
815 $options = (array)$options;
817 if ( !in_array( 'xml', $options ) ) {
818 # HTML4-style escaping
819 static $replace = array(
824 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
825 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
827 if ( !preg_match( '/^[a-zA-Z]/', $id )
828 && !in_array( 'noninitial', $options ) ) {
829 // Initial character must be a letter!
835 # XML-style escaping. For the patterns used, see the XML 1.0 standard,
836 # 5th edition, NameStartChar and NameChar: <http://www.w3.org/TR/REC-xml/>
837 $nameStartChar = ':a-zA-Z_\xC0-\xD6\xD8-\xF6\xF8-\x{2FF}\x{370}-\x{37D}'
838 . '\x{37F}-\x{1FFF}\x{200C}-\x{200D}\x{2070}-\x{218F}\x{2C00}-\x{2FEF}'
839 . '\x{3001}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFFD}\x{10000}-\x{EFFFF}';
840 $nameChar = $nameStartChar . '.\-0-9\xB7\x{0300}-\x{036F}'
841 . '\x{203F}-\x{2040}';
842 # Replace _ as well so we don't get multiple consecutive underscores
843 $id = preg_replace( "/([^$nameChar]|_)+/u", '_', $id );
844 $id = trim( $id, '_' );
846 if ( !preg_match( "/^[$nameStartChar]/u", $id )
847 && !in_array( 'noninitial', $options ) ) {
855 * Given a value, escape it so that it can be used as a CSS class and
858 * @todo For extra validity, input should be validated UTF-8.
860 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
862 * @param $class String
865 static function escapeClass( $class ) {
866 // Convert ugly stuff to underscores and kill underscores in ugly places
867 return rtrim(preg_replace(
868 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
874 * Given HTML input, escape with htmlspecialchars but un-escape entites.
875 * This allows (generally harmless) entities like to survive.
877 * @param $html String to escape
878 * @return String: escaped input
880 static function escapeHtmlAllowEntities( $html ) {
881 # It seems wise to escape ' as well as ", as a matter of course. Can't
883 $html = htmlspecialchars( $html, ENT_QUOTES
);
884 $html = str_replace( '&', '&', $html );
885 $html = Sanitizer
::normalizeCharReferences( $html );
890 * Regex replace callback for armoring links against further processing.
891 * @param $matches Array
894 private static function armorLinksCallback( $matches ) {
895 return str_replace( ':', ':', $matches[1] );
899 * Return an associative array of attribute names and values from
900 * a partial tag string. Attribute names are forces to lowercase,
901 * character references are decoded to UTF-8 text.
903 * @param $text String
906 public static function decodeTagAttributes( $text ) {
909 if( trim( $text ) == '' ) {
922 foreach( $pairs as $set ) {
923 $attribute = strtolower( $set[1] );
924 $value = Sanitizer
::getTagAttributeCallback( $set );
926 // Normalize whitespace
927 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
928 $value = trim( $value );
930 // Decode character references
931 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
937 * Pick the appropriate attribute value from a match set from the
938 * MW_ATTRIBS_REGEX matches.
943 private static function getTagAttributeCallback( $set ) {
944 if( isset( $set[6] ) ) {
945 # Illegal #XXXXXX color with no quotes.
947 } elseif( isset( $set[5] ) ) {
950 } elseif( isset( $set[4] ) ) {
953 } elseif( isset( $set[3] ) ) {
956 } elseif( !isset( $set[2] ) ) {
957 # In XHTML, attributes must have a value.
958 # For 'reduced' form, return explicitly the attribute name here.
961 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
966 * Normalize whitespace and character references in an XML source-
967 * encoded text for an attribute value.
969 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
970 * but note that we're not returning the value, but are returning
971 * XML source fragments that will be slapped into output.
973 * @param $text String
976 private static function normalizeAttributeValue( $text ) {
977 return str_replace( '"', '"',
978 self
::normalizeWhitespace(
979 Sanitizer
::normalizeCharReferences( $text ) ) );
982 private static function normalizeWhitespace( $text ) {
984 '/\r\n|[\x20\x0d\x0a\x09]/',
990 * Ensure that any entities and character references are legal
991 * for XML and XHTML specifically. Any stray bits will be
992 * &-escaped to result in a valid text fragment.
994 * a. any named char refs must be known in XHTML
995 * b. any numeric char refs must be legal chars, not invalid or forbidden
996 * c. use &#x, not &#X
997 * d. fix or reject non-valid attributes
999 * @param $text String
1003 static function normalizeCharReferences( $text ) {
1004 return preg_replace_callback(
1006 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
1010 * @param $matches String
1013 static function normalizeCharReferencesCallback( $matches ) {
1015 if( $matches[1] != '' ) {
1016 $ret = Sanitizer
::normalizeEntity( $matches[1] );
1017 } elseif( $matches[2] != '' ) {
1018 $ret = Sanitizer
::decCharReference( $matches[2] );
1019 } elseif( $matches[3] != '' ) {
1020 $ret = Sanitizer
::hexCharReference( $matches[3] );
1021 } elseif( $matches[4] != '' ) {
1022 $ret = Sanitizer
::hexCharReference( $matches[4] );
1024 if( is_null( $ret ) ) {
1025 return htmlspecialchars( $matches[0] );
1032 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1033 * return the named entity reference as is. If the entity is a
1034 * MediaWiki-specific alias, returns the HTML equivalent. Otherwise,
1035 * returns HTML-escaped text of pseudo-entity source (eg &foo;)
1037 * @param $name String
1040 static function normalizeEntity( $name ) {
1041 global $wgHtmlEntities, $wgHtmlEntityAliases;
1042 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1043 return "&{$wgHtmlEntityAliases[$name]};";
1044 } elseif( isset( $wgHtmlEntities[$name] ) ) {
1047 return "&$name;";
1051 static function decCharReference( $codepoint ) {
1052 $point = intval( $codepoint );
1053 if( Sanitizer
::validateCodepoint( $point ) ) {
1054 return sprintf( '&#%d;', $point );
1060 static function hexCharReference( $codepoint ) {
1061 $point = hexdec( $codepoint );
1062 if( Sanitizer
::validateCodepoint( $point ) ) {
1063 return sprintf( '&#x%x;', $point );
1070 * Returns true if a given Unicode codepoint is a valid character in XML.
1071 * @param $codepoint Integer
1074 private static function validateCodepoint( $codepoint ) {
1075 return ($codepoint == 0x09)
1076 ||
($codepoint == 0x0a)
1077 ||
($codepoint == 0x0d)
1078 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
1079 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
1080 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
1084 * Decode any character references, numeric or named entities,
1085 * in the text and return a UTF-8 string.
1087 * @param $text String
1090 public static function decodeCharReferences( $text ) {
1091 return preg_replace_callback(
1093 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1098 * @param $matches String
1101 static function decodeCharReferencesCallback( $matches ) {
1102 if( $matches[1] != '' ) {
1103 return Sanitizer
::decodeEntity( $matches[1] );
1104 } elseif( $matches[2] != '' ) {
1105 return Sanitizer
::decodeChar( intval( $matches[2] ) );
1106 } elseif( $matches[3] != '' ) {
1107 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
1108 } elseif( $matches[4] != '' ) {
1109 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
1111 # Last case should be an ampersand by itself
1116 * Return UTF-8 string for a codepoint if that is a valid
1117 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1118 * @param $codepoint Integer
1122 static function decodeChar( $codepoint ) {
1123 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
1124 return codepointToUtf8( $codepoint );
1126 return UTF8_REPLACEMENT
;
1131 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1132 * return the UTF-8 encoding of that character. Otherwise, returns
1133 * pseudo-entity source (eg &foo;)
1135 * @param $name Strings
1138 static function decodeEntity( $name ) {
1139 global $wgHtmlEntities, $wgHtmlEntityAliases;
1140 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1141 $name = $wgHtmlEntityAliases[$name];
1143 if( isset( $wgHtmlEntities[$name] ) ) {
1144 return codepointToUtf8( $wgHtmlEntities[$name] );
1151 * Fetch the whitelist of acceptable attributes for a given element name.
1153 * @param $element String
1156 static function attributeWhitelist( $element ) {
1158 if( !isset( $list ) ) {
1159 $list = Sanitizer
::setupAttributeWhitelist();
1161 return isset( $list[$element] )
1167 * Foreach array key (an allowed HTML element), return an array
1168 * of allowed attributes
1171 static function setupAttributeWhitelist() {
1172 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style',
1173 #RDFa attributes as specified in section 9 of http://www.w3.org/TR/2008/REC-rdfa-syntax-20081014
1174 'about', 'property', 'resource', 'datatype', 'typeof',
1177 $block = array_merge( $common, array( 'align' ) );
1178 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1179 $tablecell = array( 'abbr',
1185 'nowrap', # deprecated
1186 'width', # deprecated
1187 'height', # deprecated
1188 'bgcolor' # deprecated
1191 # Numbers refer to sections in HTML 4.01 standard describing the element.
1192 # See: http://www.w3.org/TR/html4/
1193 $whitelist = array (
1196 'center' => $common, # deprecated
1197 'span' => $block, # ??
1215 'strong' => $common,
1226 'blockquote' => array_merge( $common, array( 'cite' ) ),
1237 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1240 'pre' => array_merge( $common, array( 'width' ) ),
1243 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1244 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1247 'ul' => array_merge( $common, array( 'type' ) ),
1248 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1249 'li' => array_merge( $common, array( 'type', 'value' ) ),
1257 'table' => array_merge( $common,
1258 array( 'summary', 'width', 'border', 'frame',
1259 'rules', 'cellspacing', 'cellpadding',
1264 'caption' => array_merge( $common, array( 'align' ) ),
1267 'thead' => array_merge( $common, $tablealign ),
1268 'tfoot' => array_merge( $common, $tablealign ),
1269 'tbody' => array_merge( $common, $tablealign ),
1272 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1273 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1276 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1279 'td' => array_merge( $common, $tablecell, $tablealign ),
1280 'th' => array_merge( $common, $tablecell, $tablealign ),
1283 # Not usually allowed, but may be used for extension-style hooks
1284 # such as <math> when it is rasterized
1285 'img' => array_merge( $common, array( 'alt' ) ),
1293 'strike' => $common,
1298 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1302 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1304 # XHTML Ruby annotation text module, simple ruby only.
1305 # http://www.w3c.org/TR/ruby/
1310 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1313 # MathML root element, where used for extensions
1314 # 'title' may not be 100% valid here; it's XHTML
1315 # http://www.w3.org/TR/REC-MathML/
1316 'math' => array( 'class', 'style', 'id', 'title' ),
1322 * Take a fragment of (potentially invalid) HTML and return
1323 * a version with any tags removed, encoded as plain text.
1325 * Warning: this return value must be further escaped for literal
1326 * inclusion in HTML output as of 1.10!
1328 * @param $text String: HTML fragment
1331 static function stripAllTags( $text ) {
1333 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
1335 # Normalize &entities and whitespace
1336 $text = self
::decodeCharReferences( $text );
1337 $text = self
::normalizeWhitespace( $text );
1343 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1344 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1347 * Use for passing XHTML fragments to PHP's XML parsing functions
1351 static function hackDocType() {
1352 global $wgHtmlEntities;
1353 $out = "<!DOCTYPE html [\n";
1354 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1355 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1361 static function cleanUrl( $url ) {
1362 # Normalize any HTML entities in input. They will be
1363 # re-escaped by makeExternalLink().
1364 $url = Sanitizer
::decodeCharReferences( $url );
1366 # Escape any control characters introduced by the above step
1367 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1369 # Validate hostname portion
1371 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1372 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1374 // Characters that will be ignored in IDNs.
1375 // http://tools.ietf.org/html/3454#section-3.1
1376 // Strip them before further processing so blacklists and such work.
1378 \\s| # general whitespace
1379 \xc2\xad| # 00ad SOFT HYPHEN
1380 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1381 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1382 \xe2\x81\xa0| # 2060 WORD JOINER
1383 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1384 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1385 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1386 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1387 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1388 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1389 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1390 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1393 $host = preg_replace( $strip, '', $host );
1395 // @fixme: validate hostnames here
1397 return $protocol . $host . $rest;