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 const INITIAL_NONLETTER
= 1;
338 * Cleans up HTML, removes dangerous tags and attributes, and
339 * removes HTML comments
341 * @param string $text
342 * @param callback $processCallback to do any variable or parameter replacements in HTML attribute values
343 * @param array $args for the processing callback
346 static function removeHTMLtags( $text, $processCallback = null, $args = array(), $extratags = array() ) {
349 static $htmlpairs, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
350 $htmllist, $listtags, $htmlsingleallowed, $htmlelements, $staticInitialised;
352 wfProfileIn( __METHOD__
);
354 if ( !$staticInitialised ) {
356 $htmlpairs = array_merge( $extratags, array( # Tags that must be closed
357 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
358 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
359 'strike', 'strong', 'tt', 'var', 'div', 'center',
360 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
361 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span', 'u'
364 'br', 'hr', 'li', 'dt', 'dd'
366 $htmlsingleonly = array( # Elements that cannot have close tags
369 $htmlnest = array( # Tags that can be nested--??
370 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
371 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
373 $tabletags = array( # Can only appear inside table, we will close them
376 $htmllist = array( # Tags used by list
379 $listtags = array( # Tags that can appear in a list
383 $htmlsingleallowed = array_merge( $htmlsingle, $tabletags );
384 $htmlelements = array_merge( $htmlsingle, $htmlpairs, $htmlnest );
386 # Convert them all to hashtables for faster lookup
387 $vars = array( 'htmlpairs', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
388 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelements' );
389 foreach ( $vars as $var ) {
390 $
$var = array_flip( $
$var );
392 $staticInitialised = true;
395 # Remove HTML comments
396 $text = Sanitizer
::removeHTMLcomments( $text );
397 $bits = explode( '<', $text );
398 $text = str_replace( '>', '>', array_shift( $bits ) );
400 $tagstack = $tablestack = array();
401 foreach ( $bits as $x ) {
403 if( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
404 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
406 $slash = $t = $params = $brace = $rest = null;
410 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
414 if( isset( $htmlsingleonly[$t] ) ) {
416 } elseif ( ( $ot = @array_pop
( $tagstack ) ) != $t ) {
417 if ( isset( $htmlsingleallowed[$ot] ) ) {
418 # Pop all elements with an optional close tag
419 # and see if we find a match below them
421 array_push ($optstack, $ot);
422 while ( ( ( $ot = @array_pop
( $tagstack ) ) != $t ) &&
423 isset( $htmlsingleallowed[$ot] ) )
425 array_push ($optstack, $ot);
428 # No match. Push the optinal elements back again
430 while ( $ot = @array_pop
( $optstack ) ) {
431 array_push( $tagstack, $ot );
435 @array_push
( $tagstack, $ot );
436 # <li> can be nested in <ul> or <ol>, skip those cases:
437 if(!(isset( $htmllist[$ot] ) && isset( $listtags[$t] ) )) {
442 if ( $t == 'table' ) {
443 $tagstack = array_pop( $tablestack );
448 # Keep track for later
449 if ( isset( $tabletags[$t] ) &&
450 ! in_array( 'table', $tagstack ) ) {
452 } else if ( in_array( $t, $tagstack ) &&
453 ! isset( $htmlnest [$t ] ) ) {
455 #Â Is it a self closed htmlpair ? (bug 5487)
456 } else if( $brace == '/>' &&
457 isset( $htmlpairs[$t] ) ) {
459 } elseif( isset( $htmlsingleonly[$t] ) ) {
460 # Hack to force empty tag for uncloseable elements
462 } else if( isset( $htmlsingle[$t] ) ) {
463 # Hack to not close $htmlsingle tags
465 } else if( isset( $tabletags[$t] )
466 && in_array($t ,$tagstack) ) {
467 // New table tag but forgot to close the previous one
470 if ( $t == 'table' ) {
471 array_push( $tablestack, $tagstack );
474 array_push( $tagstack, $t );
477 # Replace any variables or template parameters with
479 if( is_callable( $processCallback ) ) {
480 call_user_func_array( $processCallback, array( &$params, $args ) );
483 # Strip non-approved attributes from the tag
484 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
487 $rest = str_replace( '>', '>', $rest );
488 $close = ( $brace == '/>' && !$slash ) ?
' /' : '';
489 $text .= "<$slash$t$newparams$close>$rest";
493 $text .= '<' . str_replace( '>', '>', $x);
495 # Close off any remaining tags
496 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
498 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
501 # this might be possible using tidy itself
502 foreach ( $bits as $x ) {
503 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
505 @list
( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
506 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
507 if( is_callable( $processCallback ) ) {
508 call_user_func_array( $processCallback, array( &$params, $args ) );
510 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
511 $rest = str_replace( '>', '>', $rest );
512 $text .= "<$slash$t$newparams$brace$rest";
514 $text .= '<' . str_replace( '>', '>', $x);
518 wfProfileOut( __METHOD__
);
523 * Remove '<!--', '-->', and everything between.
524 * To avoid leaving blank lines, when a comment is both preceded
525 * and followed by a newline (ignoring spaces), trim leading and
526 * trailing spaces and one of the newlines.
529 * @param string $text
532 static function removeHTMLcomments( $text ) {
533 wfProfileIn( __METHOD__
);
534 while (($start = strpos($text, '<!--')) !== false) {
535 $end = strpos($text, '-->', $start +
4);
536 if ($end === false) {
537 # Unterminated comment; bail out
543 # Trim space and newline if the comment is both
544 # preceded and followed by a newline
545 $spaceStart = max($start - 1, 0);
546 $spaceLen = $end - $spaceStart;
547 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
551 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
553 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
554 # Remove the comment, leading and trailing
555 # spaces, and leave only one newline.
556 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
559 # Remove just the comment.
560 $text = substr_replace($text, '', $start, $end - $start);
563 wfProfileOut( __METHOD__
);
568 * Take an array of attribute names and values and normalize or discard
569 * illegal values for the given element type.
571 * - Discards attributes not on a whitelist for the given element
572 * - Unsafe style attributes are discarded
573 * - Invalid id attributes are reencoded
575 * @param array $attribs
576 * @param string $element
579 * @todo Check for legal values where the DTD limits things.
580 * @todo Check for unique id attribute :P
582 static function validateTagAttributes( $attribs, $element ) {
583 return Sanitizer
::validateAttributes( $attribs,
584 Sanitizer
::attributeWhitelist( $element ) );
588 * Take an array of attribute names and values and normalize or discard
589 * illegal values for the given whitelist.
591 * - Discards attributes not the given whitelist
592 * - Unsafe style attributes are discarded
593 * - Invalid id attributes are reencoded
595 * @param array $attribs
596 * @param array $whitelist list of allowed attribute names
599 * @todo Check for legal values where the DTD limits things.
600 * @todo Check for unique id attribute :P
602 static function validateAttributes( $attribs, $whitelist ) {
603 $whitelist = array_flip( $whitelist );
605 foreach( $attribs as $attribute => $value ) {
606 if( !isset( $whitelist[$attribute] ) ) {
609 # Strip javascript "expression" from stylesheets.
610 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
611 if( $attribute == 'style' ) {
612 $value = Sanitizer
::checkCss( $value );
613 if( $value === false ) {
619 if ( $attribute === 'id' )
620 $value = Sanitizer
::escapeId( $value );
622 // If this attribute was previously set, override it.
623 // Output should only have one attribute of each name.
624 $out[$attribute] = $value;
630 * Merge two sets of HTML attributes. Conflicting items in the second set
631 * will override those in the first, except for 'class' attributes which
632 * will be combined (if they're both strings).
634 * @todo implement merging for other attributes such as style
639 static function mergeAttributes( $a, $b ) {
640 $out = array_merge( $a, $b );
641 if( isset( $a['class'] ) && isset( $b['class'] )
642 && is_string( $a['class'] ) && is_string( $b['class'] )
643 && $a['class'] !== $b['class'] ) {
644 $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
645 -1, PREG_SPLIT_NO_EMPTY
);
646 $out['class'] = implode( ' ', array_unique( $classes ) );
652 * Pick apart some CSS and check it for forbidden or unsafe structures.
653 * Returns a sanitized string, or false if it was just too evil.
655 * Currently URL references, 'expression', 'tps' are forbidden.
657 * @param string $value
660 static function checkCss( $value ) {
661 $stripped = Sanitizer
::decodeCharReferences( $value );
663 // Remove any comments; IE gets token splitting wrong
664 $stripped = StringUtils
::delimiterReplace( '/*', '*/', ' ', $stripped );
668 // ... and continue checks
669 $stripped = preg_replace( '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!e',
670 'codepointToUtf8(hexdec("$1"))', $stripped );
671 $stripped = str_replace( '\\', '', $stripped );
672 if( preg_match( '/(?:expression|tps*:\/\/|url\\s*\().*/is',
682 * Take a tag soup fragment listing an HTML element's attributes
683 * and normalize it to well-formed XML, discarding unwanted attributes.
684 * Output is safe for further wikitext processing, with escaping of
685 * values that could trigger problems.
687 * - Normalizes attribute names to lowercase
688 * - Discards attributes not on a whitelist for the given element
689 * - Turns broken or invalid entities into plaintext
690 * - Double-quotes all attribute values
691 * - Attributes without values are given the name as attribute
692 * - Double attributes are discarded
693 * - Unsafe style attributes are discarded
694 * - Prepends space if there are attributes.
696 * @param string $text
697 * @param string $element
700 static function fixTagAttributes( $text, $element ) {
701 if( trim( $text ) == '' ) {
705 $stripped = Sanitizer
::validateTagAttributes(
706 Sanitizer
::decodeTagAttributes( $text ), $element );
709 foreach( $stripped as $attribute => $value ) {
710 $encAttribute = htmlspecialchars( $attribute );
711 $encValue = Sanitizer
::safeEncodeAttribute( $value );
713 $attribs[] = "$encAttribute=\"$encValue\"";
715 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
719 * Encode an attribute value for HTML output.
721 * @return HTML-encoded text fragment
723 static function encodeAttribute( $text ) {
724 $encValue = htmlspecialchars( $text, ENT_QUOTES
);
726 // Whitespace is normalized during attribute decoding,
727 // so if we've been passed non-spaces we must encode them
728 // ahead of time or they won't be preserved.
729 $encValue = strtr( $encValue, array(
739 * Encode an attribute value for HTML tags, with extra armoring
740 * against further wiki processing.
742 * @return HTML-encoded text fragment
744 static function safeEncodeAttribute( $text ) {
745 $encValue = Sanitizer
::encodeAttribute( $text );
747 # Templates and links may be expanded in later parsing,
748 # creating invalid or dangerous output. Suppress this.
749 $encValue = strtr( $encValue, array(
750 '<' => '<', // This should never happen,
751 '>' => '>', // we've received invalid input
752 '"' => '"', // which should have been escaped.
755 "''" => '''',
756 'ISBN' => 'ISBN',
758 'PMID' => 'PMID',
764 $encValue = preg_replace_callback(
765 '/(' . wfUrlProtocols() . ')/',
766 array( 'Sanitizer', 'armorLinksCallback' ),
772 * Given a value escape it so that it can be used in an id attribute and
773 * return it, this does not validate the value however (see first link)
775 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
778 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
780 * @param string $id Id to validate
781 * @param int $flags Currently only two values: Sanitizer::INITIAL_NONLETTER
782 * (default) permits initial non-letter characters,
783 * such as if you're adding a prefix to them.
784 * Sanitizer::NONE will prepend an 'x' if the id
785 * would otherwise start with a nonletter.
788 static function escapeId( $id, $flags = Sanitizer
::INITIAL_NONLETTER
) {
789 static $replace = array(
794 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
795 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
797 if( ~
$flags & Sanitizer
::INITIAL_NONLETTER
798 && !preg_match( '/[a-zA-Z]/', $id[0] ) ) {
799 // Initial character must be a letter!
806 * Given a value, escape it so that it can be used as a CSS class and
809 * @todo For extra validity, input should be validated UTF-8.
811 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
813 * @param string $class
816 static function escapeClass( $class ) {
817 // Convert ugly stuff to underscores and kill underscores in ugly places
818 return rtrim(preg_replace(
819 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
825 * Given HTML input, escape with htmlspecialchars but un-escape entites.
826 * This allows (generally harmless) entities like to survive.
828 * @param string $html String to escape
829 * @return string Escaped input
831 static function escapeHtmlAllowEntities( $html ) {
832 # It seems wise to escape ' as well as ", as a matter of course. Can't
834 $html = htmlspecialchars( $html, ENT_QUOTES
);
835 $html = str_replace( '&', '&', $html );
836 $html = Sanitizer
::normalizeCharReferences( $html );
841 * Regex replace callback for armoring links against further processing.
842 * @param array $matches
846 private static function armorLinksCallback( $matches ) {
847 return str_replace( ':', ':', $matches[1] );
851 * Return an associative array of attribute names and values from
852 * a partial tag string. Attribute names are forces to lowercase,
853 * character references are decoded to UTF-8 text.
858 public static function decodeTagAttributes( $text ) {
861 if( trim( $text ) == '' ) {
874 foreach( $pairs as $set ) {
875 $attribute = strtolower( $set[1] );
876 $value = Sanitizer
::getTagAttributeCallback( $set );
878 // Normalize whitespace
879 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
880 $value = trim( $value );
882 // Decode character references
883 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
889 * Pick the appropriate attribute value from a match set from the
890 * MW_ATTRIBS_REGEX matches.
896 private static function getTagAttributeCallback( $set ) {
897 if( isset( $set[6] ) ) {
898 # Illegal #XXXXXX color with no quotes.
900 } elseif( isset( $set[5] ) ) {
903 } elseif( isset( $set[4] ) ) {
906 } elseif( isset( $set[3] ) ) {
909 } elseif( !isset( $set[2] ) ) {
910 # In XHTML, attributes must have a value.
911 # For 'reduced' form, return explicitly the attribute name here.
914 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
919 * Normalize whitespace and character references in an XML source-
920 * encoded text for an attribute value.
922 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
923 * but note that we're not returning the value, but are returning
924 * XML source fragments that will be slapped into output.
926 * @param string $text
930 private static function normalizeAttributeValue( $text ) {
931 return str_replace( '"', '"',
932 self
::normalizeWhitespace(
933 Sanitizer
::normalizeCharReferences( $text ) ) );
936 private static function normalizeWhitespace( $text ) {
938 '/\r\n|[\x20\x0d\x0a\x09]/',
944 * Ensure that any entities and character references are legal
945 * for XML and XHTML specifically. Any stray bits will be
946 * &-escaped to result in a valid text fragment.
948 * a. any named char refs must be known in XHTML
949 * b. any numeric char refs must be legal chars, not invalid or forbidden
950 * c. use &#x, not &#X
951 * d. fix or reject non-valid attributes
953 * @param string $text
957 static function normalizeCharReferences( $text ) {
958 return preg_replace_callback(
960 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
964 * @param string $matches
967 static function normalizeCharReferencesCallback( $matches ) {
969 if( $matches[1] != '' ) {
970 $ret = Sanitizer
::normalizeEntity( $matches[1] );
971 } elseif( $matches[2] != '' ) {
972 $ret = Sanitizer
::decCharReference( $matches[2] );
973 } elseif( $matches[3] != '' ) {
974 $ret = Sanitizer
::hexCharReference( $matches[3] );
975 } elseif( $matches[4] != '' ) {
976 $ret = Sanitizer
::hexCharReference( $matches[4] );
978 if( is_null( $ret ) ) {
979 return htmlspecialchars( $matches[0] );
986 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
987 * return the named entity reference as is. If the entity is a
988 * MediaWiki-specific alias, returns the HTML equivalent. Otherwise,
989 * returns HTML-escaped text of pseudo-entity source (eg &foo;)
991 * @param string $name
995 static function normalizeEntity( $name ) {
996 global $wgHtmlEntities, $wgHtmlEntityAliases;
997 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
998 return "&{$wgHtmlEntityAliases[$name]};";
999 } elseif( isset( $wgHtmlEntities[$name] ) ) {
1002 return "&$name;";
1006 static function decCharReference( $codepoint ) {
1007 $point = intval( $codepoint );
1008 if( Sanitizer
::validateCodepoint( $point ) ) {
1009 return sprintf( '&#%d;', $point );
1015 static function hexCharReference( $codepoint ) {
1016 $point = hexdec( $codepoint );
1017 if( Sanitizer
::validateCodepoint( $point ) ) {
1018 return sprintf( '&#x%x;', $point );
1025 * Returns true if a given Unicode codepoint is a valid character in XML.
1026 * @param int $codepoint
1029 private static function validateCodepoint( $codepoint ) {
1030 return ($codepoint == 0x09)
1031 ||
($codepoint == 0x0a)
1032 ||
($codepoint == 0x0d)
1033 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
1034 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
1035 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
1039 * Decode any character references, numeric or named entities,
1040 * in the text and return a UTF-8 string.
1042 * @param string $text
1047 public static function decodeCharReferences( $text ) {
1048 return preg_replace_callback(
1050 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1055 * @param string $matches
1058 static function decodeCharReferencesCallback( $matches ) {
1059 if( $matches[1] != '' ) {
1060 return Sanitizer
::decodeEntity( $matches[1] );
1061 } elseif( $matches[2] != '' ) {
1062 return Sanitizer
::decodeChar( intval( $matches[2] ) );
1063 } elseif( $matches[3] != '' ) {
1064 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
1065 } elseif( $matches[4] != '' ) {
1066 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
1068 # Last case should be an ampersand by itself
1073 * Return UTF-8 string for a codepoint if that is a valid
1074 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1075 * @param int $codepoint
1079 static function decodeChar( $codepoint ) {
1080 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
1081 return codepointToUtf8( $codepoint );
1083 return UTF8_REPLACEMENT
;
1088 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1089 * return the UTF-8 encoding of that character. Otherwise, returns
1090 * pseudo-entity source (eg &foo;)
1092 * @param string $name
1095 static function decodeEntity( $name ) {
1096 global $wgHtmlEntities, $wgHtmlEntityAliases;
1097 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1098 $name = $wgHtmlEntityAliases[$name];
1100 if( isset( $wgHtmlEntities[$name] ) ) {
1101 return codepointToUtf8( $wgHtmlEntities[$name] );
1108 * Fetch the whitelist of acceptable attributes for a given
1111 * @param string $element
1114 static function attributeWhitelist( $element ) {
1116 if( !isset( $list ) ) {
1117 $list = Sanitizer
::setupAttributeWhitelist();
1119 return isset( $list[$element] )
1125 * @todo Document it a bit
1128 static function setupAttributeWhitelist() {
1129 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1130 $block = array_merge( $common, array( 'align' ) );
1131 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1132 $tablecell = array( 'abbr',
1138 'nowrap', # deprecated
1139 'width', # deprecated
1140 'height', # deprecated
1141 'bgcolor' # deprecated
1144 # Numbers refer to sections in HTML 4.01 standard describing the element.
1145 # See: http://www.w3.org/TR/html4/
1146 $whitelist = array (
1149 'center' => $common, # deprecated
1150 'span' => $block, # ??
1168 'strong' => $common,
1179 'blockquote' => array_merge( $common, array( 'cite' ) ),
1190 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1193 'pre' => array_merge( $common, array( 'width' ) ),
1196 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1197 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1200 'ul' => array_merge( $common, array( 'type' ) ),
1201 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1202 'li' => array_merge( $common, array( 'type', 'value' ) ),
1210 'table' => array_merge( $common,
1211 array( 'summary', 'width', 'border', 'frame',
1212 'rules', 'cellspacing', 'cellpadding',
1217 'caption' => array_merge( $common, array( 'align' ) ),
1220 'thead' => array_merge( $common, $tablealign ),
1221 'tfoot' => array_merge( $common, $tablealign ),
1222 'tbody' => array_merge( $common, $tablealign ),
1225 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1226 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1229 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1232 'td' => array_merge( $common, $tablecell, $tablealign ),
1233 'th' => array_merge( $common, $tablecell, $tablealign ),
1236 # Not usually allowed, but may be used for extension-style hooks
1237 # such as <math> when it is rasterized
1238 'img' => array_merge( $common, array( 'alt' ) ),
1246 'strike' => $common,
1251 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1255 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1257 # XHTML Ruby annotation text module, simple ruby only.
1258 # http://www.w3c.org/TR/ruby/
1263 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1266 # MathML root element, where used for extensions
1267 # 'title' may not be 100% valid here; it's XHTML
1268 # http://www.w3.org/TR/REC-MathML/
1269 'math' => array( 'class', 'style', 'id', 'title' ),
1275 * Take a fragment of (potentially invalid) HTML and return
1276 * a version with any tags removed, encoded as plain text.
1278 * Warning: this return value must be further escaped for literal
1279 * inclusion in HTML output as of 1.10!
1281 * @param string $text HTML fragment
1284 static function stripAllTags( $text ) {
1286 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
1288 # Normalize &entities and whitespace
1289 $text = self
::decodeCharReferences( $text );
1290 $text = self
::normalizeWhitespace( $text );
1296 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1297 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1300 * Use for passing XHTML fragments to PHP's XML parsing functions
1305 static function hackDocType() {
1306 global $wgHtmlEntities;
1307 $out = "<!DOCTYPE html [\n";
1308 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1309 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1315 static function cleanUrl( $url ) {
1316 # Normalize any HTML entities in input. They will be
1317 # re-escaped by makeExternalLink().
1318 $url = Sanitizer
::decodeCharReferences( $url );
1320 # Escape any control characters introduced by the above step
1321 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1323 # Validate hostname portion
1325 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1326 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1328 // Characters that will be ignored in IDNs.
1329 // http://tools.ietf.org/html/3454#section-3.1
1330 // Strip them before further processing so blacklists and such work.
1332 \\s| # general whitespace
1333 \xc2\xad| # 00ad SOFT HYPHEN
1334 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1335 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1336 \xe2\x81\xa0| # 2060 WORD JOINER
1337 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1338 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1339 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1340 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1341 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1342 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1343 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1344 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1347 $host = preg_replace( $strip, '', $host );
1349 // @fixme: validate hostnames here
1351 return $protocol . $host . $rest;