3 * HTML 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 * HTML 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]+);
43 * Blacklist for evil uris like javascript:
44 * WARNING: DO NOT use this in any place that actually requires blacklisting
45 * for security reasons. There are NUMEROUS[1] ways to bypass blacklisting, the
46 * only way to be secure from javascript: uri based xss vectors is to whitelist
47 * things that you know are safe and deny everything else.
48 * [1]: http://ha.ckers.org/xss.html
50 const EVIL_URI_PATTERN
= '!(^|\s|\*/\s*)(javascript|vbscript)([^\w]|$)!i';
51 const XMLNS_ATTRIBUTE_PATTERN
= "/^xmlns:[:A-Z_a-z-.0-9]+$/";
54 * List of all named character entities defined in HTML 4.01
55 * http://www.w3.org/TR/html4/sgml/entities.html
56 * As well as ' which is only defined starting in XHTML1.
59 private static $htmlEntities = array(
75 'apos' => 39, // New in XHTML & HTML 5; avoid in output for compatibility with IE.
316 * Character entity aliases accepted by MediaWiki
318 private static $htmlEntityAliases = array(
324 * Lazy-initialised attributes regex, see getAttribsRegex()
327 private static $attribsRegex;
330 * Regular expression to match HTML/XML attribute pairs within a tag.
331 * Allows some... latitude.
332 * Used in Sanitizer::fixTagAttributes and Sanitizer::decodeTagAttributes
334 static function getAttribsRegex() {
335 if ( self
::$attribsRegex === null ) {
336 $attribFirst = '[:A-Z_a-z0-9]';
337 $attrib = '[:A-Z_a-z-.0-9]';
338 $space = '[\x09\x0a\x0d\x20]';
339 self
::$attribsRegex =
340 "/(?:^|$space)({$attribFirst}{$attrib}*)
343 # The attribute value: quoted or alone
346 | ([a-zA-Z0-9!#$%&()*,\\-.\\/:;<>?@[\\]^_`{|}~]+)
347 | (\#[0-9a-fA-F]+) # Technically wrong, but lots of
348 # colors are specified like this.
349 # We'll be normalizing it.
353 return self
::$attribsRegex;
357 * Cleans up HTML, removes dangerous tags and attributes, and
358 * removes HTML comments
360 * @param $text String
361 * @param $processCallback Callback to do any variable or parameter
362 * replacements in HTML attribute values
363 * @param array $args for the processing callback
364 * @param array $extratags for any extra tags to include
365 * @param array $removetags for any tags (default or extra) to exclude
368 static function removeHTMLtags( $text, $processCallback = null,
369 $args = array(), $extratags = array(), $removetags = array()
371 global $wgUseTidy, $wgAllowMicrodataAttributes, $wgAllowImageTag;
373 static $htmlpairsStatic, $htmlsingle, $htmlsingleonly, $htmlnest, $tabletags,
374 $htmllist, $listtags, $htmlsingleallowed, $htmlelementsStatic, $staticInitialised;
376 wfProfileIn( __METHOD__
);
378 // Base our staticInitialised variable off of the global config state so that if the globals
379 // are changed (like in the screwed up test system) we will re-initialise the settings.
380 $globalContext = implode( '-', compact( 'wgAllowMicrodataAttributes', 'wgAllowImageTag' ) );
381 if ( !$staticInitialised ||
$staticInitialised != $globalContext ) {
383 $htmlpairsStatic = array( # Tags that must be closed
384 'b', 'bdi', 'del', 'i', 'ins', 'u', 'font', 'big', 'small', 'sub', 'sup', 'h1',
385 'h2', 'h3', 'h4', 'h5', 'h6', 'cite', 'code', 'em', 's',
386 'strike', 'strong', 'tt', 'var', 'div', 'center',
387 'blockquote', 'ol', 'ul', 'dl', 'table', 'caption', 'pre',
388 'ruby', 'rt', 'rb', 'rp', 'p', 'span', 'abbr', 'dfn',
389 'kbd', 'samp', 'data', 'time', 'mark'
392 'br', 'hr', 'li', 'dt', 'dd'
394 $htmlsingleonly = array( # Elements that cannot have close tags
397 if ( $wgAllowMicrodataAttributes ) {
398 $htmlsingle[] = $htmlsingleonly[] = 'meta';
399 $htmlsingle[] = $htmlsingleonly[] = 'link';
401 $htmlnest = array( # Tags that can be nested--??
402 'table', 'tr', 'td', 'th', 'div', 'blockquote', 'ol', 'ul',
403 'li', 'dl', 'dt', 'dd', 'font', 'big', 'small', 'sub', 'sup', 'span',
404 'var', 'kbd', 'samp', 'em', 'strong', 'q', 'ruby', 'bdo'
406 $tabletags = array( # Can only appear inside table, we will close them
409 $htmllist = array( # Tags used by list
412 $listtags = array( # Tags that can appear in a list
416 if ( $wgAllowImageTag ) {
417 $htmlsingle[] = 'img';
418 $htmlsingleonly[] = 'img';
421 $htmlsingleallowed = array_unique( array_merge( $htmlsingle, $tabletags ) );
422 $htmlelementsStatic = array_unique( array_merge( $htmlsingle, $htmlpairsStatic, $htmlnest ) );
424 # Convert them all to hashtables for faster lookup
425 $vars = array( 'htmlpairsStatic', 'htmlsingle', 'htmlsingleonly', 'htmlnest', 'tabletags',
426 'htmllist', 'listtags', 'htmlsingleallowed', 'htmlelementsStatic' );
427 foreach ( $vars as $var ) {
428 $
$var = array_flip( $
$var );
430 $staticInitialised = $globalContext;
432 # Populate $htmlpairs and $htmlelements with the $extratags and $removetags arrays
433 $extratags = array_flip( $extratags );
434 $removetags = array_flip( $removetags );
435 $htmlpairs = array_merge( $extratags, $htmlpairsStatic );
436 $htmlelements = array_diff_key( array_merge( $extratags, $htmlelementsStatic ), $removetags );
438 # Remove HTML comments
439 $text = Sanitizer
::removeHTMLcomments( $text );
440 $bits = explode( '<', $text );
441 $text = str_replace( '>', '>', array_shift( $bits ) );
443 $tagstack = $tablestack = array();
444 foreach ( $bits as $x ) {
446 # $slash: Does the current element start with a '/'?
447 # $t: Current element name
448 # $params: String between element name and >
449 # $brace: Ending '>' or '/>'
450 # $rest: Everything until the next element of $bits
451 if ( preg_match( '!^(/?)([^\\s/>]+)([^>]*?)(/{0,1}>)([^<]*)$!', $x, $regs ) ) {
452 list( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
454 $slash = $t = $params = $brace = $rest = null;
458 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
460 if ( $slash && isset( $htmlsingleonly[$t] ) ) {
462 } elseif ( $slash ) {
463 # Closing a tag... is it the one we just opened?
464 $ot = @array_pop
( $tagstack );
466 if ( isset( $htmlsingleallowed[$ot] ) ) {
467 # Pop all elements with an optional close tag
468 # and see if we find a match below them
470 array_push( $optstack, $ot );
471 wfSuppressWarnings();
472 $ot = array_pop( $tagstack );
474 while ( $ot != $t && isset( $htmlsingleallowed[$ot] ) ) {
475 array_push( $optstack, $ot );
476 wfSuppressWarnings();
477 $ot = array_pop( $tagstack );
481 # No match. Push the optional elements back again
483 wfSuppressWarnings();
484 $ot = array_pop( $optstack );
487 array_push( $tagstack, $ot );
488 wfSuppressWarnings();
489 $ot = array_pop( $optstack );
494 @array_push
( $tagstack, $ot );
495 # <li> can be nested in <ul> or <ol>, skip those cases:
496 if ( !isset( $htmllist[$ot] ) ||
!isset( $listtags[$t] ) ) {
501 if ( $t == 'table' ) {
502 $tagstack = array_pop( $tablestack );
507 # Keep track for later
508 if ( isset( $tabletags[$t] ) &&
509 !in_array( 'table', $tagstack ) ) {
511 } elseif ( in_array( $t, $tagstack ) &&
512 !isset( $htmlnest[$t] ) ) {
514 # Is it a self closed htmlpair ? (bug 5487)
515 } elseif ( $brace == '/>' &&
516 isset( $htmlpairs[$t] ) ) {
518 } elseif ( isset( $htmlsingleonly[$t] ) ) {
519 # Hack to force empty tag for unclosable elements
521 } elseif ( isset( $htmlsingle[$t] ) ) {
522 # Hack to not close $htmlsingle tags
524 # Still need to push this optionally-closed tag to
525 # the tag stack so that we can match end tags
526 # instead of marking them as bad.
527 array_push( $tagstack, $t );
528 } elseif ( isset( $tabletags[$t] )
529 && in_array( $t, $tagstack ) ) {
530 // New table tag but forgot to close the previous one
533 if ( $t == 'table' ) {
534 array_push( $tablestack, $tagstack );
537 array_push( $tagstack, $t );
540 # Replace any variables or template parameters with
542 if ( is_callable( $processCallback ) ) {
543 call_user_func_array( $processCallback, array( &$params, $args ) );
546 if ( !Sanitizer
::validateTag( $params, $t ) ) {
550 # Strip non-approved attributes from the tag
551 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
554 $rest = str_replace( '>', '>', $rest );
555 $close = ( $brace == '/>' && !$slash ) ?
' /' : '';
556 $text .= "<$slash$t$newparams$close>$rest";
560 $text .= '<' . str_replace( '>', '>', $x );
562 # Close off any remaining tags
563 while ( is_array( $tagstack ) && ( $t = array_pop( $tagstack ) ) ) {
565 if ( $t == 'table' ) {
566 $tagstack = array_pop( $tablestack );
570 # this might be possible using tidy itself
571 foreach ( $bits as $x ) {
572 preg_match( '/^(\\/?)(\\w+)([^>]*?)(\\/{0,1}>)([^<]*)$/',
574 @list
( /* $qbar */, $slash, $t, $params, $brace, $rest ) = $regs;
576 if ( isset( $htmlelements[$t = strtolower( $t )] ) ) {
577 if ( is_callable( $processCallback ) ) {
578 call_user_func_array( $processCallback, array( &$params, $args ) );
581 if ( !Sanitizer
::validateTag( $params, $t ) ) {
585 $newparams = Sanitizer
::fixTagAttributes( $params, $t );
587 $rest = str_replace( '>', '>', $rest );
588 $text .= "<$slash$t$newparams$brace$rest";
592 $text .= '<' . str_replace( '>', '>', $x );
595 wfProfileOut( __METHOD__
);
600 * Remove '<!--', '-->', and everything between.
601 * To avoid leaving blank lines, when a comment is both preceded
602 * and followed by a newline (ignoring spaces), trim leading and
603 * trailing spaces and one of the newlines.
606 * @param $text String
609 static function removeHTMLcomments( $text ) {
610 wfProfileIn( __METHOD__
);
611 while ( ( $start = strpos( $text, '<!--' ) ) !== false ) {
612 $end = strpos( $text, '-->', $start +
4 );
613 if ( $end === false ) {
614 # Unterminated comment; bail out
620 # Trim space and newline if the comment is both
621 # preceded and followed by a newline
622 $spaceStart = max( $start - 1, 0 );
623 $spaceLen = $end - $spaceStart;
624 while ( substr( $text, $spaceStart, 1 ) === ' ' && $spaceStart > 0 ) {
628 while ( substr( $text, $spaceStart +
$spaceLen, 1 ) === ' ' ) {
631 if ( substr( $text, $spaceStart, 1 ) === "\n"
632 && substr( $text, $spaceStart +
$spaceLen, 1 ) === "\n" ) {
633 # Remove the comment, leading and trailing
634 # spaces, and leave only one newline.
635 $text = substr_replace( $text, "\n", $spaceStart, $spaceLen +
1 );
638 # Remove just the comment.
639 $text = substr_replace( $text, '', $start, $end - $start );
642 wfProfileOut( __METHOD__
);
647 * Takes attribute names and values for a tag and the tag name and
648 * validates that the tag is allowed to be present.
649 * This DOES NOT validate the attributes, nor does it validate the
650 * tags themselves. This method only handles the special circumstances
651 * where we may want to allow a tag within content but ONLY when it has
652 * specific attributes set.
658 static function validateTag( $params, $element ) {
659 $params = Sanitizer
::decodeTagAttributes( $params );
661 if ( $element == 'meta' ||
$element == 'link' ) {
662 if ( !isset( $params['itemprop'] ) ) {
663 // <meta> and <link> must have an itemprop="" otherwise they are not valid or safe in content
666 if ( $element == 'meta' && !isset( $params['content'] ) ) {
667 // <meta> must have a content="" for the itemprop
670 if ( $element == 'link' && !isset( $params['href'] ) ) {
671 // <link> must have an associated href=""
680 * Take an array of attribute names and values and normalize or discard
681 * illegal values for the given element type.
683 * - Discards attributes not on a whitelist for the given element
684 * - Unsafe style attributes are discarded
685 * - Invalid id attributes are re-encoded
687 * @param $attribs Array
688 * @param $element String
691 * @todo Check for legal values where the DTD limits things.
692 * @todo Check for unique id attribute :P
694 static function validateTagAttributes( $attribs, $element ) {
695 return Sanitizer
::validateAttributes( $attribs,
696 Sanitizer
::attributeWhitelist( $element ) );
700 * Take an array of attribute names and values and normalize or discard
701 * illegal values for the given whitelist.
703 * - Discards attributes not the given whitelist
704 * - Unsafe style attributes are discarded
705 * - Invalid id attributes are re-encoded
707 * @param $attribs Array
708 * @param array $whitelist list of allowed attribute names
711 * @todo Check for legal values where the DTD limits things.
712 * @todo Check for unique id attribute :P
714 static function validateAttributes( $attribs, $whitelist ) {
715 global $wgAllowRdfaAttributes, $wgAllowMicrodataAttributes;
717 $whitelist = array_flip( $whitelist );
718 $hrefExp = '/^(' . wfUrlProtocols() . ')[^\s]+$/';
721 foreach ( $attribs as $attribute => $value ) {
722 #allow XML namespace declaration if RDFa is enabled
723 if ( $wgAllowRdfaAttributes && preg_match( self
::XMLNS_ATTRIBUTE_PATTERN
, $attribute ) ) {
724 if ( !preg_match( self
::EVIL_URI_PATTERN
, $value ) ) {
725 $out[$attribute] = $value;
731 # Allow any attribute beginning with "data-"
732 if ( !preg_match( '/^data-/i', $attribute ) && !isset( $whitelist[$attribute] ) ) {
736 # Strip javascript "expression" from stylesheets.
737 # http://msdn.microsoft.com/workshop/author/dhtml/overview/recalc.asp
738 if ( $attribute == 'style' ) {
739 $value = Sanitizer
::checkCss( $value );
742 if ( $attribute === 'id' ) {
743 $value = Sanitizer
::escapeId( $value, 'noninitial' );
747 # http://www.w3.org/TR/wai-aria/
748 # http://www.whatwg.org/html/elements.html#wai-aria
749 # For now we only support role="presentation" until we work out what roles should be
750 # usable by content and we ensure that our code explicitly rejects patterns that
751 # violate HTML5's ARIA restrictions.
752 if ( $attribute === 'role' && $value !== 'presentation' ) {
756 // RDFa and microdata properties allow URLs, URIs and/or CURIs.
757 // Check them for sanity.
758 if ( $attribute === 'rel' ||
$attribute === 'rev'
760 ||
$attribute === 'about' ||
$attribute === 'property'
761 ||
$attribute === 'resource' ||
$attribute === 'datatype'
762 ||
$attribute === 'typeof'
764 ||
$attribute === 'itemid' ||
$attribute === 'itemprop'
765 ||
$attribute === 'itemref' ||
$attribute === 'itemscope'
766 ||
$attribute === 'itemtype'
768 //Paranoia. Allow "simple" values but suppress javascript
769 if ( preg_match( self
::EVIL_URI_PATTERN
, $value ) ) {
774 # NOTE: even though elements using href/src are not allowed directly, supply
775 # validation code that can be used by tag hook handlers, etc
776 if ( $attribute === 'href' ||
$attribute === 'src' ) {
777 if ( !preg_match( $hrefExp, $value ) ) {
778 continue; //drop any href or src attributes not using an allowed protocol.
779 // NOTE: this also drops all relative URLs
783 // If this attribute was previously set, override it.
784 // Output should only have one attribute of each name.
785 $out[$attribute] = $value;
788 if ( $wgAllowMicrodataAttributes ) {
789 # itemtype, itemid, itemref don't make sense without itemscope
790 if ( !array_key_exists( 'itemscope', $out ) ) {
791 unset( $out['itemtype'] );
792 unset( $out['itemid'] );
793 unset( $out['itemref'] );
795 # TODO: Strip itemprop if we aren't descendants of an itemscope or pointed to by an itemref.
801 * Merge two sets of HTML attributes. Conflicting items in the second set
802 * will override those in the first, except for 'class' attributes which
803 * will be combined (if they're both strings).
805 * @todo implement merging for other attributes such as style
810 static function mergeAttributes( $a, $b ) {
811 $out = array_merge( $a, $b );
812 if ( isset( $a['class'] ) && isset( $b['class'] )
813 && is_string( $a['class'] ) && is_string( $b['class'] )
814 && $a['class'] !== $b['class']
816 $classes = preg_split( '/\s+/', "{$a['class']} {$b['class']}",
817 -1, PREG_SPLIT_NO_EMPTY
);
818 $out['class'] = implode( ' ', array_unique( $classes ) );
824 * Pick apart some CSS and check it for forbidden or unsafe structures.
825 * Returns a sanitized string. This sanitized string will have
826 * character references and escape sequences decoded and comments
827 * stripped (unless it is itself one valid comment, in which case the value
828 * will be passed through). If the input is just too evil, only a comment
829 * complaining about evilness will be returned.
831 * Currently URL references, 'expression', 'tps' are forbidden.
833 * NOTE: Despite the fact that character references are decoded, the
834 * returned string may contain character references given certain
835 * clever input strings. These character references must
836 * be escaped before the return value is embedded in HTML.
838 * @param $value String
841 static function checkCss( $value ) {
842 // Decode character references like {
843 $value = Sanitizer
::decodeCharReferences( $value );
845 // Decode escape sequences and line continuation
846 // See the grammar in the CSS 2 spec, appendix D.
847 // This has to be done AFTER decoding character references.
848 // This means it isn't possible for this function to return
849 // unsanitized escape sequences. It is possible to manufacture
850 // input that contains character references that decode to
851 // escape sequences that decode to character references, but
852 // it's OK for the return value to contain character references
853 // because the caller is supposed to escape those anyway.
855 if ( !$decodeRegex ) {
856 $space = '[\\x20\\t\\r\\n\\f]';
857 $nl = '(?:\\n|\\r\\n|\\r|\\f)';
859 $decodeRegex = "/ $backslash
861 ($nl) | # 1. Line continuation
862 ([0-9A-Fa-f]{1,6})$space? | # 2. character number
863 (.) | # 3. backslash cancelling special meaning
864 () | # 4. backslash at end of string
867 $value = preg_replace_callback( $decodeRegex,
868 array( __CLASS__
, 'cssDecodeCallback' ), $value );
870 // Let the value through if it's nothing but a single comment, to
871 // allow other functions which may reject it to pass some error
873 if ( !preg_match( '! ^ \s* /\* [^*\\/]* \*/ \s* $ !x', $value ) ) {
874 // Remove any comments; IE gets token splitting wrong
875 // This must be done AFTER decoding character references and
876 // escape sequences, because those steps can introduce comments
877 // This step cannot introduce character references or escape
878 // sequences, because it replaces comments with spaces rather
879 // than removing them completely.
880 $value = StringUtils
::delimiterReplace( '/*', '*/', ' ', $value );
882 // Remove anything after a comment-start token, to guard against
883 // incorrect client implementations.
884 $commentPos = strpos( $value, '/*' );
885 if ( $commentPos !== false ) {
886 $value = substr( $value, 0, $commentPos );
890 // Reject problematic keywords and control characters
891 if ( preg_match( '/[\000-\010\016-\037\177]/', $value ) ) {
892 return '/* invalid control char */';
893 } elseif ( preg_match( '! expression | filter\s*: | accelerator\s*: | url\s*\( | image\s*\( | image-set\s*\( !ix', $value ) ) {
894 return '/* insecure input */';
900 * @param $matches array
903 static function cssDecodeCallback( $matches ) {
904 if ( $matches[1] !== '' ) {
907 } elseif ( $matches[2] !== '' ) {
908 $char = codepointToUtf8( hexdec( $matches[2] ) );
909 } elseif ( $matches[3] !== '' ) {
914 if ( $char == "\n" ||
$char == '"' ||
$char == "'" ||
$char == '\\' ) {
915 // These characters need to be escaped in strings
916 // Clean up the escape sequence to avoid parsing errors by clients
917 return '\\' . dechex( ord( $char ) ) . ' ';
919 // Decode unnecessary escape
925 * Take a tag soup fragment listing an HTML element's attributes
926 * and normalize it to well-formed XML, discarding unwanted attributes.
927 * Output is safe for further wikitext processing, with escaping of
928 * values that could trigger problems.
930 * - Normalizes attribute names to lowercase
931 * - Discards attributes not on a whitelist for the given element
932 * - Turns broken or invalid entities into plaintext
933 * - Double-quotes all attribute values
934 * - Attributes without values are given the name as attribute
935 * - Double attributes are discarded
936 * - Unsafe style attributes are discarded
937 * - Prepends space if there are attributes.
939 * @param $text String
940 * @param $element String
943 static function fixTagAttributes( $text, $element ) {
944 if ( trim( $text ) == '' ) {
948 $decoded = Sanitizer
::decodeTagAttributes( $text );
949 $stripped = Sanitizer
::validateTagAttributes( $decoded, $element );
951 return Sanitizer
::safeEncodeTagAttributes( $stripped );
955 * Encode an attribute value for HTML output.
956 * @param $text String
957 * @return HTML-encoded text fragment
959 static function encodeAttribute( $text ) {
960 $encValue = htmlspecialchars( $text, ENT_QUOTES
);
962 // Whitespace is normalized during attribute decoding,
963 // so if we've been passed non-spaces we must encode them
964 // ahead of time or they won't be preserved.
965 $encValue = strtr( $encValue, array(
975 * Encode an attribute value for HTML tags, with extra armoring
976 * against further wiki processing.
977 * @param $text String
978 * @return HTML-encoded text fragment
980 static function safeEncodeAttribute( $text ) {
981 $encValue = Sanitizer
::encodeAttribute( $text );
983 # Templates and links may be expanded in later parsing,
984 # creating invalid or dangerous output. Suppress this.
985 $encValue = strtr( $encValue, array(
986 '<' => '<', // This should never happen,
987 '>' => '>', // we've received invalid input
988 '"' => '"', // which should have been escaped.
991 "''" => '''',
992 'ISBN' => 'ISBN',
994 'PMID' => 'PMID',
1000 $encValue = preg_replace_callback(
1001 '/((?i)' . wfUrlProtocols() . ')/',
1002 array( 'Sanitizer', 'armorLinksCallback' ),
1008 * Given a value, escape it so that it can be used in an id attribute and
1009 * return it. This will use HTML5 validation if $wgExperimentalHtmlIds is
1010 * true, allowing anything but ASCII whitespace. Otherwise it will use
1011 * HTML 4 rules, which means a narrow subset of ASCII, with bad characters
1012 * escaped with lots of dots.
1014 * To ensure we don't have to bother escaping anything, we also strip ', ",
1015 * & even if $wgExperimentalIds is true. TODO: Is this the best tactic?
1016 * We also strip # because it upsets IE, and % because it could be
1017 * ambiguous if it's part of something that looks like a percent escape
1018 * (which don't work reliably in fragments cross-browser).
1020 * @see http://www.w3.org/TR/html401/types.html#type-name Valid characters
1023 * @see http://www.w3.org/TR/html401/struct/links.html#h-12.2.3 Anchors with the id attribute
1024 * @see http://www.whatwg.org/html/elements.html#the-id-attribute
1025 * HTML5 definition of id attribute
1027 * @param string $id id to escape
1028 * @param $options Mixed: string or array of strings (default is array()):
1029 * 'noninitial': This is a non-initial fragment of an id, not a full id,
1030 * so don't pay attention if the first character isn't valid at the
1031 * beginning of an id. Only matters if $wgExperimentalHtmlIds is
1033 * 'legacy': Behave the way the old HTML 4-based ID escaping worked even
1034 * if $wgExperimentalHtmlIds is used, so we can generate extra
1035 * anchors and links won't break.
1038 static function escapeId( $id, $options = array() ) {
1039 global $wgExperimentalHtmlIds;
1040 $options = (array)$options;
1042 if ( $wgExperimentalHtmlIds && !in_array( 'legacy', $options ) ) {
1043 $id = Sanitizer
::decodeCharReferences( $id );
1044 $id = preg_replace( '/[ \t\n\r\f_\'"&#%]+/', '_', $id );
1045 $id = trim( $id, '_' );
1047 # Must have been all whitespace to start with.
1054 # HTML4-style escaping
1055 static $replace = array(
1060 $id = urlencode( Sanitizer
::decodeCharReferences( strtr( $id, ' ', '_' ) ) );
1061 $id = str_replace( array_keys( $replace ), array_values( $replace ), $id );
1063 if ( !preg_match( '/^[a-zA-Z]/', $id )
1064 && !in_array( 'noninitial', $options ) ) {
1065 // Initial character must be a letter!
1072 * Given a value, escape it so that it can be used as a CSS class and
1075 * @todo For extra validity, input should be validated UTF-8.
1077 * @see http://www.w3.org/TR/CSS21/syndata.html Valid characters/format
1079 * @param $class String
1082 static function escapeClass( $class ) {
1083 // Convert ugly stuff to underscores and kill underscores in ugly places
1084 return rtrim( preg_replace(
1085 array( '/(^[0-9\\-])|[\\x00-\\x20!"#$%&\'()*+,.\\/:;<=>?@[\\]^`{|}~]|\\xC2\\xA0/', '/_+/' ),
1091 * Given HTML input, escape with htmlspecialchars but un-escape entities.
1092 * This allows (generally harmless) entities like   to survive.
1094 * @param string $html to escape
1095 * @return String: escaped input
1097 static function escapeHtmlAllowEntities( $html ) {
1098 $html = Sanitizer
::decodeCharReferences( $html );
1099 # It seems wise to escape ' as well as ", as a matter of course. Can't
1101 $html = htmlspecialchars( $html, ENT_QUOTES
);
1106 * Regex replace callback for armoring links against further processing.
1107 * @param $matches Array
1110 private static function armorLinksCallback( $matches ) {
1111 return str_replace( ':', ':', $matches[1] );
1115 * Return an associative array of attribute names and values from
1116 * a partial tag string. Attribute names are forces to lowercase,
1117 * character references are decoded to UTF-8 text.
1119 * @param $text String
1122 public static function decodeTagAttributes( $text ) {
1123 if ( trim( $text ) == '' ) {
1129 if ( !preg_match_all(
1130 self
::getAttribsRegex(),
1133 PREG_SET_ORDER
) ) {
1137 foreach ( $pairs as $set ) {
1138 $attribute = strtolower( $set[1] );
1139 $value = Sanitizer
::getTagAttributeCallback( $set );
1141 // Normalize whitespace
1142 $value = preg_replace( '/[\t\r\n ]+/', ' ', $value );
1143 $value = trim( $value );
1145 // Decode character references
1146 $attribs[$attribute] = Sanitizer
::decodeCharReferences( $value );
1152 * Build a partial tag string from an associative array of attribute
1153 * names and values as returned by decodeTagAttributes.
1155 * @param $assoc_array Array
1158 public static function safeEncodeTagAttributes( $assoc_array ) {
1160 foreach ( $assoc_array as $attribute => $value ) {
1161 $encAttribute = htmlspecialchars( $attribute );
1162 $encValue = Sanitizer
::safeEncodeAttribute( $value );
1164 $attribs[] = "$encAttribute=\"$encValue\"";
1166 return count( $attribs ) ?
' ' . implode( ' ', $attribs ) : '';
1170 * Pick the appropriate attribute value from a match set from the
1171 * attribs regex matches.
1174 * @throws MWException
1177 private static function getTagAttributeCallback( $set ) {
1178 if ( isset( $set[6] ) ) {
1179 # Illegal #XXXXXX color with no quotes.
1181 } elseif ( isset( $set[5] ) ) {
1184 } elseif ( isset( $set[4] ) ) {
1187 } elseif ( isset( $set[3] ) ) {
1190 } elseif ( !isset( $set[2] ) ) {
1191 # In XHTML, attributes must have a value.
1192 # For 'reduced' form, return explicitly the attribute name here.
1195 throw new MWException( "Tag conditions not met. This should never happen and is a bug." );
1200 * Normalize whitespace and character references in an XML source-
1201 * encoded text for an attribute value.
1203 * See http://www.w3.org/TR/REC-xml/#AVNormalize for background,
1204 * but note that we're not returning the value, but are returning
1205 * XML source fragments that will be slapped into output.
1207 * @param $text String
1210 private static function normalizeAttributeValue( $text ) {
1211 return str_replace( '"', '"',
1212 self
::normalizeWhitespace(
1213 Sanitizer
::normalizeCharReferences( $text ) ) );
1217 * @param $text string
1220 private static function normalizeWhitespace( $text ) {
1221 return preg_replace(
1222 '/\r\n|[\x20\x0d\x0a\x09]/',
1228 * Normalizes whitespace in a section name, such as might be returned
1229 * by Parser::stripSectionName(), for use in the id's that are used for
1232 * @param $section String
1235 static function normalizeSectionNameWhitespace( $section ) {
1236 return trim( preg_replace( '/[ _]+/', ' ', $section ) );
1240 * Ensure that any entities and character references are legal
1241 * for XML and XHTML specifically. Any stray bits will be
1242 * &-escaped to result in a valid text fragment.
1244 * a. named char refs can only be < > & ", others are
1245 * numericized (this way we're well-formed even without a DTD)
1246 * b. any numeric char refs must be legal chars, not invalid or forbidden
1247 * c. use lower cased "&#x", not "&#X"
1248 * d. fix or reject non-valid attributes
1250 * @param $text String
1254 static function normalizeCharReferences( $text ) {
1255 return preg_replace_callback(
1256 self
::CHAR_REFS_REGEX
,
1257 array( 'Sanitizer', 'normalizeCharReferencesCallback' ),
1261 * @param $matches String
1264 static function normalizeCharReferencesCallback( $matches ) {
1266 if ( $matches[1] != '' ) {
1267 $ret = Sanitizer
::normalizeEntity( $matches[1] );
1268 } elseif ( $matches[2] != '' ) {
1269 $ret = Sanitizer
::decCharReference( $matches[2] );
1270 } elseif ( $matches[3] != '' ) {
1271 $ret = Sanitizer
::hexCharReference( $matches[3] );
1273 if ( is_null( $ret ) ) {
1274 return htmlspecialchars( $matches[0] );
1281 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1282 * return the equivalent numeric entity reference (except for the core <
1283 * > & "). If the entity is a MediaWiki-specific alias, returns
1284 * the HTML equivalent. Otherwise, returns HTML-escaped text of
1285 * pseudo-entity source (eg &foo;)
1287 * @param $name String
1290 static function normalizeEntity( $name ) {
1291 if ( isset( self
::$htmlEntityAliases[$name] ) ) {
1292 return '&' . self
::$htmlEntityAliases[$name] . ';';
1293 } elseif ( in_array( $name,
1294 array( 'lt', 'gt', 'amp', 'quot' ) ) ) {
1296 } elseif ( isset( self
::$htmlEntities[$name] ) ) {
1297 return '&#' . self
::$htmlEntities[$name] . ';';
1299 return "&$name;";
1305 * @return null|string
1307 static function decCharReference( $codepoint ) {
1308 $point = intval( $codepoint );
1309 if ( Sanitizer
::validateCodepoint( $point ) ) {
1310 return sprintf( '&#%d;', $point );
1318 * @return null|string
1320 static function hexCharReference( $codepoint ) {
1321 $point = hexdec( $codepoint );
1322 if ( Sanitizer
::validateCodepoint( $point ) ) {
1323 return sprintf( '&#x%x;', $point );
1330 * Returns true if a given Unicode codepoint is a valid character in XML.
1331 * @param $codepoint Integer
1334 private static function validateCodepoint( $codepoint ) {
1335 return $codepoint == 0x09
1336 ||
$codepoint == 0x0a
1337 ||
$codepoint == 0x0d
1338 ||
( $codepoint >= 0x20 && $codepoint <= 0xd7ff )
1339 ||
( $codepoint >= 0xe000 && $codepoint <= 0xfffd )
1340 ||
( $codepoint >= 0x10000 && $codepoint <= 0x10ffff );
1344 * Decode any character references, numeric or named entities,
1345 * in the text and return a UTF-8 string.
1347 * @param $text String
1350 public static function decodeCharReferences( $text ) {
1351 return preg_replace_callback(
1352 self
::CHAR_REFS_REGEX
,
1353 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1358 * Decode any character references, numeric or named entities,
1359 * in the next and normalize the resulting string. (bug 14952)
1361 * This is useful for page titles, not for text to be displayed,
1362 * MediaWiki allows HTML entities to escape normalization as a feature.
1364 * @param string $text (already normalized, containing entities)
1365 * @return String (still normalized, without entities)
1367 public static function decodeCharReferencesAndNormalize( $text ) {
1369 $text = preg_replace_callback(
1370 self
::CHAR_REFS_REGEX
,
1371 array( 'Sanitizer', 'decodeCharReferencesCallback' ),
1372 $text, /* limit */ -1, $count );
1375 return $wgContLang->normalize( $text );
1382 * @param $matches String
1385 static function decodeCharReferencesCallback( $matches ) {
1386 if ( $matches[1] != '' ) {
1387 return Sanitizer
::decodeEntity( $matches[1] );
1388 } elseif ( $matches[2] != '' ) {
1389 return Sanitizer
::decodeChar( intval( $matches[2] ) );
1390 } elseif ( $matches[3] != '' ) {
1391 return Sanitizer
::decodeChar( hexdec( $matches[3] ) );
1393 # Last case should be an ampersand by itself
1398 * Return UTF-8 string for a codepoint if that is a valid
1399 * character reference, otherwise U+FFFD REPLACEMENT CHARACTER.
1400 * @param $codepoint Integer
1404 static function decodeChar( $codepoint ) {
1405 if ( Sanitizer
::validateCodepoint( $codepoint ) ) {
1406 return codepointToUtf8( $codepoint );
1408 return UTF8_REPLACEMENT
;
1413 * If the named entity is defined in the HTML 4.0/XHTML 1.0 DTD,
1414 * return the UTF-8 encoding of that character. Otherwise, returns
1415 * pseudo-entity source (eg "&foo;")
1417 * @param $name String
1420 static function decodeEntity( $name ) {
1421 if ( isset( self
::$htmlEntityAliases[$name] ) ) {
1422 $name = self
::$htmlEntityAliases[$name];
1424 if ( isset( self
::$htmlEntities[$name] ) ) {
1425 return codepointToUtf8( self
::$htmlEntities[$name] );
1432 * Fetch the whitelist of acceptable attributes for a given element name.
1434 * @param $element String
1437 static function attributeWhitelist( $element ) {
1438 $list = Sanitizer
::setupAttributeWhitelist();
1439 return isset( $list[$element] )
1445 * Foreach array key (an allowed HTML element), return an array
1446 * of allowed attributes
1449 static function setupAttributeWhitelist() {
1450 global $wgAllowRdfaAttributes, $wgAllowMicrodataAttributes;
1452 static $whitelist, $staticInitialised;
1453 $globalContext = implode( '-', compact( 'wgAllowRdfaAttributes', 'wgAllowMicrodataAttributes' ) );
1455 if ( isset( $whitelist ) && $staticInitialised == $globalContext ) {
1472 if ( $wgAllowRdfaAttributes ) {
1473 # RDFa attributes as specified in section 9 of
1474 # http://www.w3.org/TR/2008/REC-rdfa-syntax-20081014
1475 $common = array_merge( $common, array(
1476 'about', 'property', 'resource', 'datatype', 'typeof',
1480 if ( $wgAllowMicrodataAttributes ) {
1481 # add HTML5 microdata tags as specified by
1482 # http://www.whatwg.org/html/microdata.html#the-microdata-model
1483 $common = array_merge( $common, array(
1484 'itemid', 'itemprop', 'itemref', 'itemscope', 'itemtype'
1488 $block = array_merge( $common, array( 'align' ) );
1489 $tablealign = array( 'align', 'char', 'charoff', 'valign' );
1497 'nowrap', # deprecated
1498 'width', # deprecated
1499 'height', # deprecated
1500 'bgcolor', # deprecated
1503 # Numbers refer to sections in HTML 4.01 standard describing the element.
1504 # See: http://www.w3.org/TR/html4/
1508 'center' => $common, # deprecated
1509 'span' => $block, # ??
1527 'strong' => $common,
1538 'blockquote' => array_merge( $common, array( 'cite' ) ),
1549 'br' => array( 'id', 'class', 'title', 'style', 'clear' ),
1552 'pre' => array_merge( $common, array( 'width' ) ),
1555 'ins' => array_merge( $common, array( 'cite', 'datetime' ) ),
1556 'del' => array_merge( $common, array( 'cite', 'datetime' ) ),
1559 'ul' => array_merge( $common, array( 'type' ) ),
1560 'ol' => array_merge( $common, array( 'type', 'start' ) ),
1561 'li' => array_merge( $common, array( 'type', 'value' ) ),
1569 'table' => array_merge( $common,
1570 array( 'summary', 'width', 'border', 'frame',
1571 'rules', 'cellspacing', 'cellpadding',
1576 'caption' => array_merge( $common, array( 'align' ) ),
1579 'thead' => array_merge( $common, $tablealign ),
1580 'tfoot' => array_merge( $common, $tablealign ),
1581 'tbody' => array_merge( $common, $tablealign ),
1584 'colgroup' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1585 'col' => array_merge( $common, array( 'span', 'width' ), $tablealign ),
1588 'tr' => array_merge( $common, array( 'bgcolor' ), $tablealign ),
1591 'td' => array_merge( $common, $tablecell, $tablealign ),
1592 'th' => array_merge( $common, $tablecell, $tablealign ),
1595 # NOTE: <a> is not allowed directly, but the attrib
1596 # whitelist is used from the Parser object
1597 'a' => array_merge( $common, array( 'href', 'rel', 'rev' ) ), # rel/rev esp. for RDFa
1600 # Not usually allowed, but may be used for extension-style hooks
1601 # such as <math> when it is rasterized, or if $wgAllowImageTag is
1603 'img' => array_merge( $common, array( 'alt', 'src', 'width', 'height' ) ),
1611 'strike' => $common,
1616 'font' => array_merge( $common, array( 'size', 'color', 'face' ) ),
1620 'hr' => array_merge( $common, array( 'noshade', 'size', 'width' ) ),
1622 # HTML Ruby annotation text module, simple ruby only.
1623 # http://www.whatwg.org/html/text-level-semantics.html#the-ruby-element
1628 'rt' => $common, #array_merge( $common, array( 'rbspan' ) ),
1631 # MathML root element, where used for extensions
1632 # 'title' may not be 100% valid here; it's XHTML
1633 # http://www.w3.org/TR/REC-MathML/
1634 'math' => array( 'class', 'style', 'id', 'title' ),
1636 # HTML 5 section 4.6
1639 # HTML5 elements, defined by:
1640 # http://www.whatwg.org/html/
1641 'data' => array_merge( $common, array( 'value' ) ),
1642 'time' => array_merge( $common, array( 'datetime' ) ),
1645 // meta and link are only permitted by removeHTMLtags when Microdata
1646 // is enabled so we don't bother adding a conditional to hide these
1647 // Also meta and link are only valid in WikiText as Microdata elements
1648 // (ie: validateTag rejects tags missing the attributes needed for Microdata)
1649 // So we don't bother including $common attributes that have no purpose.
1650 'meta' => array( 'itemprop', 'content' ),
1651 'link' => array( 'itemprop', 'href' ),
1654 $staticInitialised = $globalContext;
1660 * Take a fragment of (potentially invalid) HTML and return
1661 * a version with any tags removed, encoded as plain text.
1663 * Warning: this return value must be further escaped for literal
1664 * inclusion in HTML output as of 1.10!
1666 * @param string $text HTML fragment
1669 static function stripAllTags( $text ) {
1671 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
1673 # Normalize &entities and whitespace
1674 $text = self
::decodeCharReferences( $text );
1675 $text = self
::normalizeWhitespace( $text );
1681 * Hack up a private DOCTYPE with HTML's standard entity declarations.
1682 * PHP 4 seemed to know these if you gave it an HTML doctype, but
1685 * Use for passing XHTML fragments to PHP's XML parsing functions
1689 static function hackDocType() {
1690 $out = "<!DOCTYPE html [\n";
1691 foreach ( self
::$htmlEntities as $entity => $codepoint ) {
1692 $out .= "<!ENTITY $entity \"&#$codepoint;\">";
1699 * @param $url string
1700 * @return mixed|string
1702 static function cleanUrl( $url ) {
1703 # Normalize any HTML entities in input. They will be
1704 # re-escaped by makeExternalLink().
1705 $url = Sanitizer
::decodeCharReferences( $url );
1707 # Escape any control characters introduced by the above step
1708 $url = preg_replace_callback( '/[\][<>"\\x00-\\x20\\x7F\|]/',
1709 array( __CLASS__
, 'cleanUrlCallback' ), $url );
1711 # Validate hostname portion
1713 if ( preg_match( '!^([^:]+:)(//[^/]+)?(.*)$!iD', $url, $matches ) ) {
1714 list( /* $whole */, $protocol, $host, $rest ) = $matches;
1716 // Characters that will be ignored in IDNs.
1717 // http://tools.ietf.org/html/3454#section-3.1
1718 // Strip them before further processing so blacklists and such work.
1720 \\s| # general whitespace
1721 \xc2\xad| # 00ad SOFT HYPHEN
1722 \xe1\xa0\x86| # 1806 MONGOLIAN TODO SOFT HYPHEN
1723 \xe2\x80\x8b| # 200b ZERO WIDTH SPACE
1724 \xe2\x81\xa0| # 2060 WORD JOINER
1725 \xef\xbb\xbf| # feff ZERO WIDTH NO-BREAK SPACE
1726 \xcd\x8f| # 034f COMBINING GRAPHEME JOINER
1727 \xe1\xa0\x8b| # 180b MONGOLIAN FREE VARIATION SELECTOR ONE
1728 \xe1\xa0\x8c| # 180c MONGOLIAN FREE VARIATION SELECTOR TWO
1729 \xe1\xa0\x8d| # 180d MONGOLIAN FREE VARIATION SELECTOR THREE
1730 \xe2\x80\x8c| # 200c ZERO WIDTH NON-JOINER
1731 \xe2\x80\x8d| # 200d ZERO WIDTH JOINER
1732 [\xef\xb8\x80-\xef\xb8\x8f] # fe00-fe0f VARIATION SELECTOR-1-16
1735 $host = preg_replace( $strip, '', $host );
1737 // @todo FIXME: Validate hostnames here
1739 return $protocol . $host . $rest;
1746 * @param $matches array
1749 static function cleanUrlCallback( $matches ) {
1750 return urlencode( $matches[0] );
1754 * Does a string look like an e-mail address?
1756 * This validates an email address using an HTML5 specification found at:
1757 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
1758 * Which as of 2011-01-24 says:
1760 * A valid e-mail address is a string that matches the ABNF production
1761 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
1762 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
1765 * This function is an implementation of the specification as requested in
1768 * Client-side forms will use the same standard validation rules via JS or
1769 * HTML 5 validation; additional restrictions can be enforced server-side
1770 * by extensions via the 'isValidEmailAddr' hook.
1772 * Note that this validation doesn't 100% match RFC 2822, but is believed
1773 * to be liberal enough for wide use. Some invalid addresses will still
1774 * pass validation here.
1778 * @param string $addr E-mail address
1781 public static function validateEmail( $addr ) {
1783 if ( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
1787 // Please note strings below are enclosed in brackets [], this make the
1788 // hyphen "-" a range indicator. Hence it is double backslashed below.
1790 $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~";
1791 $rfc1034_ldh_str = "a-z0-9\\-";
1793 $HTML5_email_regexp = "/
1795 [$rfc5322_atext\\.]+ # user part which is liberal :p
1797 [$rfc1034_ldh_str]+ # First domain part
1798 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
1800 /ix"; // case Insensitive, eXtended
1802 return (bool) preg_match( $HTML5_email_regexp, $addr );