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 * 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(
320 * Character entity aliases accepted by MediaWiki
322 global $wgHtmlEntityAliases;
323 $wgHtmlEntityAliases = array(
330 * XHTML sanitizer for MediaWiki
335 * Cleans up HTML, removes dangerous tags and attributes, and
336 * removes HTML comments
338 * @param $text String
339 * @param $processCallback Callback to do any variable or parameter replacements in HTML attribute values
340 * @param $args Array for the processing callback
341 * @param $extratags Array for any extra tags to include
342 * @param $removetags Array for any tags (default or extra) to exclude
345 static function removeHTMLtags( $text, $processCallback = null, $args = array(), $extratags = array(), $removetags = array() ) {
348 static $htmlpairsStatic, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
349 $htmllist, $listtags, $htmlsingleallowed, $htmlelementsStatic, $staticInitialised;
351 wfProfileIn( __METHOD__
);
353 if ( !$staticInitialised ) {
355 $htmlpairsStatic = array( # Tags that must be closed
356 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
357 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
358 'strike', 'strong', 'tt', 'var', 'div', 'center',
359 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
360 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span', 'u', 'abbr'
363 'br', 'hr', 'li', 'dt', 'dd'
365 $htmlsingleonly = array( # Elements that cannot have close tags
368 $htmlnest = array( # Tags that can be nested--??
369 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
370 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
372 $tabletags = array( # Can only appear inside table, we will close them
375 $htmllist = array( # Tags used by list
378 $listtags = array( # Tags that can appear in a list
382 $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
383 $htmlelementsStatic = array_unique( array_merge( $htmlsingle, $htmlpairsStatic, $htmlnest ) );
385 # Convert them all to hashtables for faster lookup
386 $vars = array( 'htmlpairsStatic', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
387 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelementsStatic' );
388 foreach ( $vars as $var ) {
389 $
$var = array_flip( $
$var );
391 $staticInitialised = true;
393 # Populate $htmlpairs and $htmlelements with the $extratags and $removetags arrays
394 $extratags = array_flip( $extratags );
395 $removetags = array_flip( $removetags );
396 $htmlpairs = array_merge( $extratags, $htmlpairsStatic );
397 $htmlelements = array_diff_key( array_merge( $extratags, $htmlelementsStatic ) , $removetags );
399 # Remove HTML comments
400 $text = Sanitizer
::removeHTMLcomments( $text );
401 $bits = explode( '<', $text );
402 $text = str_replace( '>', '>', array_shift( $bits ) );
404 $tagstack = $tablestack = array();
405 foreach ( $bits as $x ) {
407 if( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
408 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
410 $slash = $t = $params = $brace = $rest = null;
414 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
418 if( isset( $htmlsingleonly[$t] ) ) {
420 } elseif ( ( $ot = @array_pop
( $tagstack ) ) != $t ) {
421 if ( isset( $htmlsingleallowed[$ot] ) ) {
422 # Pop all elements with an optional close tag
423 # and see if we find a match below them
425 array_push ($optstack, $ot);
426 while ( ( ( $ot = @array_pop
( $tagstack ) ) != $t ) &&
427 isset( $htmlsingleallowed[$ot] ) )
429 array_push ($optstack, $ot);
432 # No match. Push the optinal elements back again
434 while ( $ot = @array_pop
( $optstack ) ) {
435 array_push( $tagstack, $ot );
439 @array_push
( $tagstack, $ot );
440 # <li> can be nested in <ul> or <ol>, skip those cases:
441 if(!(isset( $htmllist[$ot] ) && isset( $listtags[$t] ) )) {
446 if ( $t == 'table' ) {
447 $tagstack = array_pop( $tablestack );
452 # Keep track for later
453 if ( isset( $tabletags[$t] ) &&
454 ! in_array( 'table', $tagstack ) ) {
456 } else if ( in_array( $t, $tagstack ) &&
457 ! isset( $htmlnest [$t ] ) ) {
459 #Â Is it a self closed htmlpair ? (bug 5487)
460 } else if( $brace == '/>' &&
461 isset( $htmlpairs[$t] ) ) {
463 } elseif( isset( $htmlsingleonly[$t] ) ) {
464 # Hack to force empty tag for uncloseable elements
466 } else if( isset( $htmlsingle[$t] ) ) {
467 # Hack to not close $htmlsingle tags
469 } else if( isset( $tabletags[$t] )
470 && in_array($t ,$tagstack) ) {
471 // New table tag but forgot to close the previous one
474 if ( $t == 'table' ) {
475 array_push( $tablestack, $tagstack );
478 array_push( $tagstack, $t );
481 # Replace any variables or template parameters with
483 if( is_callable( $processCallback ) ) {
484 call_user_func_array( $processCallback, array( &$params, $args ) );
487 # Strip non-approved attributes from the tag
488 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
491 $rest = str_replace( '>', '>', $rest );
492 $close = ( $brace == '/>' && !$slash ) ?
' /' : '';
493 $text .= "<$slash$t$newparams$close>$rest";
497 $text .= '<' . str_replace( '>', '>', $x);
499 # Close off any remaining tags
500 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
502 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
505 # this might be possible using tidy itself
506 foreach ( $bits as $x ) {
507 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
509 @list
( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
510 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
511 if( is_callable( $processCallback ) ) {
512 call_user_func_array( $processCallback, array( &$params, $args ) );
514 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
515 $rest = str_replace( '>', '>', $rest );
516 $text .= "<$slash$t$newparams$brace$rest";
518 $text .= '<' . str_replace( '>', '>', $x);
522 wfProfileOut( __METHOD__
);
527 * Remove '<!--', '-->', and everything between.
528 * To avoid leaving blank lines, when a comment is both preceded
529 * and followed by a newline (ignoring spaces), trim leading and
530 * trailing spaces and one of the newlines.
533 * @param $text String
536 static function removeHTMLcomments( $text ) {
537 wfProfileIn( __METHOD__
);
538 while (($start = strpos($text, '<!--')) !== false) {
539 $end = strpos($text, '-->', $start +
4);
540 if ($end === false) {
541 # Unterminated comment; bail out
547 # Trim space and newline if the comment is both
548 # preceded and followed by a newline
549 $spaceStart = max($start - 1, 0);
550 $spaceLen = $end - $spaceStart;
551 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
555 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
557 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
558 # Remove the comment, leading and trailing
559 # spaces, and leave only one newline.
560 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
563 # Remove just the comment.
564 $text = substr_replace($text, '', $start, $end - $start);
567 wfProfileOut( __METHOD__
);
572 * Take an array of attribute names and values and normalize or discard
573 * illegal values for the given element type.
575 * - Discards attributes not on a whitelist for the given element
576 * - Unsafe style attributes are discarded
577 * - Invalid id attributes are reencoded
579 * @param $attribs Array
580 * @param $element String
583 * @todo Check for legal values where the DTD limits things.
584 * @todo Check for unique id attribute :P
586 static function validateTagAttributes( $attribs, $element ) {
587 return Sanitizer
::validateAttributes( $attribs,
588 Sanitizer
::attributeWhitelist( $element ) );
592 * Take an array of attribute names and values and normalize or discard
593 * illegal values for the given whitelist.
595 * - Discards attributes not the given whitelist
596 * - Unsafe style attributes are discarded
597 * - Invalid id attributes are reencoded
599 * @param $attribs Array
600 * @param $whitelist Array: list of allowed attribute names
603 * @todo Check for legal values where the DTD limits things.
604 * @todo Check for unique id attribute :P
606 static function validateAttributes( $attribs, $whitelist ) {
607 $whitelist = array_flip( $whitelist );
609 foreach( $attribs as $attribute => $value ) {
610 if( !isset( $whitelist[$attribute] ) ) {
613 # Strip javascript "expression" from stylesheets.
614 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
615 if( $attribute == 'style' ) {
616 $value = Sanitizer
::checkCss( $value );
617 if( $value === false ) {
623 if ( $attribute === 'id' ) {
624 global $wgEnforceHtmlIds;
625 $value = Sanitizer
::escapeId( $value,
626 $wgEnforceHtmlIds ?
'noninitial' : 'xml' );
629 //RDFa properties allow URIs. check them
630 if ( $attribute === 'rel' ||
$attribute === 'rev' ||
631 $attribute === 'about' ||
$attribute === 'property' ||
$attribute === 'resource' ||
632 $attribute === 'datatype' ||
$attribute === 'typeof' ) {
633 //Paranoia. Allow "simple" values but suppress javascript
634 if ( preg_match( '/(^|\s)javascript\s*:/i', $value ) ) {
639 // If this attribute was previously set, override it.
640 // Output should only have one attribute of each name.
641 $out[$attribute] = $value;
647 * Merge two sets of HTML attributes. Conflicting items in the second set
648 * will override those in the first, except for 'class' attributes which
649 * will be combined (if they're both strings).
651 * @todo implement merging for other attributes such as style
656 static function mergeAttributes( $a, $b ) {
657 $out = array_merge( $a, $b );
658 if( isset( $a['class'] ) && isset( $b['class'] )
659 && is_string( $a['class'] ) && is_string( $b['class'] )
660 && $a['class'] !== $b['class'] ) {
661 $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
662 -1, PREG_SPLIT_NO_EMPTY
);
663 $out['class'] = implode( ' ', array_unique( $classes ) );
669 * Pick apart some CSS and check it for forbidden or unsafe structures.
670 * Returns a sanitized string, or false if it was just too evil.
672 * Currently URL references, 'expression', 'tps' are forbidden.
674 * @param $value String
677 static function checkCss( $value ) {
678 $stripped = Sanitizer
::decodeCharReferences( $value );
680 // Remove any comments; IE gets token splitting wrong
681 $stripped = StringUtils
::delimiterReplace( '/*', '*/', ' ', $stripped );
685 // ... and continue checks
686 $stripped = preg_replace( '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!e',
687 'codepointToUtf8(hexdec("$1"))', $stripped );
688 $stripped = str_replace( '\\', '', $stripped );
689 if( preg_match( '/(?:expression|tps*:\/\/|url\\s*\().*/is',
699 * Take a tag soup fragment listing an HTML element's attributes
700 * and normalize it to well-formed XML, discarding unwanted attributes.
701 * Output is safe for further wikitext processing, with escaping of
702 * values that could trigger problems.
704 * - Normalizes attribute names to lowercase
705 * - Discards attributes not on a whitelist for the given element
706 * - Turns broken or invalid entities into plaintext
707 * - Double-quotes all attribute values
708 * - Attributes without values are given the name as attribute
709 * - Double attributes are discarded
710 * - Unsafe style attributes are discarded
711 * - Prepends space if there are attributes.
713 * @param $text String
714 * @param $element String
717 static function fixTagAttributes( $text, $element ) {
718 if( trim( $text ) == '' ) {
722 $stripped = Sanitizer
::validateTagAttributes(
723 Sanitizer
::decodeTagAttributes( $text ), $element );
726 foreach( $stripped as $attribute => $value ) {
727 $encAttribute = htmlspecialchars( $attribute );
728 $encValue = Sanitizer
::safeEncodeAttribute( $value );
730 $attribs[] = "$encAttribute=\"$encValue\"";
732 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
736 * Encode an attribute value for HTML output.
737 * @param $text String
738 * @return HTML-encoded text fragment
740 static function encodeAttribute( $text ) {
741 $encValue = htmlspecialchars( $text, ENT_QUOTES
);
743 // Whitespace is normalized during attribute decoding,
744 // so if we've been passed non-spaces we must encode them
745 // ahead of time or they won't be preserved.
746 $encValue = strtr( $encValue, array(
756 * Encode an attribute value for HTML tags, with extra armoring
757 * against further wiki processing.
758 * @param $text String
759 * @return HTML-encoded text fragment
761 static function safeEncodeAttribute( $text ) {
762 $encValue = Sanitizer
::encodeAttribute( $text );
764 # Templates and links may be expanded in later parsing,
765 # creating invalid or dangerous output. Suppress this.
766 $encValue = strtr( $encValue, array(
767 '<' => '<', // This should never happen,
768 '>' => '>', // we've received invalid input
769 '"' => '"', // which should have been escaped.
772 "''" => '''',
773 'ISBN' => 'ISBN',
775 'PMID' => 'PMID',
781 $encValue = preg_replace_callback(
782 '/(' . wfUrlProtocols() . ')/',
783 array( 'Sanitizer', 'armorLinksCallback' ),
789 * Given a value escape it so that it can be used in an id attribute and
790 * return it, this does not validate the value however (see first link)
792 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
795 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
797 * @param $id String: id to validate
798 * @param $options Mixed: string or array of strings (default is array()):
799 * 'noninitial': This is a non-initial fragment of an id, not a full id,
800 * so don't pay attention if the first character isn't valid at the
801 * beginning of an id.
802 * 'xml': Don't restrict the id to be HTML4-compatible. This option
803 * allows any alphabetic character to be used, per the XML standard.
804 * Therefore, it also completely changes the type of escaping: instead
805 * of weird dot-encoding, runs of invalid characters (mostly
806 * whitespace) are just compressed into a single underscore.
809 static function escapeId( $id, $options = array() ) {
810 $options = (array)$options;
812 if ( !in_array( 'xml', $options ) ) {
813 # HTML4-style escaping
814 static $replace = array(
819 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
820 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
822 if ( !preg_match( '/^[a-zA-Z]/', $id )
823 && !in_array( 'noninitial', $options ) ) {
824 // Initial character must be a letter!
830 # XML-style escaping. For the patterns used, see the XML 1.0 standard,
831 # 5th edition, NameStartChar and NameChar: <http://www.w3.org/TR/REC-xml/>
832 $nameStartChar = ':a-zA-Z_\xC0-\xD6\xD8-\xF6\xF8-\x{2FF}\x{370}-\x{37D}'
833 . '\x{37F}-\x{1FFF}\x{200C}-\x{200D}\x{2070}-\x{218F}\x{2C00}-\x{2FEF}'
834 . '\x{3001}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFFD}\x{10000}-\x{EFFFF}';
835 $nameChar = $nameStartChar . '.\-0-9\xB7\x{0300}-\x{036F}'
836 . '\x{203F}-\x{2040}';
837 # Replace _ as well so we don't get multiple consecutive underscores
838 $id = preg_replace( "/([^$nameChar]|_)+/u", '_', $id );
839 $id = trim( $id, '_' );
841 if ( !preg_match( "/^[$nameStartChar]/u", $id )
842 && !in_array( 'noninitial', $options ) ) {
850 * Given a value, escape it so that it can be used as a CSS class and
853 * @todo For extra validity, input should be validated UTF-8.
855 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
857 * @param $class String
860 static function escapeClass( $class ) {
861 // Convert ugly stuff to underscores and kill underscores in ugly places
862 return rtrim(preg_replace(
863 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
869 * Given HTML input, escape with htmlspecialchars but un-escape entites.
870 * This allows (generally harmless) entities like to survive.
872 * @param $html String to escape
873 * @return String: escaped input
875 static function escapeHtmlAllowEntities( $html ) {
876 # It seems wise to escape ' as well as ", as a matter of course. Can't
878 $html = htmlspecialchars( $html, ENT_QUOTES
);
879 $html = str_replace( '&', '&', $html );
880 $html = Sanitizer
::normalizeCharReferences( $html );
885 * Regex replace callback for armoring links against further processing.
886 * @param $matches Array
889 private static function armorLinksCallback( $matches ) {
890 return str_replace( ':', ':', $matches[1] );
894 * Return an associative array of attribute names and values from
895 * a partial tag string. Attribute names are forces to lowercase,
896 * character references are decoded to UTF-8 text.
898 * @param $text String
901 public static function decodeTagAttributes( $text ) {
904 if( trim( $text ) == '' ) {
917 foreach( $pairs as $set ) {
918 $attribute = strtolower( $set[1] );
919 $value = Sanitizer
::getTagAttributeCallback( $set );
921 // Normalize whitespace
922 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
923 $value = trim( $value );
925 // Decode character references
926 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
932 * Pick the appropriate attribute value from a match set from the
933 * MW_ATTRIBS_REGEX matches.
938 private static function getTagAttributeCallback( $set ) {
939 if( isset( $set[6] ) ) {
940 # Illegal #XXXXXX color with no quotes.
942 } elseif( isset( $set[5] ) ) {
945 } elseif( isset( $set[4] ) ) {
948 } elseif( isset( $set[3] ) ) {
951 } elseif( !isset( $set[2] ) ) {
952 # In XHTML, attributes must have a value.
953 # For 'reduced' form, return explicitly the attribute name here.
956 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
961 * Normalize whitespace and character references in an XML source-
962 * encoded text for an attribute value.
964 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
965 * but note that we're not returning the value, but are returning
966 * XML source fragments that will be slapped into output.
968 * @param $text String
971 private static function normalizeAttributeValue( $text ) {
972 return str_replace( '"', '"',
973 self
::normalizeWhitespace(
974 Sanitizer
::normalizeCharReferences( $text ) ) );
977 private static function normalizeWhitespace( $text ) {
979 '/\r\n|[\x20\x0d\x0a\x09]/',
985 * Ensure that any entities and character references are legal
986 * for XML and XHTML specifically. Any stray bits will be
987 * &-escaped to result in a valid text fragment.
989 * a. any named char refs must be known in XHTML
990 * b. any numeric char refs must be legal chars, not invalid or forbidden
991 * c. use &#x, not &#X
992 * d. fix or reject non-valid attributes
994 * @param $text String
998 static function normalizeCharReferences( $text ) {
999 return preg_replace_callback(
1001 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
1005 * @param $matches String
1008 static function normalizeCharReferencesCallback( $matches ) {
1010 if( $matches[1] != '' ) {
1011 $ret = Sanitizer
::normalizeEntity( $matches[1] );
1012 } elseif( $matches[2] != '' ) {
1013 $ret = Sanitizer
::decCharReference( $matches[2] );
1014 } elseif( $matches[3] != '' ) {
1015 $ret = Sanitizer
::hexCharReference( $matches[3] );
1016 } elseif( $matches[4] != '' ) {
1017 $ret = Sanitizer
::hexCharReference( $matches[4] );
1019 if( is_null( $ret ) ) {
1020 return htmlspecialchars( $matches[0] );
1027 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1028 * return the named entity reference as is. If the entity is a
1029 * MediaWiki-specific alias, returns the HTML equivalent. Otherwise,
1030 * returns HTML-escaped text of pseudo-entity source (eg &foo;)
1032 * @param $name String
1035 static function normalizeEntity( $name ) {
1036 global $wgHtmlEntities, $wgHtmlEntityAliases;
1037 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1038 return "&{$wgHtmlEntityAliases[$name]};";
1039 } elseif( isset( $wgHtmlEntities[$name] ) ) {
1042 return "&$name;";
1046 static function decCharReference( $codepoint ) {
1047 $point = intval( $codepoint );
1048 if( Sanitizer
::validateCodepoint( $point ) ) {
1049 return sprintf( '&#%d;', $point );
1055 static function hexCharReference( $codepoint ) {
1056 $point = hexdec( $codepoint );
1057 if( Sanitizer
::validateCodepoint( $point ) ) {
1058 return sprintf( '&#x%x;', $point );
1065 * Returns true if a given Unicode codepoint is a valid character in XML.
1066 * @param $codepoint Integer
1069 private static function validateCodepoint( $codepoint ) {
1070 return ($codepoint == 0x09)
1071 ||
($codepoint == 0x0a)
1072 ||
($codepoint == 0x0d)
1073 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
1074 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
1075 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
1079 * Decode any character references, numeric or named entities,
1080 * in the text and return a UTF-8 string.
1082 * @param $text String
1085 public static function decodeCharReferences( $text ) {
1086 return preg_replace_callback(
1088 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1093 * @param $matches String
1096 static function decodeCharReferencesCallback( $matches ) {
1097 if( $matches[1] != '' ) {
1098 return Sanitizer
::decodeEntity( $matches[1] );
1099 } elseif( $matches[2] != '' ) {
1100 return Sanitizer
::decodeChar( intval( $matches[2] ) );
1101 } elseif( $matches[3] != '' ) {
1102 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
1103 } elseif( $matches[4] != '' ) {
1104 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
1106 # Last case should be an ampersand by itself
1111 * Return UTF-8 string for a codepoint if that is a valid
1112 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1113 * @param $codepoint Integer
1117 static function decodeChar( $codepoint ) {
1118 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
1119 return codepointToUtf8( $codepoint );
1121 return UTF8_REPLACEMENT
;
1126 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1127 * return the UTF-8 encoding of that character. Otherwise, returns
1128 * pseudo-entity source (eg &foo;)
1130 * @param $name Strings
1133 static function decodeEntity( $name ) {
1134 global $wgHtmlEntities, $wgHtmlEntityAliases;
1135 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1136 $name = $wgHtmlEntityAliases[$name];
1138 if( isset( $wgHtmlEntities[$name] ) ) {
1139 return codepointToUtf8( $wgHtmlEntities[$name] );
1146 * Fetch the whitelist of acceptable attributes for a given element name.
1148 * @param $element String
1151 static function attributeWhitelist( $element ) {
1153 if( !isset( $list ) ) {
1154 $list = Sanitizer
::setupAttributeWhitelist();
1156 return isset( $list[$element] )
1162 * Foreach array key (an allowed HTML element), return an array
1163 * of allowed attributes
1166 static function setupAttributeWhitelist() {
1167 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style',
1168 #RDFa attributes as specified in section 9 of http://www.w3.org/TR/2008/REC-rdfa-syntax-20081014
1169 'about', 'property', 'resource', 'datatype', 'typeof',
1172 $block = array_merge( $common, array( 'align' ) );
1173 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1174 $tablecell = array( 'abbr',
1180 'nowrap', # deprecated
1181 'width', # deprecated
1182 'height', # deprecated
1183 'bgcolor' # deprecated
1186 # Numbers refer to sections in HTML 4.01 standard describing the element.
1187 # See: http://www.w3.org/TR/html4/
1188 $whitelist = array (
1191 'center' => $common, # deprecated
1192 'span' => $block, # ??
1210 'strong' => $common,
1221 'blockquote' => array_merge( $common, array( 'cite' ) ),
1232 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1235 'pre' => array_merge( $common, array( 'width' ) ),
1238 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1239 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1242 'ul' => array_merge( $common, array( 'type' ) ),
1243 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1244 'li' => array_merge( $common, array( 'type', 'value' ) ),
1252 'table' => array_merge( $common,
1253 array( 'summary', 'width', 'border', 'frame',
1254 'rules', 'cellspacing', 'cellpadding',
1259 'caption' => array_merge( $common, array( 'align' ) ),
1262 'thead' => array_merge( $common, $tablealign ),
1263 'tfoot' => array_merge( $common, $tablealign ),
1264 'tbody' => array_merge( $common, $tablealign ),
1267 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1268 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1271 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1274 'td' => array_merge( $common, $tablecell, $tablealign ),
1275 'th' => array_merge( $common, $tablecell, $tablealign ),
1278 # Not usually allowed, but may be used for extension-style hooks
1279 # such as <math> when it is rasterized
1280 'img' => array_merge( $common, array( 'alt' ) ),
1288 'strike' => $common,
1293 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1297 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1299 # XHTML Ruby annotation text module, simple ruby only.
1300 # http://www.w3c.org/TR/ruby/
1305 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1308 # MathML root element, where used for extensions
1309 # 'title' may not be 100% valid here; it's XHTML
1310 # http://www.w3.org/TR/REC-MathML/
1311 'math' => array( 'class', 'style', 'id', 'title' ),
1317 * Take a fragment of (potentially invalid) HTML and return
1318 * a version with any tags removed, encoded as plain text.
1320 * Warning: this return value must be further escaped for literal
1321 * inclusion in HTML output as of 1.10!
1323 * @param $text String: HTML fragment
1326 static function stripAllTags( $text ) {
1328 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
1330 # Normalize &entities and whitespace
1331 $text = self
::decodeCharReferences( $text );
1332 $text = self
::normalizeWhitespace( $text );
1338 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1339 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1342 * Use for passing XHTML fragments to PHP's XML parsing functions
1346 static function hackDocType() {
1347 global $wgHtmlEntities;
1348 $out = "<!DOCTYPE html [\n";
1349 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1350 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1356 static function cleanUrl( $url ) {
1357 # Normalize any HTML entities in input. They will be
1358 # re-escaped by makeExternalLink().
1359 $url = Sanitizer
::decodeCharReferences( $url );
1361 # Escape any control characters introduced by the above step
1362 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1364 # Validate hostname portion
1366 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1367 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1369 // Characters that will be ignored in IDNs.
1370 // http://tools.ietf.org/html/3454#section-3.1
1371 // Strip them before further processing so blacklists and such work.
1373 \\s| # general whitespace
1374 \xc2\xad| # 00ad SOFT HYPHEN
1375 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1376 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1377 \xe2\x81\xa0| # 2060 WORD JOINER
1378 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1379 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1380 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1381 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1382 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1383 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1384 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1385 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1388 $host = preg_replace( $strip, '', $host );
1390 // @fixme: validate hostnames here
1392 return $protocol . $host . $rest;