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 string $text
339 * @param callback $processCallback to do any variable or parameter replacements in HTML attribute values
340 * @param array $args for the processing callback
343 static function removeHTMLtags( $text, $processCallback = null, $args = array(), $extratags = array() ) {
346 static $htmlpairs, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
347 $htmllist, $listtags, $htmlsingleallowed, $htmlelements, $staticInitialised;
349 wfProfileIn( __METHOD__
);
351 if ( !$staticInitialised ) {
353 $htmlpairs = array_merge( $extratags, array( # Tags that must be closed
354 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
355 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
356 'strike', 'strong', 'tt', 'var', 'div', 'center',
357 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
358 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span', 'u'
361 'br', 'hr', 'li', 'dt', 'dd'
363 $htmlsingleonly = array( # Elements that cannot have close tags
366 $htmlnest = array( # Tags that can be nested--??
367 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
368 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
370 $tabletags = array( # Can only appear inside table, we will close them
373 $htmllist = array( # Tags used by list
376 $listtags = array( # Tags that can appear in a list
380 $htmlsingleallowed = array_merge( $htmlsingle, $tabletags );
381 $htmlelements = array_merge( $htmlsingle, $htmlpairs, $htmlnest );
383 # Convert them all to hashtables for faster lookup
384 $vars = array( 'htmlpairs', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
385 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelements' );
386 foreach ( $vars as $var ) {
387 $
$var = array_flip( $
$var );
389 $staticInitialised = true;
392 # Remove HTML comments
393 $text = Sanitizer
::removeHTMLcomments( $text );
394 $bits = explode( '<', $text );
395 $text = str_replace( '>', '>', array_shift( $bits ) );
397 $tagstack = $tablestack = array();
398 foreach ( $bits as $x ) {
400 if( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
401 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
403 $slash = $t = $params = $brace = $rest = null;
407 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
411 if( isset( $htmlsingleonly[$t] ) ) {
413 } elseif ( ( $ot = @array_pop
( $tagstack ) ) != $t ) {
414 if ( isset( $htmlsingleallowed[$ot] ) ) {
415 # Pop all elements with an optional close tag
416 # and see if we find a match below them
418 array_push ($optstack, $ot);
419 while ( ( ( $ot = @array_pop
( $tagstack ) ) != $t ) &&
420 isset( $htmlsingleallowed[$ot] ) )
422 array_push ($optstack, $ot);
425 # No match. Push the optinal elements back again
427 while ( $ot = @array_pop
( $optstack ) ) {
428 array_push( $tagstack, $ot );
432 @array_push
( $tagstack, $ot );
433 # <li> can be nested in <ul> or <ol>, skip those cases:
434 if(!(isset( $htmllist[$ot] ) && isset( $listtags[$t] ) )) {
439 if ( $t == 'table' ) {
440 $tagstack = array_pop( $tablestack );
445 # Keep track for later
446 if ( isset( $tabletags[$t] ) &&
447 ! in_array( 'table', $tagstack ) ) {
449 } else if ( in_array( $t, $tagstack ) &&
450 ! isset( $htmlnest [$t ] ) ) {
452 #Â Is it a self closed htmlpair ? (bug 5487)
453 } else if( $brace == '/>' &&
454 isset( $htmlpairs[$t] ) ) {
456 } elseif( isset( $htmlsingleonly[$t] ) ) {
457 # Hack to force empty tag for uncloseable elements
459 } else if( isset( $htmlsingle[$t] ) ) {
460 # Hack to not close $htmlsingle tags
462 } else if( isset( $tabletags[$t] )
463 && in_array($t ,$tagstack) ) {
464 // New table tag but forgot to close the previous one
467 if ( $t == 'table' ) {
468 array_push( $tablestack, $tagstack );
471 array_push( $tagstack, $t );
474 # Replace any variables or template parameters with
476 if( is_callable( $processCallback ) ) {
477 call_user_func_array( $processCallback, array( &$params, $args ) );
480 # Strip non-approved attributes from the tag
481 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
484 $rest = str_replace( '>', '>', $rest );
485 $close = ( $brace == '/>' && !$slash ) ?
' /' : '';
486 $text .= "<$slash$t$newparams$close>$rest";
490 $text .= '<' . str_replace( '>', '>', $x);
492 # Close off any remaining tags
493 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
495 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
498 # this might be possible using tidy itself
499 foreach ( $bits as $x ) {
500 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
502 @list
( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
503 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
504 if( is_callable( $processCallback ) ) {
505 call_user_func_array( $processCallback, array( &$params, $args ) );
507 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
508 $rest = str_replace( '>', '>', $rest );
509 $text .= "<$slash$t$newparams$brace$rest";
511 $text .= '<' . str_replace( '>', '>', $x);
515 wfProfileOut( __METHOD__
);
520 * Remove '<!--', '-->', and everything between.
521 * To avoid leaving blank lines, when a comment is both preceded
522 * and followed by a newline (ignoring spaces), trim leading and
523 * trailing spaces and one of the newlines.
526 * @param string $text
529 static function removeHTMLcomments( $text ) {
530 wfProfileIn( __METHOD__
);
531 while (($start = strpos($text, '<!--')) !== false) {
532 $end = strpos($text, '-->', $start +
4);
533 if ($end === false) {
534 # Unterminated comment; bail out
540 # Trim space and newline if the comment is both
541 # preceded and followed by a newline
542 $spaceStart = max($start - 1, 0);
543 $spaceLen = $end - $spaceStart;
544 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
548 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
550 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
551 # Remove the comment, leading and trailing
552 # spaces, and leave only one newline.
553 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
556 # Remove just the comment.
557 $text = substr_replace($text, '', $start, $end - $start);
560 wfProfileOut( __METHOD__
);
565 * Take an array of attribute names and values and normalize or discard
566 * illegal values for the given element type.
568 * - Discards attributes not on a whitelist for the given element
569 * - Unsafe style attributes are discarded
570 * - Invalid id attributes are reencoded
572 * @param array $attribs
573 * @param string $element
576 * @todo Check for legal values where the DTD limits things.
577 * @todo Check for unique id attribute :P
579 static function validateTagAttributes( $attribs, $element ) {
580 return Sanitizer
::validateAttributes( $attribs,
581 Sanitizer
::attributeWhitelist( $element ) );
585 * Take an array of attribute names and values and normalize or discard
586 * illegal values for the given whitelist.
588 * - Discards attributes not the given whitelist
589 * - Unsafe style attributes are discarded
590 * - Invalid id attributes are reencoded
592 * @param array $attribs
593 * @param array $whitelist list of allowed attribute names
596 * @todo Check for legal values where the DTD limits things.
597 * @todo Check for unique id attribute :P
599 static function validateAttributes( $attribs, $whitelist ) {
600 $whitelist = array_flip( $whitelist );
602 foreach( $attribs as $attribute => $value ) {
603 if( !isset( $whitelist[$attribute] ) ) {
606 # Strip javascript "expression" from stylesheets.
607 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
608 if( $attribute == 'style' ) {
609 $value = Sanitizer
::checkCss( $value );
610 if( $value === false ) {
616 if ( $attribute === 'id' )
617 $value = Sanitizer
::escapeId( $value );
619 // If this attribute was previously set, override it.
620 // Output should only have one attribute of each name.
621 $out[$attribute] = $value;
627 * Merge two sets of HTML attributes. Conflicting items in the second set
628 * will override those in the first, except for 'class' attributes which
629 * will be combined (if they're both strings).
631 * @todo implement merging for other attributes such as style
636 static function mergeAttributes( $a, $b ) {
637 $out = array_merge( $a, $b );
638 if( isset( $a['class'] ) && isset( $b['class'] )
639 && is_string( $a['class'] ) && is_string( $b['class'] )
640 && $a['class'] !== $b['class'] ) {
641 $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
642 -1, PREG_SPLIT_NO_EMPTY
);
643 $out['class'] = implode( ' ', array_unique( $classes ) );
649 * Pick apart some CSS and check it for forbidden or unsafe structures.
650 * Returns a sanitized string, or false if it was just too evil.
652 * Currently URL references, 'expression', 'tps' are forbidden.
654 * @param string $value
657 static function checkCss( $value ) {
658 $stripped = Sanitizer
::decodeCharReferences( $value );
660 // Remove any comments; IE gets token splitting wrong
661 $stripped = StringUtils
::delimiterReplace( '/*', '*/', ' ', $stripped );
665 // ... and continue checks
666 $stripped = preg_replace( '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!e',
667 'codepointToUtf8(hexdec("$1"))', $stripped );
668 $stripped = str_replace( '\\', '', $stripped );
669 if( preg_match( '/(?:expression|tps*:\/\/|url\\s*\().*/is',
679 * Take a tag soup fragment listing an HTML element's attributes
680 * and normalize it to well-formed XML, discarding unwanted attributes.
681 * Output is safe for further wikitext processing, with escaping of
682 * values that could trigger problems.
684 * - Normalizes attribute names to lowercase
685 * - Discards attributes not on a whitelist for the given element
686 * - Turns broken or invalid entities into plaintext
687 * - Double-quotes all attribute values
688 * - Attributes without values are given the name as attribute
689 * - Double attributes are discarded
690 * - Unsafe style attributes are discarded
691 * - Prepends space if there are attributes.
693 * @param string $text
694 * @param string $element
697 static function fixTagAttributes( $text, $element ) {
698 if( trim( $text ) == '' ) {
702 $stripped = Sanitizer
::validateTagAttributes(
703 Sanitizer
::decodeTagAttributes( $text ), $element );
706 foreach( $stripped as $attribute => $value ) {
707 $encAttribute = htmlspecialchars( $attribute );
708 $encValue = Sanitizer
::safeEncodeAttribute( $value );
710 $attribs[] = "$encAttribute=\"$encValue\"";
712 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
716 * Encode an attribute value for HTML output.
718 * @return HTML-encoded text fragment
720 static function encodeAttribute( $text ) {
721 $encValue = htmlspecialchars( $text, ENT_QUOTES
);
723 // Whitespace is normalized during attribute decoding,
724 // so if we've been passed non-spaces we must encode them
725 // ahead of time or they won't be preserved.
726 $encValue = strtr( $encValue, array(
736 * Encode an attribute value for HTML tags, with extra armoring
737 * against further wiki processing.
739 * @return HTML-encoded text fragment
741 static function safeEncodeAttribute( $text ) {
742 $encValue = Sanitizer
::encodeAttribute( $text );
744 # Templates and links may be expanded in later parsing,
745 # creating invalid or dangerous output. Suppress this.
746 $encValue = strtr( $encValue, array(
747 '<' => '<', // This should never happen,
748 '>' => '>', // we've received invalid input
749 '"' => '"', // which should have been escaped.
752 "''" => '''',
753 'ISBN' => 'ISBN',
755 'PMID' => 'PMID',
761 $encValue = preg_replace_callback(
762 '/(' . wfUrlProtocols() . ')/',
763 array( 'Sanitizer', 'armorLinksCallback' ),
769 * Given a value escape it so that it can be used in an id attribute and
770 * return it, this does not validate the value however (see first link)
772 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
775 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
777 * @param string $id Id to validate
778 * @param mixed $options String or array of strings (default is array()):
779 * 'noninitial': This is a non-initial fragment of an id, not a full id,
780 * so don't prepend an 'x' if the first character isn't valid at the
781 * beginning of an id.
784 static function escapeId( $id, $options = array() ) {
785 $options = (array)$options;
786 static $replace = array(
791 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
792 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
794 if( preg_match( '/[^a-zA-Z]/', $id[0] )
795 && !in_array( 'noninitial', $options ) ) {
796 // Initial character must be a letter!
803 * Given a value, escape it so that it can be used as a CSS class and
806 * @todo For extra validity, input should be validated UTF-8.
808 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
810 * @param string $class
813 static function escapeClass( $class ) {
814 // Convert ugly stuff to underscores and kill underscores in ugly places
815 return rtrim(preg_replace(
816 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
822 * Given HTML input, escape with htmlspecialchars but un-escape entites.
823 * This allows (generally harmless) entities like to survive.
825 * @param string $html String to escape
826 * @return string Escaped input
828 static function escapeHtmlAllowEntities( $html ) {
829 # It seems wise to escape ' as well as ", as a matter of course. Can't
831 $html = htmlspecialchars( $html, ENT_QUOTES
);
832 $html = str_replace( '&', '&', $html );
833 $html = Sanitizer
::normalizeCharReferences( $html );
838 * Regex replace callback for armoring links against further processing.
839 * @param array $matches
843 private static function armorLinksCallback( $matches ) {
844 return str_replace( ':', ':', $matches[1] );
848 * Return an associative array of attribute names and values from
849 * a partial tag string. Attribute names are forces to lowercase,
850 * character references are decoded to UTF-8 text.
855 public static function decodeTagAttributes( $text ) {
858 if( trim( $text ) == '' ) {
871 foreach( $pairs as $set ) {
872 $attribute = strtolower( $set[1] );
873 $value = Sanitizer
::getTagAttributeCallback( $set );
875 // Normalize whitespace
876 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
877 $value = trim( $value );
879 // Decode character references
880 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
886 * Pick the appropriate attribute value from a match set from the
887 * MW_ATTRIBS_REGEX matches.
893 private static function getTagAttributeCallback( $set ) {
894 if( isset( $set[6] ) ) {
895 # Illegal #XXXXXX color with no quotes.
897 } elseif( isset( $set[5] ) ) {
900 } elseif( isset( $set[4] ) ) {
903 } elseif( isset( $set[3] ) ) {
906 } elseif( !isset( $set[2] ) ) {
907 # In XHTML, attributes must have a value.
908 # For 'reduced' form, return explicitly the attribute name here.
911 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
916 * Normalize whitespace and character references in an XML source-
917 * encoded text for an attribute value.
919 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
920 * but note that we're not returning the value, but are returning
921 * XML source fragments that will be slapped into output.
923 * @param string $text
927 private static function normalizeAttributeValue( $text ) {
928 return str_replace( '"', '"',
929 self
::normalizeWhitespace(
930 Sanitizer
::normalizeCharReferences( $text ) ) );
933 private static function normalizeWhitespace( $text ) {
935 '/\r\n|[\x20\x0d\x0a\x09]/',
941 * Ensure that any entities and character references are legal
942 * for XML and XHTML specifically. Any stray bits will be
943 * &-escaped to result in a valid text fragment.
945 * a. any named char refs must be known in XHTML
946 * b. any numeric char refs must be legal chars, not invalid or forbidden
947 * c. use &#x, not &#X
948 * d. fix or reject non-valid attributes
950 * @param string $text
954 static function normalizeCharReferences( $text ) {
955 return preg_replace_callback(
957 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
961 * @param string $matches
964 static function normalizeCharReferencesCallback( $matches ) {
966 if( $matches[1] != '' ) {
967 $ret = Sanitizer
::normalizeEntity( $matches[1] );
968 } elseif( $matches[2] != '' ) {
969 $ret = Sanitizer
::decCharReference( $matches[2] );
970 } elseif( $matches[3] != '' ) {
971 $ret = Sanitizer
::hexCharReference( $matches[3] );
972 } elseif( $matches[4] != '' ) {
973 $ret = Sanitizer
::hexCharReference( $matches[4] );
975 if( is_null( $ret ) ) {
976 return htmlspecialchars( $matches[0] );
983 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
984 * return the named entity reference as is. If the entity is a
985 * MediaWiki-specific alias, returns the HTML equivalent. Otherwise,
986 * returns HTML-escaped text of pseudo-entity source (eg &foo;)
988 * @param string $name
992 static function normalizeEntity( $name ) {
993 global $wgHtmlEntities, $wgHtmlEntityAliases;
994 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
995 return "&{$wgHtmlEntityAliases[$name]};";
996 } elseif( isset( $wgHtmlEntities[$name] ) ) {
999 return "&$name;";
1003 static function decCharReference( $codepoint ) {
1004 $point = intval( $codepoint );
1005 if( Sanitizer
::validateCodepoint( $point ) ) {
1006 return sprintf( '&#%d;', $point );
1012 static function hexCharReference( $codepoint ) {
1013 $point = hexdec( $codepoint );
1014 if( Sanitizer
::validateCodepoint( $point ) ) {
1015 return sprintf( '&#x%x;', $point );
1022 * Returns true if a given Unicode codepoint is a valid character in XML.
1023 * @param int $codepoint
1026 private static function validateCodepoint( $codepoint ) {
1027 return ($codepoint == 0x09)
1028 ||
($codepoint == 0x0a)
1029 ||
($codepoint == 0x0d)
1030 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
1031 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
1032 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
1036 * Decode any character references, numeric or named entities,
1037 * in the text and return a UTF-8 string.
1039 * @param string $text
1044 public static function decodeCharReferences( $text ) {
1045 return preg_replace_callback(
1047 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1052 * @param string $matches
1055 static function decodeCharReferencesCallback( $matches ) {
1056 if( $matches[1] != '' ) {
1057 return Sanitizer
::decodeEntity( $matches[1] );
1058 } elseif( $matches[2] != '' ) {
1059 return Sanitizer
::decodeChar( intval( $matches[2] ) );
1060 } elseif( $matches[3] != '' ) {
1061 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
1062 } elseif( $matches[4] != '' ) {
1063 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
1065 # Last case should be an ampersand by itself
1070 * Return UTF-8 string for a codepoint if that is a valid
1071 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1072 * @param int $codepoint
1076 static function decodeChar( $codepoint ) {
1077 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
1078 return codepointToUtf8( $codepoint );
1080 return UTF8_REPLACEMENT
;
1085 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1086 * return the UTF-8 encoding of that character. Otherwise, returns
1087 * pseudo-entity source (eg &foo;)
1089 * @param string $name
1092 static function decodeEntity( $name ) {
1093 global $wgHtmlEntities, $wgHtmlEntityAliases;
1094 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1095 $name = $wgHtmlEntityAliases[$name];
1097 if( isset( $wgHtmlEntities[$name] ) ) {
1098 return codepointToUtf8( $wgHtmlEntities[$name] );
1105 * Fetch the whitelist of acceptable attributes for a given
1108 * @param string $element
1111 static function attributeWhitelist( $element ) {
1113 if( !isset( $list ) ) {
1114 $list = Sanitizer
::setupAttributeWhitelist();
1116 return isset( $list[$element] )
1122 * Foreach array key (an allowed HTML element), return an array
1123 * of allowed attributes
1126 static function setupAttributeWhitelist() {
1127 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1128 $block = array_merge( $common, array( 'align' ) );
1129 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1130 $tablecell = array( 'abbr',
1136 'nowrap', # deprecated
1137 'width', # deprecated
1138 'height', # deprecated
1139 'bgcolor' # deprecated
1142 # Numbers refer to sections in HTML 4.01 standard describing the element.
1143 # See: http://www.w3.org/TR/html4/
1144 $whitelist = array (
1147 'center' => $common, # deprecated
1148 'span' => $block, # ??
1166 'strong' => $common,
1177 'blockquote' => array_merge( $common, array( 'cite' ) ),
1188 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1191 'pre' => array_merge( $common, array( 'width' ) ),
1194 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1195 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1198 'ul' => array_merge( $common, array( 'type' ) ),
1199 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1200 'li' => array_merge( $common, array( 'type', 'value' ) ),
1208 'table' => array_merge( $common,
1209 array( 'summary', 'width', 'border', 'frame',
1210 'rules', 'cellspacing', 'cellpadding',
1215 'caption' => array_merge( $common, array( 'align' ) ),
1218 'thead' => array_merge( $common, $tablealign ),
1219 'tfoot' => array_merge( $common, $tablealign ),
1220 'tbody' => array_merge( $common, $tablealign ),
1223 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1224 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1227 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1230 'td' => array_merge( $common, $tablecell, $tablealign ),
1231 'th' => array_merge( $common, $tablecell, $tablealign ),
1234 # Not usually allowed, but may be used for extension-style hooks
1235 # such as <math> when it is rasterized
1236 'img' => array_merge( $common, array( 'alt' ) ),
1244 'strike' => $common,
1249 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1253 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1255 # XHTML Ruby annotation text module, simple ruby only.
1256 # http://www.w3c.org/TR/ruby/
1261 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1264 # MathML root element, where used for extensions
1265 # 'title' may not be 100% valid here; it's XHTML
1266 # http://www.w3.org/TR/REC-MathML/
1267 'math' => array( 'class', 'style', 'id', 'title' ),
1273 * Take a fragment of (potentially invalid) HTML and return
1274 * a version with any tags removed, encoded as plain text.
1276 * Warning: this return value must be further escaped for literal
1277 * inclusion in HTML output as of 1.10!
1279 * @param string $text HTML fragment
1282 static function stripAllTags( $text ) {
1284 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
1286 # Normalize &entities and whitespace
1287 $text = self
::decodeCharReferences( $text );
1288 $text = self
::normalizeWhitespace( $text );
1294 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1295 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1298 * Use for passing XHTML fragments to PHP's XML parsing functions
1303 static function hackDocType() {
1304 global $wgHtmlEntities;
1305 $out = "<!DOCTYPE html [\n";
1306 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1307 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1313 static function cleanUrl( $url ) {
1314 # Normalize any HTML entities in input. They will be
1315 # re-escaped by makeExternalLink().
1316 $url = Sanitizer
::decodeCharReferences( $url );
1318 # Escape any control characters introduced by the above step
1319 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1321 # Validate hostname portion
1323 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1324 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1326 // Characters that will be ignored in IDNs.
1327 // http://tools.ietf.org/html/3454#section-3.1
1328 // Strip them before further processing so blacklists and such work.
1330 \\s| # general whitespace
1331 \xc2\xad| # 00ad SOFT HYPHEN
1332 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1333 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1334 \xe2\x81\xa0| # 2060 WORD JOINER
1335 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1336 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1337 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1338 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1339 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1340 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1341 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1342 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1345 $host = preg_replace( $strip, '', $host );
1347 // @fixme: validate hostnames here
1349 return $protocol . $host . $rest;