3 * XHTML sanitizer for MediaWiki
5 * Copyright © 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 * XHTML sanitizer for MediaWiki
33 * Regular expression to match various types of character references in
34 * Sanitizer::normalizeCharReferences and Sanitizer::decodeCharReferences
36 const CHAR_REFS_REGEX
=
37 '/&([A-Za-z0-9\x80-\xff]+);
39 |&\#[xX]([0-9A-Fa-f]+);
42 const EVIL_URI_PATTERN
= '!(^|\s|\*/\s*)(javascript|vbscript)([^\w]|$)!i';
43 const XMLNS_ATTRIBUTE_PATTERN
= "/^xmlns:[:A-Z_a-z-.0-9]+$/";
46 * List of all named character entities defined in HTML 4.01
47 * http://www.w3.org/TR/html4/sgml/entities.html
50 static $htmlEntities = array(
306 * Character entity aliases accepted by MediaWiki
308 static $htmlEntityAliases = array(
314 * Lazy-initialised attributes regex, see getAttribsRegex()
316 static $attribsRegex;
319 * Regular expression to match HTML/XML attribute pairs within a tag.
320 * Allows some... latitude.
321 * Used in Sanitizer::fixTagAttributes and Sanitizer::decodeTagAttributes
323 static function getAttribsRegex() {
324 if ( self
::$attribsRegex === null ) {
325 $attribFirst = '[:A-Z_a-z0-9]';
326 $attrib = '[:A-Z_a-z-.0-9]';
327 $space = '[\x09\x0a\x0d\x20]';
328 self
::$attribsRegex =
329 "/(?:^|$space)({$attribFirst}{$attrib}*)
332 # The attribute value: quoted or alone
335 | ([a-zA-Z0-9!#$%&()*,\\-.\\/:;<>?@[\\]^_`{|}~]+)
336 | (\#[0-9a-fA-F]+) # Technically wrong, but lots of
337 # colors are specified like this.
338 # We'll be normalizing it.
342 return self
::$attribsRegex;
346 * Cleans up HTML, removes dangerous tags and attributes, and
347 * removes HTML comments
349 * @param $text String
350 * @param $processCallback Callback to do any variable or parameter replacements in HTML attribute values
351 * @param $args Array for the processing callback
352 * @param $extratags Array for any extra tags to include
353 * @param $removetags Array for any tags (default or extra) to exclude
356 static function removeHTMLtags( $text, $processCallback = null, $args = array(), $extratags = array(), $removetags = array() ) {
359 static $htmlpairsStatic, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
360 $htmllist, $listtags, $htmlsingleallowed, $htmlelementsStatic, $staticInitialised;
362 wfProfileIn( __METHOD__
);
364 if ( !$staticInitialised ) {
366 $htmlpairsStatic = array( # Tags that must be closed
367 'b', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
368 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
369 'strike', 'strong', 'tt', 'var', 'div', 'center',
370 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
371 'ruby', 'rt' , 'rb' , 'rp', 'p', 'span', 'abbr', 'dfn',
375 'br', 'hr', 'li', 'dt', 'dd'
377 $htmlsingleonly = array( # Elements that cannot have close tags
380 $htmlnest = array( # Tags that can be nested--??
381 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
382 'dl', 'font', 'big', 'small', 'sub', 'sup', 'span'
384 $tabletags = array( # Can only appear inside table, we will close them
387 $htmllist = array( # Tags used by list
390 $listtags = array( # Tags that can appear in a list
394 global $wgAllowImageTag;
395 if ( $wgAllowImageTag ) {
396 $htmlsingle[] = 'img';
397 $htmlsingleonly[] = 'img';
400 $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
401 $htmlelementsStatic = array_unique( array_merge( $htmlsingle, $htmlpairsStatic, $htmlnest ) );
403 # Convert them all to hashtables for faster lookup
404 $vars = array( 'htmlpairsStatic', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
405 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelementsStatic' );
406 foreach ( $vars as $var ) {
407 $
$var = array_flip( $
$var );
409 $staticInitialised = true;
411 # Populate $htmlpairs and $htmlelements with the $extratags and $removetags arrays
412 $extratags = array_flip( $extratags );
413 $removetags = array_flip( $removetags );
414 $htmlpairs = array_merge( $extratags, $htmlpairsStatic );
415 $htmlelements = array_diff_key( array_merge( $extratags, $htmlelementsStatic ) , $removetags );
417 # Remove HTML comments
418 $text = Sanitizer
::removeHTMLcomments( $text );
419 $bits = explode( '<', $text );
420 $text = str_replace( '>', '>', array_shift( $bits ) );
422 $tagstack = $tablestack = array();
423 foreach ( $bits as $x ) {
425 # $slash: Does the current element start with a '/'?
426 # $t: Current element name
427 # $params: String between element name and >
428 # $brace: Ending '>' or '/>'
429 # $rest: Everything until the next element of $bits
430 if( preg_match( '!^(/?)(\\w+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
431 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
433 $slash = $t = $params = $brace = $rest = null;
437 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
439 if ( $slash && isset( $htmlsingleonly[$t] ) ) {
441 } elseif ( $slash ) {
442 # Closing a tag... is it the one we just opened?
443 $ot = @array_pop
( $tagstack );
445 if ( isset( $htmlsingleallowed[$ot] ) ) {
446 # Pop all elements with an optional close tag
447 # and see if we find a match below them
449 array_push( $optstack, $ot );
450 $ot = @array_pop
( $tagstack );
451 while ( $ot != $t && isset( $htmlsingleallowed[$ot] ) ) {
452 array_push( $optstack, $ot );
453 $ot = @array_pop
( $tagstack );
456 # No match. Push the optional elements back again
458 while ( $ot = @array_pop
( $optstack ) ) {
459 array_push( $tagstack, $ot );
463 @array_push
( $tagstack, $ot );
464 # <li> can be nested in <ul> or <ol>, skip those cases:
465 if ( !isset( $htmllist[$ot] ) ||
!isset( $listtags[$t] ) ) {
470 if ( $t == 'table' ) {
471 $tagstack = array_pop( $tablestack );
476 # Keep track for later
477 if ( isset( $tabletags[$t] ) &&
478 !in_array( 'table', $tagstack ) ) {
480 } elseif ( in_array( $t, $tagstack ) &&
481 !isset( $htmlnest [$t ] ) ) {
483 # Is it a self closed htmlpair ? (bug 5487)
484 } elseif ( $brace == '/>' &&
485 isset( $htmlpairs[$t] ) ) {
487 } elseif ( isset( $htmlsingleonly[$t] ) ) {
488 # Hack to force empty tag for uncloseable elements
490 } elseif ( isset( $htmlsingle[$t] ) ) {
491 # Hack to not close $htmlsingle tags
493 } elseif ( isset( $tabletags[$t] )
494 && in_array( $t, $tagstack ) ) {
495 // New table tag but forgot to close the previous one
498 if ( $t == 'table' ) {
499 array_push( $tablestack, $tagstack );
502 array_push( $tagstack, $t );
505 # Replace any variables or template parameters with
507 if( is_callable( $processCallback ) ) {
508 call_user_func_array( $processCallback, array( &$params, $args ) );
511 # Strip non-approved attributes from the tag
512 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
515 $rest = str_replace( '>', '>', $rest );
516 $close = ( $brace == '/>' && !$slash ) ?
' /' : '';
517 $text .= "<$slash$t$newparams$close>$rest";
521 $text .= '<' . str_replace( '>', '>', $x);
523 # Close off any remaining tags
524 while ( is_array( $tagstack ) && ($t = array_pop( $tagstack )) ) {
526 if ( $t == 'table' ) { $tagstack = array_pop( $tablestack ); }
529 # this might be possible using tidy itself
530 foreach ( $bits as $x ) {
531 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
533 @list
( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
534 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
535 if( is_callable( $processCallback ) ) {
536 call_user_func_array( $processCallback, array( &$params, $args ) );
538 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
539 $rest = str_replace( '>', '>', $rest );
540 $text .= "<$slash$t$newparams$brace$rest";
542 $text .= '<' . str_replace( '>', '>', $x);
546 wfProfileOut( __METHOD__
);
551 * Remove '<!--', '-->', and everything between.
552 * To avoid leaving blank lines, when a comment is both preceded
553 * and followed by a newline (ignoring spaces), trim leading and
554 * trailing spaces and one of the newlines.
557 * @param $text String
560 static function removeHTMLcomments( $text ) {
561 wfProfileIn( __METHOD__
);
562 while (($start = strpos($text, '<!--')) !== false) {
563 $end = strpos($text, '-->', $start +
4);
564 if ($end === false) {
565 # Unterminated comment; bail out
571 # Trim space and newline if the comment is both
572 # preceded and followed by a newline
573 $spaceStart = max($start - 1, 0);
574 $spaceLen = $end - $spaceStart;
575 while (substr($text, $spaceStart, 1) === ' ' && $spaceStart > 0) {
579 while (substr($text, $spaceStart +
$spaceLen, 1) === ' ')
581 if (substr($text, $spaceStart, 1) === "\n" and substr($text, $spaceStart +
$spaceLen, 1) === "\n") {
582 # Remove the comment, leading and trailing
583 # spaces, and leave only one newline.
584 $text = substr_replace($text, "\n", $spaceStart, $spaceLen +
1);
587 # Remove just the comment.
588 $text = substr_replace($text, '', $start, $end - $start);
591 wfProfileOut( __METHOD__
);
596 * Take an array of attribute names and values and normalize or discard
597 * illegal values for the given element type.
599 * - Discards attributes not on a whitelist for the given element
600 * - Unsafe style attributes are discarded
601 * - Invalid id attributes are reencoded
603 * @param $attribs Array
604 * @param $element String
607 * @todo Check for legal values where the DTD limits things.
608 * @todo Check for unique id attribute :P
610 static function validateTagAttributes( $attribs, $element ) {
611 return Sanitizer
::validateAttributes( $attribs,
612 Sanitizer
::attributeWhitelist( $element ) );
616 * Take an array of attribute names and values and normalize or discard
617 * illegal values for the given whitelist.
619 * - Discards attributes not the given whitelist
620 * - Unsafe style attributes are discarded
621 * - Invalid id attributes are reencoded
623 * @param $attribs Array
624 * @param $whitelist Array: list of allowed attribute names
627 * @todo Check for legal values where the DTD limits things.
628 * @todo Check for unique id attribute :P
630 static function validateAttributes( $attribs, $whitelist ) {
631 global $wgAllowRdfaAttributes, $wgAllowMicrodataAttributes, $wgHtml5;
633 $whitelist = array_flip( $whitelist );
634 $hrefExp = '/^(' . wfUrlProtocols() . ')[^\s]+$/';
637 foreach( $attribs as $attribute => $value ) {
638 #allow XML namespace declaration if RDFa is enabled
639 if ( $wgAllowRdfaAttributes && preg_match( self
::XMLNS_ATTRIBUTE_PATTERN
, $attribute ) ) {
640 if ( !preg_match( self
::EVIL_URI_PATTERN
, $value ) ) {
641 $out[$attribute] = $value;
647 # Allow any attribute beginning with "data-", if in HTML5 mode
648 if ( !($wgHtml5 && preg_match( '/^data-/i', $attribute )) && !isset( $whitelist[$attribute] ) ) {
652 # Strip javascript "expression" from stylesheets.
653 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
654 if( $attribute == 'style' ) {
655 $value = Sanitizer
::checkCss( $value );
658 if ( $attribute === 'id' ) {
659 $value = Sanitizer
::escapeId( $value, 'noninitial' );
662 //RDFa and microdata properties allow URLs, URIs and/or CURIs. check them for sanity
663 if ( $attribute === 'rel' ||
$attribute === 'rev' ||
664 $attribute === 'about' ||
$attribute === 'property' ||
$attribute === 'resource' ||
#RDFa
665 $attribute === 'datatype' ||
$attribute === 'typeof' ||
#RDFa
666 $attribute === 'itemid' ||
$attribute === 'itemprop' ||
$attribute === 'itemref' ||
#HTML5 microdata
667 $attribute === 'itemscope' ||
$attribute === 'itemtype' ) { #HTML5 microdata
669 //Paranoia. Allow "simple" values but suppress javascript
670 if ( preg_match( self
::EVIL_URI_PATTERN
, $value ) ) {
675 # NOTE: even though elements using href/src are not allowed directly, supply
676 # validation code that can be used by tag hook handlers, etc
677 if ( $attribute === 'href' ||
$attribute === 'src' ) {
678 if ( !preg_match( $hrefExp, $value ) ) {
679 continue; //drop any href or src attributes not using an allowed protocol.
680 //NOTE: this also drops all relative URLs
684 // If this attribute was previously set, override it.
685 // Output should only have one attribute of each name.
686 $out[$attribute] = $value;
689 if ( $wgAllowMicrodataAttributes ) {
690 # itemtype, itemid, itemref don't make sense without itemscope
691 if ( !array_key_exists( 'itemscope', $out ) ) {
692 unset( $out['itemtype'] );
693 unset( $out['itemid'] );
694 unset( $out['itemref'] );
696 # TODO: Strip itemprop if we aren't descendants of an itemscope.
702 * Merge two sets of HTML attributes. Conflicting items in the second set
703 * will override those in the first, except for 'class' attributes which
704 * will be combined (if they're both strings).
706 * @todo implement merging for other attributes such as style
711 static function mergeAttributes( $a, $b ) {
712 $out = array_merge( $a, $b );
713 if( isset( $a['class'] ) && isset( $b['class'] )
714 && is_string( $a['class'] ) && is_string( $b['class'] )
715 && $a['class'] !== $b['class'] ) {
716 $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
717 -1, PREG_SPLIT_NO_EMPTY
);
718 $out['class'] = implode( ' ', array_unique( $classes ) );
724 * Pick apart some CSS and check it for forbidden or unsafe structures.
725 * Returns a sanitized string, or false if it was just too evil.
727 * Currently URL references, 'expression', 'tps' are forbidden.
729 * @param $value String
732 static function checkCss( $value ) {
733 $value = Sanitizer
::decodeCharReferences( $value );
735 // Remove any comments; IE gets token splitting wrong
736 $value = StringUtils
::delimiterReplace( '/*', '*/', ' ', $value );
738 // Remove anything after a comment-start token, to guard against
739 // incorrect client implementations.
740 $commentPos = strpos( $value, '/*' );
741 if ( $commentPos !== false ) {
742 $value = substr( $value, 0, $commentPos );
745 // Decode escape sequences and line continuation
746 // See the grammar in the CSS 2 spec, appendix D.
748 if ( !$decodeRegex ) {
749 $space = '[\\x20\\t\\r\\n\\f]';
750 $nl = '(?:\\n|\\r\\n|\\r|\\f)';
752 $decodeRegex = "/ $backslash
754 ($nl) | # 1. Line continuation
755 ([0-9A-Fa-f]{1,6})$space? | # 2. character number
756 (.) | # 3. backslash cancelling special meaning
757 () | # 4. backslash at end of string
760 $value = preg_replace_callback( $decodeRegex,
761 array( __CLASS__
, 'cssDecodeCallback' ), $value );
763 // Reject problematic keywords and control characters
764 if ( preg_match( '/[\000-\010\016-\037\177]/', $value ) ) {
765 return '/* invalid control char */';
766 } elseif ( preg_match( '! expression | filter\s*: | accelerator\s*: | url\s*\( !ix', $value ) ) {
767 return '/* insecure input */';
772 static function cssDecodeCallback( $matches ) {
773 if ( $matches[1] !== '' ) {
776 } elseif ( $matches[2] !== '' ) {
777 $char = codepointToUtf8( hexdec( $matches[2] ) );
778 } elseif ( $matches[3] !== '' ) {
783 if ( $char == "\n" ||
$char == '"' ||
$char == "'" ||
$char == '\\' ) {
784 // These characters need to be escaped in strings
785 // Clean up the escape sequence to avoid parsing errors by clients
786 return '\\' . dechex( ord( $char ) ) . ' ';
788 // Decode unnecessary escape
794 * Take a tag soup fragment listing an HTML element's attributes
795 * and normalize it to well-formed XML, discarding unwanted attributes.
796 * Output is safe for further wikitext processing, with escaping of
797 * values that could trigger problems.
799 * - Normalizes attribute names to lowercase
800 * - Discards attributes not on a whitelist for the given element
801 * - Turns broken or invalid entities into plaintext
802 * - Double-quotes all attribute values
803 * - Attributes without values are given the name as attribute
804 * - Double attributes are discarded
805 * - Unsafe style attributes are discarded
806 * - Prepends space if there are attributes.
808 * @param $text String
809 * @param $element String
812 static function fixTagAttributes( $text, $element ) {
813 if( trim( $text ) == '' ) {
817 $stripped = Sanitizer
::validateTagAttributes(
818 Sanitizer
::decodeTagAttributes( $text ), $element );
821 foreach( $stripped as $attribute => $value ) {
822 $encAttribute = htmlspecialchars( $attribute );
823 $encValue = Sanitizer
::safeEncodeAttribute( $value );
825 $attribs[] = "$encAttribute=\"$encValue\"";
827 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
831 * Encode an attribute value for HTML output.
832 * @param $text String
833 * @return HTML-encoded text fragment
835 static function encodeAttribute( $text ) {
836 $encValue = htmlspecialchars( $text, ENT_QUOTES
);
838 // Whitespace is normalized during attribute decoding,
839 // so if we've been passed non-spaces we must encode them
840 // ahead of time or they won't be preserved.
841 $encValue = strtr( $encValue, array(
851 * Encode an attribute value for HTML tags, with extra armoring
852 * against further wiki processing.
853 * @param $text String
854 * @return HTML-encoded text fragment
856 static function safeEncodeAttribute( $text ) {
857 $encValue = Sanitizer
::encodeAttribute( $text );
859 # Templates and links may be expanded in later parsing,
860 # creating invalid or dangerous output. Suppress this.
861 $encValue = strtr( $encValue, array(
862 '<' => '<', // This should never happen,
863 '>' => '>', // we've received invalid input
864 '"' => '"', // which should have been escaped.
867 "''" => '''',
868 'ISBN' => 'ISBN',
870 'PMID' => 'PMID',
876 $encValue = preg_replace_callback(
877 '/(' . wfUrlProtocols() . ')/',
878 array( 'Sanitizer', 'armorLinksCallback' ),
884 * Given a value, escape it so that it can be used in an id attribute and
885 * return it. This will use HTML5 validation if $wgExperimentalHtmlIds is
886 * true, allowing anything but ASCII whitespace. Otherwise it will use
887 * HTML 4 rules, which means a narrow subset of ASCII, with bad characters
888 * escaped with lots of dots.
890 * To ensure we don't have to bother escaping anything, we also strip ', ",
891 * & even if $wgExperimentalIds is true. TODO: Is this the best tactic?
892 * We also strip # because it upsets IE, and % because it could be
893 * ambiguous if it's part of something that looks like a percent escape
894 * (which don't work reliably in fragments cross-browser).
896 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
899 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
900 * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#the-id-attribute
901 * HTML5 definition of id attribute
903 * @param $id String: id to escape
904 * @param $options Mixed: string or array of strings (default is array()):
905 * 'noninitial': This is a non-initial fragment of an id, not a full id,
906 * so don't pay attention if the first character isn't valid at the
907 * beginning of an id. Only matters if $wgExperimentalHtmlIds is
909 * 'legacy': Behave the way the old HTML 4-based ID escaping worked even
910 * if $wgExperimentalHtmlIds is used, so we can generate extra
911 * anchors and links won't break.
914 static function escapeId( $id, $options = array() ) {
915 global $wgHtml5, $wgExperimentalHtmlIds;
916 $options = (array)$options;
918 if ( $wgHtml5 && $wgExperimentalHtmlIds && !in_array( 'legacy', $options ) ) {
919 $id = Sanitizer
::decodeCharReferences( $id );
920 $id = preg_replace( '/[ \t\n\r\f_\'"&#%]+/', '_', $id );
921 $id = trim( $id, '_' );
923 # Must have been all whitespace to start with.
930 # HTML4-style escaping
931 static $replace = array(
936 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
937 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
939 if ( !preg_match( '/^[a-zA-Z]/', $id )
940 && !in_array( 'noninitial', $options ) ) {
941 // Initial character must be a letter!
948 * Given a value, escape it so that it can be used as a CSS class and
951 * @todo For extra validity, input should be validated UTF-8.
953 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
955 * @param $class String
958 static function escapeClass( $class ) {
959 // Convert ugly stuff to underscores and kill underscores in ugly places
960 return rtrim(preg_replace(
961 array('/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/','/_+/'),
967 * Given HTML input, escape with htmlspecialchars but un-escape entites.
968 * This allows (generally harmless) entities like   to survive.
970 * @param $html String to escape
971 * @return String: escaped input
973 static function escapeHtmlAllowEntities( $html ) {
974 $html = Sanitizer
::decodeCharReferences( $html );
975 # It seems wise to escape ' as well as ", as a matter of course. Can't
977 $html = htmlspecialchars( $html, ENT_QUOTES
);
982 * Regex replace callback for armoring links against further processing.
983 * @param $matches Array
986 private static function armorLinksCallback( $matches ) {
987 return str_replace( ':', ':', $matches[1] );
991 * Return an associative array of attribute names and values from
992 * a partial tag string. Attribute names are forces to lowercase,
993 * character references are decoded to UTF-8 text.
995 * @param $text String
998 public static function decodeTagAttributes( $text ) {
999 if( trim( $text ) == '' ) {
1005 if( !preg_match_all(
1006 self
::getAttribsRegex(),
1009 PREG_SET_ORDER
) ) {
1013 foreach( $pairs as $set ) {
1014 $attribute = strtolower( $set[1] );
1015 $value = Sanitizer
::getTagAttributeCallback( $set );
1017 // Normalize whitespace
1018 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
1019 $value = trim( $value );
1021 // Decode character references
1022 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
1028 * Pick the appropriate attribute value from a match set from the
1029 * attribs regex matches.
1034 private static function getTagAttributeCallback( $set ) {
1035 if( isset( $set[6] ) ) {
1036 # Illegal #XXXXXX color with no quotes.
1038 } elseif( isset( $set[5] ) ) {
1041 } elseif( isset( $set[4] ) ) {
1044 } elseif( isset( $set[3] ) ) {
1047 } elseif( !isset( $set[2] ) ) {
1048 # In XHTML, attributes must have a value.
1049 # For 'reduced' form, return explicitly the attribute name here.
1052 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
1057 * Normalize whitespace and character references in an XML source-
1058 * encoded text for an attribute value.
1060 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
1061 * but note that we're not returning the value, but are returning
1062 * XML source fragments that will be slapped into output.
1064 * @param $text String
1067 private static function normalizeAttributeValue( $text ) {
1068 return str_replace( '"', '"',
1069 self
::normalizeWhitespace(
1070 Sanitizer
::normalizeCharReferences( $text ) ) );
1073 private static function normalizeWhitespace( $text ) {
1074 return preg_replace(
1075 '/\r\n|[\x20\x0d\x0a\x09]/',
1081 * Normalizes whitespace in a section name, such as might be returned
1082 * by Parser::stripSectionName(), for use in the id's that are used for
1085 * @param $section String
1088 static function normalizeSectionNameWhitespace( $section ) {
1089 return trim( preg_replace( '/[ _]+/', ' ', $section ) );
1093 * Ensure that any entities and character references are legal
1094 * for XML and XHTML specifically. Any stray bits will be
1095 * &-escaped to result in a valid text fragment.
1097 * a. named char refs can only be < > & ", others are
1098 * numericized (this way we're well-formed even without a DTD)
1099 * b. any numeric char refs must be legal chars, not invalid or forbidden
1100 * c. use &#x, not &#X
1101 * d. fix or reject non-valid attributes
1103 * @param $text String
1107 static function normalizeCharReferences( $text ) {
1108 return preg_replace_callback(
1109 self
::CHAR_REFS_REGEX
,
1110 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
1114 * @param $matches String
1117 static function normalizeCharReferencesCallback( $matches ) {
1119 if( $matches[1] != '' ) {
1120 $ret = Sanitizer
::normalizeEntity( $matches[1] );
1121 } elseif( $matches[2] != '' ) {
1122 $ret = Sanitizer
::decCharReference( $matches[2] );
1123 } elseif( $matches[3] != '' ) {
1124 $ret = Sanitizer
::hexCharReference( $matches[3] );
1126 if( is_null( $ret ) ) {
1127 return htmlspecialchars( $matches[0] );
1134 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1135 * return the equivalent numeric entity reference (except for the core <
1136 * > & "). If the entity is a MediaWiki-specific alias, returns
1137 * the HTML equivalent. Otherwise, returns HTML-escaped text of
1138 * pseudo-entity source (eg &foo;)
1140 * @param $name String
1143 static function normalizeEntity( $name ) {
1144 if ( isset( self
::$htmlEntityAliases[$name] ) ) {
1145 return '&' . self
::$htmlEntityAliases[$name] . ';';
1146 } elseif ( in_array( $name,
1147 array( 'lt', 'gt', 'amp', 'quot' ) ) ) {
1149 } elseif ( isset( self
::$htmlEntities[$name] ) ) {
1150 return '&#' . self
::$htmlEntities[$name] . ';';
1152 return "&$name;";
1156 static function decCharReference( $codepoint ) {
1157 $point = intval( $codepoint );
1158 if( Sanitizer
::validateCodepoint( $point ) ) {
1159 return sprintf( '&#%d;', $point );
1165 static function hexCharReference( $codepoint ) {
1166 $point = hexdec( $codepoint );
1167 if( Sanitizer
::validateCodepoint( $point ) ) {
1168 return sprintf( '&#x%x;', $point );
1175 * Returns true if a given Unicode codepoint is a valid character in XML.
1176 * @param $codepoint Integer
1179 private static function validateCodepoint( $codepoint ) {
1180 return ($codepoint == 0x09)
1181 ||
($codepoint == 0x0a)
1182 ||
($codepoint == 0x0d)
1183 ||
($codepoint >= 0x20 && $codepoint <= 0xd7ff)
1184 ||
($codepoint >= 0xe000 && $codepoint <= 0xfffd)
1185 ||
($codepoint >= 0x10000 && $codepoint <= 0x10ffff);
1189 * Decode any character references, numeric or named entities,
1190 * in the text and return a UTF-8 string.
1192 * @param $text String
1195 public static function decodeCharReferences( $text ) {
1196 return preg_replace_callback(
1197 self
::CHAR_REFS_REGEX
,
1198 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1203 * Decode any character references, numeric or named entities,
1204 * in the next and normalize the resulting string. (bug 14952)
1206 * This is useful for page titles, not for text to be displayed,
1207 * MediaWiki allows HTML entities to escape normalization as a feature.
1209 * @param $text String (already normalized, containing entities)
1210 * @return String (still normalized, without entities)
1212 public static function decodeCharReferencesAndNormalize( $text ) {
1214 $text = preg_replace_callback(
1215 self
::CHAR_REFS_REGEX
,
1216 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1217 $text, /* limit */ -1, $count );
1220 return $wgContLang->normalize( $text );
1227 * @param $matches String
1230 static function decodeCharReferencesCallback( $matches ) {
1231 if( $matches[1] != '' ) {
1232 return Sanitizer
::decodeEntity( $matches[1] );
1233 } elseif( $matches[2] != '' ) {
1234 return Sanitizer
::decodeChar( intval( $matches[2] ) );
1235 } elseif( $matches[3] != '' ) {
1236 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
1238 # Last case should be an ampersand by itself
1243 * Return UTF-8 string for a codepoint if that is a valid
1244 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1245 * @param $codepoint Integer
1249 static function decodeChar( $codepoint ) {
1250 if( Sanitizer
::validateCodepoint( $codepoint ) ) {
1251 return codepointToUtf8( $codepoint );
1253 return UTF8_REPLACEMENT
;
1258 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1259 * return the UTF-8 encoding of that character. Otherwise, returns
1260 * pseudo-entity source (eg &foo;)
1262 * @param $name Strings
1265 static function decodeEntity( $name ) {
1266 if ( isset( self
::$htmlEntityAliases[$name] ) ) {
1267 $name = self
::$htmlEntityAliases[$name];
1269 if( isset( self
::$htmlEntities[$name] ) ) {
1270 return codepointToUtf8( self
::$htmlEntities[$name] );
1277 * Fetch the whitelist of acceptable attributes for a given element name.
1279 * @param $element String
1282 static function attributeWhitelist( $element ) {
1284 if( !isset( $list ) ) {
1285 $list = Sanitizer
::setupAttributeWhitelist();
1287 return isset( $list[$element] )
1293 * Foreach array key (an allowed HTML element), return an array
1294 * of allowed attributes
1297 static function setupAttributeWhitelist() {
1298 global $wgAllowRdfaAttributes, $wgHtml5, $wgAllowMicrodataAttributes;
1300 $common = array( 'id', 'class', 'lang', 'dir', 'title', 'style' );
1302 if ( $wgAllowRdfaAttributes ) {
1303 #RDFa attributes as specified in section 9 of http://www.w3.org/TR/2008/REC-rdfa-syntax-20081014
1304 $common = array_merge( $common, array(
1305 'about', 'property', 'resource', 'datatype', 'typeof',
1309 if ( $wgHtml5 && $wgAllowMicrodataAttributes ) {
1310 # add HTML5 microdata tages as pecified by http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html#the-microdata-model
1311 $common = array_merge( $common, array(
1312 'itemid', 'itemprop', 'itemref', 'itemscope', 'itemtype'
1316 $block = array_merge( $common, array( 'align' ) );
1317 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1318 $tablecell = array( 'abbr',
1324 'nowrap', # deprecated
1325 'width', # deprecated
1326 'height', # deprecated
1327 'bgcolor' # deprecated
1330 # Numbers refer to sections in HTML 4.01 standard describing the element.
1331 # See: http://www.w3.org/TR/html4/
1332 $whitelist = array (
1335 'center' => $common, # deprecated
1336 'span' => $block, # ??
1354 'strong' => $common,
1365 'blockquote' => array_merge( $common, array( 'cite' ) ),
1376 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1379 'pre' => array_merge( $common, array( 'width' ) ),
1382 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1383 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1386 'ul' => array_merge( $common, array( 'type' ) ),
1387 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1388 'li' => array_merge( $common, array( 'type', 'value' ) ),
1396 'table' => array_merge( $common,
1397 array( 'summary', 'width', 'border', 'frame',
1398 'rules', 'cellspacing', 'cellpadding',
1403 'caption' => array_merge( $common, array( 'align' ) ),
1406 'thead' => array_merge( $common, $tablealign ),
1407 'tfoot' => array_merge( $common, $tablealign ),
1408 'tbody' => array_merge( $common, $tablealign ),
1411 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1412 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1415 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1418 'td' => array_merge( $common, $tablecell, $tablealign ),
1419 'th' => array_merge( $common, $tablecell, $tablealign ),
1421 # 12.2 # NOTE: <a> is not allowed directly, but the attrib whitelist is used from the Parser object
1422 'a' => array_merge( $common, array( 'href', 'rel', 'rev' ) ), # rel/rev esp. for RDFa
1425 # Not usually allowed, but may be used for extension-style hooks
1426 # such as <math> when it is rasterized, or if $wgAllowImageTag is
1428 'img' => array_merge( $common, array( 'alt', 'src', 'width', 'height' ) ),
1436 'strike' => $common,
1441 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1445 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1447 # XHTML Ruby annotation text module, simple ruby only.
1448 # http://www.w3c.org/TR/ruby/
1453 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1456 # MathML root element, where used for extensions
1457 # 'title' may not be 100% valid here; it's XHTML
1458 # http://www.w3.org/TR/REC-MathML/
1459 'math' => array( 'class', 'style', 'id', 'title' ),
1465 * Take a fragment of (potentially invalid) HTML and return
1466 * a version with any tags removed, encoded as plain text.
1468 * Warning: this return value must be further escaped for literal
1469 * inclusion in HTML output as of 1.10!
1471 * @param $text String: HTML fragment
1474 static function stripAllTags( $text ) {
1476 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
1478 # Normalize &entities and whitespace
1479 $text = self
::decodeCharReferences( $text );
1480 $text = self
::normalizeWhitespace( $text );
1486 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1487 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1490 * Use for passing XHTML fragments to PHP's XML parsing functions
1494 static function hackDocType() {
1495 $out = "<!DOCTYPE html [\n";
1496 foreach( self
::$htmlEntities as $entity => $codepoint ) {
1497 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1503 static function cleanUrl( $url ) {
1504 # Normalize any HTML entities in input. They will be
1505 # re-escaped by makeExternalLink().
1506 $url = Sanitizer
::decodeCharReferences( $url );
1508 # Escape any control characters introduced by the above step
1509 $url = preg_replace( '/[\][<>"\\x00-\\x20\\x7F\|]/e', "urlencode('\\0')", $url );
1511 # Validate hostname portion
1513 if( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1514 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1516 // Characters that will be ignored in IDNs.
1517 // http://tools.ietf.org/html/3454#section-3.1
1518 // Strip them before further processing so blacklists and such work.
1520 \\s| # general whitespace
1521 \xc2\xad| # 00ad SOFT HYPHEN
1522 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1523 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1524 \xe2\x81\xa0| # 2060 WORD JOINER
1525 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1526 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1527 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1528 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1529 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1530 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1531 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1532 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe00f VARIATION SELECTOR-1-16
1535 $host = preg_replace( $strip, '', $host );
1537 // @todo Fixme: validate hostnames here
1539 return $protocol . $host . $rest;