b7578ff53a7ddf5f7e95f9254eb8d79966e1579a
3 * XHTML sanitizer for MediaWiki
5 * Copyright (C) 2002-2005 Brion Vibber <brion@pobox.com> et al
6 * http://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
27 * Regular expression to match various types of character references in
28 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
30 define( 'MW_CHAR_REFS_REGEX',
31 '/&([A-Za-z0-9\x80-\xff]+);
38 * Regular expression to match HTML/XML attribute pairs within a tag.
39 * Allows some... latitude.
40 * Used in Sanitizer::fixTagAttributes and Sanitizer::decodeTagAttributes
42 $attrib = '[A-Za-z0-9]';
43 $space = '[\x09\x0a\x0d\x20]';
44 define( 'MW_ATTRIBS_REGEX',
45 "/(?:^|$space)($attrib+)
48 # The attribute value: quoted or alone
51 | ([a-zA-Z0-9!#$%&()*,\\-.\\/:;<>?@[\\]^_`{|}~]+)
52 | (\#[0-9a-fA-F]+) # Technically wrong, but lots of
53 # colors are specified like this.
54 # We'll be normalizing it.
56 )?(?=$space|\$)/sx" );
59 * List of all named character entities defined in HTML 4.01
60 * http://www.w3.org/TR/html4/sgml/entities.html
63 global $wgHtmlEntities;
64 $wgHtmlEntities = array(
319 * Character entity aliases accepted by MediaWiki
321 global $wgHtmlEntityAliases;
322 $wgHtmlEntityAliases = array(
329 * XHTML sanitizer for MediaWiki
334 const INITIAL_NONLETTER
= 1;
337 * Cleans up HTML, removes dangerous tags and attributes, and
338 * removes HTML comments
340 * @param string $text
341 * @param callback $processCallback to do any variable or parameter replacements in HTML attribute values
342 * @param array $args for the processing callback
345 static function removeHTMLtags( $text, $processCallback = null, $args = array(), $extratags = array() ) {
348 static $htmlpairs, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
349 $htmllist, $listtags, $htmlsingleallowed, $htmlelements, $staticInitialised;
351 wfProfileIn( __METHOD__
);
353 if ( !$staticInitialised ) {
355 $htmlpairs = array_merge( $extratags, 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'
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_merge( $htmlsingle, $tabletags );
383 $htmlelements = array_merge( $htmlsingle, $htmlpairs, $htmlnest );
385 # Convert them all to hashtables for faster lookup
386 $vars = array( 'htmlpairs', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
387 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelements' );
388 foreach ( $vars as $var ) {
389 $
$var = array_flip( $
$var );
391 $staticInitialised = true;
394 # Remove HTML comments
395 $text = Sanitizer
::removeHTMLcomments( $text );
396 $bits = explode( '<', $text );
397 $text = str_replace( '>', '>', array_shift( $bits ) );
399 $tagstack = $tablestack = array();
400 foreach ( $bits as $x ) {
402 if( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
403 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
405 $slash = $t = $params = $brace = $rest = null;
409 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
413 if( isset( $htmlsingleonly[$t] ) ) {
415 } elseif ( ( $ot = @array_pop
( $tagstack ) ) != $t ) {
416 if ( isset( $htmlsingleallowed[$ot] ) ) {
417 # Pop all elements with an optional close tag
418 # and see if we find a match below them
420 array_push ($optstack, $ot);
421 while ( ( ( $ot = @array_pop
( $tagstack ) ) != $t ) &&
422 isset( $htmlsingleallowed[$ot] ) )
424 array_push ($optstack, $ot);
427 # No match. Push the optinal elements back again
429 while ( $ot = @array_pop
( $optstack ) ) {
430 array_push( $tagstack, $ot );
434 @array_push
( $tagstack, $ot );
435 # <li> can be nested in <ul> or <ol>, skip those cases:
436 if(!(isset( $htmllist[$ot] ) && isset( $listtags[$t] ) )) {
441 if ( $t == 'table' ) {
442 $tagstack = array_pop( $tablestack );
447 # Keep track for later
448 if ( isset( $tabletags[$t] ) &&
449 ! in_array( 'table', $tagstack ) ) {
451 } else if ( in_array( $t, $tagstack ) &&
452 ! isset( $htmlnest [$t ] ) ) {
454 #Â Is it a self closed htmlpair ? (bug 5487)
455 } else if( $brace == '/>' &&
456 isset( $htmlpairs[$t] ) ) {
458 } elseif( isset( $htmlsingleonly[$t] ) ) {
459 # Hack to force empty tag for uncloseable elements
461 } else if( isset( $htmlsingle[$t] ) ) {
462 # Hack to not close $htmlsingle tags
464 } else if( isset( $tabletags[$t] )
465 && in_array($t ,$tagstack) ) {
466 // New table tag but forgot to close the previous one
469 if ( $t == 'table' ) {
470 array_push( $tablestack, $tagstack );
473 array_push( $tagstack, $t );
476 # Replace any variables or template parameters with
478 if( is_callable( $processCallback ) ) {
479 call_user_func_array( $processCallback, array( &$params, $args ) );
482 # Strip non-approved attributes from the tag
483 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
486 $rest = str_replace( '>', '>', $rest );
487 $close = ( $brace == '/>' && !$slash ) ?
' /' : '';
488 $text .= "<$slash$t$newparams$close>$rest";
492 $text .= '<' . str_replace( '>', '>', $x);
494 # Close off any remaining tags
495 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
497 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
500 # this might be possible using tidy itself
501 foreach ( $bits as $x ) {
502 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
504 @list
( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
505 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
506 if( is_callable( $processCallback ) ) {
507 call_user_func_array( $processCallback, array( &$params, $args ) );
509 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
510 $rest = str_replace( '>', '>', $rest );
511 $text .= "<$slash$t$newparams$brace$rest";
513 $text .= '<' . str_replace( '>', '>', $x);
517 wfProfileOut( __METHOD__
);
522 * Remove '<!--', '-->', and everything between.
523 * To avoid leaving blank lines, when a comment is both preceded
524 * and followed by a newline (ignoring spaces), trim leading and
525 * trailing spaces and one of the newlines.
528 * @param string $text
531 static function removeHTMLcomments( $text ) {
532 wfProfileIn( __METHOD__
);
533 while (($start = strpos($text, '<!--')) !== false) {
534 $end = strpos($text, '-->', $start +
4);
535 if ($end === false) {
536 # Unterminated comment; bail out
542 # Trim space and newline if the comment is both
543 # preceded and followed by a newline
544 $spaceStart = max($start - 1, 0);
545 $spaceLen = $end - $spaceStart;
546 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
550 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
552 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
553 # Remove the comment, leading and trailing
554 # spaces, and leave only one newline.
555 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
558 # Remove just the comment.
559 $text = substr_replace($text, '', $start, $end - $start);
562 wfProfileOut( __METHOD__
);
567 * Take an array of attribute names and values and normalize or discard
568 * illegal values for the given element type.
570 * - Discards attributes not on a whitelist for the given element
571 * - Unsafe style attributes are discarded
572 * - Invalid id attributes are reencoded
574 * @param array $attribs
575 * @param string $element
578 * @todo Check for legal values where the DTD limits things.
579 * @todo Check for unique id attribute :P
581 static function validateTagAttributes( $attribs, $element ) {
582 return Sanitizer
::validateAttributes( $attribs,
583 Sanitizer
::attributeWhitelist( $element ) );
587 * Take an array of attribute names and values and normalize or discard
588 * illegal values for the given whitelist.
590 * - Discards attributes not the given whitelist
591 * - Unsafe style attributes are discarded
592 * - Invalid id attributes are reencoded
594 * @param array $attribs
595 * @param array $whitelist list of allowed attribute names
598 * @todo Check for legal values where the DTD limits things.
599 * @todo Check for unique id attribute :P
601 static function validateAttributes( $attribs, $whitelist ) {
602 $whitelist = array_flip( $whitelist );
604 foreach( $attribs as $attribute => $value ) {
605 if( !isset( $whitelist[$attribute] ) ) {
608 # Strip javascript "expression" from stylesheets.
609 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
610 if( $attribute == 'style' ) {
611 $value = Sanitizer
::checkCss( $value );
612 if( $value === false ) {
618 if ( $attribute === 'id' )
619 $value = Sanitizer
::escapeId( $value );
621 // If this attribute was previously set, override it.
622 // Output should only have one attribute of each name.
623 $out[$attribute] = $value;
629 * Merge two sets of HTML attributes.
630 * Conflicting items in the second set will override those
631 * in the first, except for 'class' attributes which will be
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'] )
642 && isset( $b['class'] )
643 && $a['class'] !== $b['class'] ) {
645 $out['class'] = implode( ' ',
648 $a['class'] . ' ' . $b['class'],
650 PREG_SPLIT_NO_EMPTY
) ) );
656 * Pick apart some CSS and check it for forbidden or unsafe structures.
657 * Returns a sanitized string, or false if it was just too evil.
659 * Currently URL references, 'expression', 'tps' are forbidden.
661 * @param string $value
664 static function checkCss( $value ) {
665 $stripped = Sanitizer
::decodeCharReferences( $value );
667 // Remove any comments; IE gets token splitting wrong
668 $stripped = StringUtils
::delimiterReplace( '/*', '*/', ' ', $stripped );
672 // ... and continue checks
673 $stripped = preg_replace( '!\\\\([0-9A-Fa-f]{1,6})[ \\n\\r\\t\\f]?!e',
674 'codepointToUtf8(hexdec("$1"))', $stripped );
675 $stripped = str_replace( '\\', '', $stripped );
676 if( preg_match( '/(?:expression|tps*:\/\/|url\\s*\().*/is',
686 * Take a tag soup fragment listing an HTML element's attributes
687 * and normalize it to well-formed XML, discarding unwanted attributes.
688 * Output is safe for further wikitext processing, with escaping of
689 * values that could trigger problems.
691 * - Normalizes attribute names to lowercase
692 * - Discards attributes not on a whitelist for the given element
693 * - Turns broken or invalid entities into plaintext
694 * - Double-quotes all attribute values
695 * - Attributes without values are given the name as attribute
696 * - Double attributes are discarded
697 * - Unsafe style attributes are discarded
698 * - Prepends space if there are attributes.
700 * @param string $text
701 * @param string $element
704 static function fixTagAttributes( $text, $element ) {
705 if( trim( $text ) == '' ) {
709 $stripped = Sanitizer
::validateTagAttributes(
710 Sanitizer
::decodeTagAttributes( $text ), $element );
713 foreach( $stripped as $attribute => $value ) {
714 $encAttribute = htmlspecialchars( $attribute );
715 $encValue = Sanitizer
::safeEncodeAttribute( $value );
717 $attribs[] = "$encAttribute=\"$encValue\"";
720 if ( !wfRunHooks( 'SanitizerAfterFixTagAttributes', array( $text, $element, &$attribs ) ) ) {
721 return ''; # They want to abort this.
723 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
727 * Encode an attribute value for HTML output.
729 * @return HTML-encoded text fragment
731 static function encodeAttribute( $text ) {
732 $encValue = htmlspecialchars( $text, ENT_QUOTES
);
734 // Whitespace is normalized during attribute decoding,
735 // so if we've been passed non-spaces we must encode them
736 // ahead of time or they won't be preserved.
737 $encValue = strtr( $encValue, array(
747 * Encode an attribute value for HTML tags, with extra armoring
748 * against further wiki processing.
750 * @return HTML-encoded text fragment
752 static function safeEncodeAttribute( $text ) {
753 $encValue = Sanitizer
::encodeAttribute( $text );
755 # Templates and links may be expanded in later parsing,
756 # creating invalid or dangerous output. Suppress this.
757 $encValue = strtr( $encValue, array(
758 '<' => '<', // This should never happen,
759 '>' => '>', // we've received invalid input
760 '"' => '"', // which should have been escaped.
763 "''" => '''',
764 'ISBN' => 'ISBN',
766 'PMID' => 'PMID',
772 $encValue = preg_replace_callback(
773 '/(' . wfUrlProtocols() . ')/',
774 array( 'Sanitizer', 'armorLinksCallback' ),
780 * Given a value escape it so that it can be used in an id attribute and
781 * return it, this does not validate the value however (see first link)
783 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
786 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
788 * @param string $id Id to validate
789 * @param int $flags Currently only two values: Sanitizer::INITIAL_NONLETTER
790 * (default) permits initial non-letter characters,
791 * such as if you're adding a prefix to them.
792 * Sanitizer::NONE will prepend an 'x' if the id
793 * would otherwise start with a nonletter.
796 static function escapeId( $id, $flags = Sanitizer
::INITIAL_NONLETTER
) {
797 static $replace = array(
802 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
803 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
805 if( ~
$flags & Sanitizer
::INITIAL_NONLETTER
806 && !preg_match( '/[a-zA-Z]/', $id[0] ) ) {
807 // Initial character must be a letter!
814 * Given a value, escape it so that it can be used as a CSS class and
817 * @todo For extra validity, input should be validated UTF-8.
819 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
821 * @param string $class
824 static function escapeClass( $class ) {
825 // Convert ugly stuff to underscores and kill underscores in ugly places
826 return rtrim(preg_replace(
827 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
833 * Regex replace callback for armoring links against further processing.
834 * @param array $matches
838 private static function armorLinksCallback( $matches ) {
839 return str_replace( ':', ':', $matches[1] );
843 * Return an associative array of attribute names and values from
844 * a partial tag string. Attribute names are forces to lowercase,
845 * character references are decoded to UTF-8 text.
850 static function decodeTagAttributes( $text ) {
853 if( trim( $text ) == '' ) {
866 foreach( $pairs as $set ) {
867 $attribute = strtolower( $set[1] );
868 $value = Sanitizer
::getTagAttributeCallback( $set );
870 // Normalize whitespace
871 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
872 $value = trim( $value );
874 // Decode character references
875 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
881 * Pick the appropriate attribute value from a match set from the
882 * MW_ATTRIBS_REGEX matches.
888 private static function getTagAttributeCallback( $set ) {
889 if( isset( $set[6] ) ) {
890 # Illegal #XXXXXX color with no quotes.
892 } elseif( isset( $set[5] ) ) {
895 } elseif( isset( $set[4] ) ) {
898 } elseif( isset( $set[3] ) ) {
901 } elseif( !isset( $set[2] ) ) {
902 # In XHTML, attributes must have a value.
903 # For 'reduced' form, return explicitly the attribute name here.
906 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
911 * Normalize whitespace and character references in an XML source-
912 * encoded text for an attribute value.
914 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
915 * but note that we're not returning the value, but are returning
916 * XML source fragments that will be slapped into output.
918 * @param string $text
922 private static function normalizeAttributeValue( $text ) {
923 return str_replace( '"', '"',
924 self
::normalizeWhitespace(
925 Sanitizer
::normalizeCharReferences( $text ) ) );
928 private static function normalizeWhitespace( $text ) {
930 '/\r\n|[\x20\x0d\x0a\x09]/',
936 * Ensure that any entities and character references are legal
937 * for XML and XHTML specifically. Any stray bits will be
938 * &-escaped to result in a valid text fragment.
940 * a. any named char refs must be known in XHTML
941 * b. any numeric char refs must be legal chars, not invalid or forbidden
942 * c. use &#x, not &#X
943 * d. fix or reject non-valid attributes
945 * @param string $text
949 static function normalizeCharReferences( $text ) {
950 return preg_replace_callback(
952 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
956 * @param string $matches
959 static function normalizeCharReferencesCallback( $matches ) {
961 if( $matches[1] != '' ) {
962 $ret = Sanitizer
::normalizeEntity( $matches[1] );
963 } elseif( $matches[2] != '' ) {
964 $ret = Sanitizer
::decCharReference( $matches[2] );
965 } elseif( $matches[3] != '' ) {
966 $ret = Sanitizer
::hexCharReference( $matches[3] );
967 } elseif( $matches[4] != '' ) {
968 $ret = Sanitizer
::hexCharReference( $matches[4] );
970 if( is_null( $ret ) ) {
971 return htmlspecialchars( $matches[0] );
978 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
979 * return the named entity reference as is. If the entity is a
980 * MediaWiki-specific alias, returns the HTML equivalent. Otherwise,
981 * returns HTML-escaped text of pseudo-entity source (eg &foo;)
983 * @param string $name
987 static function normalizeEntity( $name ) {
988 global $wgHtmlEntities, $wgHtmlEntityAliases;
989 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
990 return "&{$wgHtmlEntityAliases[$name]};";
991 } elseif( isset( $wgHtmlEntities[$name] ) ) {
994 return "&$name;";
998 static function decCharReference( $codepoint ) {
999 $point = intval( $codepoint );
1000 if( Sanitizer
::validateCodepoint( $point ) ) {
1001 return sprintf( '&#%d;', $point );
1007 static function hexCharReference( $codepoint ) {
1008 $point = hexdec( $codepoint );
1009 if( Sanitizer
::validateCodepoint( $point ) ) {
1010 return sprintf( '&#x%x;', $point );
1017 * Returns true if a given Unicode codepoint is a valid character in XML.
1018 * @param int $codepoint
1021 private static function validateCodepoint( $codepoint ) {
1022 return ($codepoint == 0x09)
1023 ||
($codepoint == 0x0a)
1024 ||
($codepoint == 0x0d)
1025 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
1026 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
1027 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
1031 * Decode any character references, numeric or named entities,
1032 * in the text and return a UTF-8 string.
1034 * @param string $text
1039 public static function decodeCharReferences( $text ) {
1040 return preg_replace_callback(
1042 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1047 * @param string $matches
1050 static function decodeCharReferencesCallback( $matches ) {
1051 if( $matches[1] != '' ) {
1052 return Sanitizer
::decodeEntity( $matches[1] );
1053 } elseif( $matches[2] != '' ) {
1054 return Sanitizer
::decodeChar( intval( $matches[2] ) );
1055 } elseif( $matches[3] != '' ) {
1056 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
1057 } elseif( $matches[4] != '' ) {
1058 return Sanitizer
::decodeChar( hexdec( $matches[4] ) );
1060 # Last case should be an ampersand by itself
1065 * Return UTF-8 string for a codepoint if that is a valid
1066 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1067 * @param int $codepoint
1071 static function decodeChar( $codepoint ) {
1072 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
1073 return codepointToUtf8( $codepoint );
1075 return UTF8_REPLACEMENT
;
1080 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1081 * return the UTF-8 encoding of that character. Otherwise, returns
1082 * pseudo-entity source (eg &foo;)
1084 * @param string $name
1087 static function decodeEntity( $name ) {
1088 global $wgHtmlEntities, $wgHtmlEntityAliases;
1089 if ( isset( $wgHtmlEntityAliases[$name] ) ) {
1090 $name = $wgHtmlEntityAliases[$name];
1092 if( isset( $wgHtmlEntities[$name] ) ) {
1093 return codepointToUtf8( $wgHtmlEntities[$name] );
1100 * Fetch the whitelist of acceptable attributes for a given
1103 * @param string $element
1106 static function attributeWhitelist( $element ) {
1108 if( !isset( $list ) ) {
1109 $list = Sanitizer
::setupAttributeWhitelist();
1111 return isset( $list[$element] )
1117 * @todo Document it a bit
1120 static function setupAttributeWhitelist() {
1121 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1122 $block = array_merge( $common, array( 'align' ) );
1123 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1124 $tablecell = array( 'abbr',
1130 'nowrap', # deprecated
1131 'width', # deprecated
1132 'height', # deprecated
1133 'bgcolor' # deprecated
1136 # Numbers refer to sections in HTML 4.01 standard describing the element.
1137 # See: http://www.w3.org/TR/html4/
1138 $whitelist = array (
1141 'center' => $common, # deprecated
1142 'span' => $block, # ??
1160 'strong' => $common,
1171 'blockquote' => array_merge( $common, array( 'cite' ) ),
1182 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1185 'pre' => array_merge( $common, array( 'width' ) ),
1188 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1189 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1192 'ul' => array_merge( $common, array( 'type' ) ),
1193 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1194 'li' => array_merge( $common, array( 'type', 'value' ) ),
1202 'table' => array_merge( $common,
1203 array( 'summary', 'width', 'border', 'frame',
1204 'rules', 'cellspacing', 'cellpadding',
1209 'caption' => array_merge( $common, array( 'align' ) ),
1212 'thead' => array_merge( $common, $tablealign ),
1213 'tfoot' => array_merge( $common, $tablealign ),
1214 'tbody' => array_merge( $common, $tablealign ),
1217 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1218 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1221 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1224 'td' => array_merge( $common, $tablecell, $tablealign ),
1225 'th' => array_merge( $common, $tablecell, $tablealign ),
1228 # Not usually allowed, but may be used for extension-style hooks
1229 # such as <math> when it is rasterized
1230 'img' => array_merge( $common, array( 'alt' ) ),
1238 'strike' => $common,
1243 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1247 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1249 # XHTML Ruby annotation text module, simple ruby only.
1250 # http://www.w3c.org/TR/ruby/
1255 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1258 # MathML root element, where used for extensions
1259 # 'title' may not be 100% valid here; it's XHTML
1260 # http://www.w3.org/TR/REC-MathML/
1261 'math' => array( 'class', 'style', 'id', 'title' ),
1267 * Take a fragment of (potentially invalid) HTML and return
1268 * a version with any tags removed, encoded as plain text.
1270 * Warning: this return value must be further escaped for literal
1271 * inclusion in HTML output as of 1.10!
1273 * @param string $text HTML fragment
1276 static function stripAllTags( $text ) {
1278 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
1280 # Normalize &entities and whitespace
1281 $text = self
::decodeCharReferences( $text );
1282 $text = self
::normalizeWhitespace( $text );
1288 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1289 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1292 * Use for passing XHTML fragments to PHP's XML parsing functions
1297 static function hackDocType() {
1298 global $wgHtmlEntities;
1299 $out = "<!DOCTYPE html [\n";
1300 foreach( $wgHtmlEntities as $entity => $codepoint ) {
1301 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1307 static function cleanUrl( $url, $hostname=true ) {
1308 # Normalize any HTML entities in input. They will be
1309 # re-escaped by makeExternalLink().
1310 $url = Sanitizer
::decodeCharReferences( $url );
1312 # Escape any control characters introduced by the above step
1313 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F]/e', "urlencode('\\0')", $url );
1315 # Validate hostname portion
1317 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1318 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1320 // Characters that will be ignored in IDNs.
1321 // http://tools.ietf.org/html/3454#section-3.1
1322 // Strip them before further processing so blacklists and such work.
1324 \\s| # general whitespace
1325 \xc2\xad| # 00ad SOFT HYPHEN
1326 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1327 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1328 \xe2\x81\xa0| # 2060 WORD JOINER
1329 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1330 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1331 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1332 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1333 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1334 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1335 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1336 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1339 $host = preg_replace( $strip, '', $host );
1341 // @fixme: validate hostnames here
1343 return $protocol . $host . $rest;