3 * kses 0.2.2 - HTML/XHTML filter that only allows some elements and attributes
4 * Copyright (C) 2002, 2003, 2005 Ulf Harnhammar
6 * This program is free software and open source software; you can redistribute
7 * it and/or modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation; either version 2 of the License,
9 * or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 * http://www.gnu.org/licenses/gpl.html
21 * [kses strips evil scripts!]
23 * Added wp_ prefix to avoid conflicts with existing kses users
26 * @copyright (C) 2002, 2003, 2005
27 * @author Ulf Harnhammar <http://advogato.org/person/metaur/>
35 * You can override this in a plugin.
39 if ( ! defined( 'CUSTOM_TAGS' ) )
40 define( 'CUSTOM_TAGS', false );
42 if ( ! CUSTOM_TAGS ) {
44 * Kses global for default allowable HTML tags.
46 * Can be override by using CUSTOM_TAGS constant.
48 * @global array $allowedposttags
51 $allowedposttags = array(
88 'blockquote' => array(
151 'fieldset' => array(),
160 'figcaption' => array(
184 'accept-charset' => true,
340 'cellpadding' => true,
341 'cellspacing' => true,
440 * Kses allowed HTML elements.
442 * @global array $allowedtags
445 $allowedtags = array(
457 'blockquote' => array(
469 'em' => array (), 'i' => array (),
470 // 'ins' => array('datetime' => array(), 'cite' => array()),
485 $allowedentitynames = array(
486 'nbsp', 'iexcl', 'cent', 'pound', 'curren', 'yen',
487 'brvbar', 'sect', 'uml', 'copy', 'ordf', 'laquo',
488 'not', 'shy', 'reg', 'macr', 'deg', 'plusmn',
489 'acute', 'micro', 'para', 'middot', 'cedil', 'ordm',
490 'raquo', 'iquest', 'Agrave', 'Aacute', 'Acirc', 'Atilde',
491 'Auml', 'Aring', 'AElig', 'Ccedil', 'Egrave', 'Eacute',
492 'Ecirc', 'Euml', 'Igrave', 'Iacute', 'Icirc', 'Iuml',
493 'ETH', 'Ntilde', 'Ograve', 'Oacute', 'Ocirc', 'Otilde',
494 'Ouml', 'times', 'Oslash', 'Ugrave', 'Uacute', 'Ucirc',
495 'Uuml', 'Yacute', 'THORN', 'szlig', 'agrave', 'aacute',
496 'acirc', 'atilde', 'auml', 'aring', 'aelig', 'ccedil',
497 'egrave', 'eacute', 'ecirc', 'euml', 'igrave', 'iacute',
498 'icirc', 'iuml', 'eth', 'ntilde', 'ograve', 'oacute',
499 'ocirc', 'otilde', 'ouml', 'divide', 'oslash', 'ugrave',
500 'uacute', 'ucirc', 'uuml', 'yacute', 'thorn', 'yuml',
501 'quot', 'amp', 'lt', 'gt', 'apos', 'OElig',
502 'oelig', 'Scaron', 'scaron', 'Yuml', 'circ', 'tilde',
503 'ensp', 'emsp', 'thinsp', 'zwnj', 'zwj', 'lrm',
504 'rlm', 'ndash', 'mdash', 'lsquo', 'rsquo', 'sbquo',
505 'ldquo', 'rdquo', 'bdquo', 'dagger', 'Dagger', 'permil',
506 'lsaquo', 'rsaquo', 'euro', 'fnof', 'Alpha', 'Beta',
507 'Gamma', 'Delta', 'Epsilon', 'Zeta', 'Eta', 'Theta',
508 'Iota', 'Kappa', 'Lambda', 'Mu', 'Nu', 'Xi',
509 'Omicron', 'Pi', 'Rho', 'Sigma', 'Tau', 'Upsilon',
510 'Phi', 'Chi', 'Psi', 'Omega', 'alpha', 'beta',
511 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta',
512 'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi',
513 'omicron', 'pi', 'rho', 'sigmaf', 'sigma', 'tau',
514 'upsilon', 'phi', 'chi', 'psi', 'omega', 'thetasym',
515 'upsih', 'piv', 'bull', 'hellip', 'prime', 'Prime',
516 'oline', 'frasl', 'weierp', 'image', 'real', 'trade',
517 'alefsym', 'larr', 'uarr', 'rarr', 'darr', 'harr',
518 'crarr', 'lArr', 'uArr', 'rArr', 'dArr', 'hArr',
519 'forall', 'part', 'exist', 'empty', 'nabla', 'isin',
520 'notin', 'ni', 'prod', 'sum', 'minus', 'lowast',
521 'radic', 'prop', 'infin', 'ang', 'and', 'or',
522 'cap', 'cup', 'int', 'sim', 'cong', 'asymp',
523 'ne', 'equiv', 'le', 'ge', 'sub', 'sup',
524 'nsub', 'sube', 'supe', 'oplus', 'otimes', 'perp',
525 'sdot', 'lceil', 'rceil', 'lfloor', 'rfloor', 'lang',
526 'rang', 'loz', 'spades', 'clubs', 'hearts', 'diams',
531 * Filters content and keeps only allowable HTML elements.
533 * This function makes sure that only the allowed HTML element names, attribute
534 * names and attribute values plus only sane HTML entities will occur in
535 * $string. You have to remove any slashes from PHP's magic quotes before you
536 * call this function.
538 * The default allowed protocols are 'http', 'https', 'ftp', 'mailto', 'news',
539 * 'irc', 'gopher', 'nntp', 'feed', 'telnet, 'mms', 'rtsp' and 'svn'. This
540 * covers all common link protocols, except for 'javascript' which should not
541 * be allowed for untrusted users.
545 * @param string $string Content to filter through kses
546 * @param array $allowed_html List of allowed HTML elements
547 * @param array $allowed_protocols Optional. Allowed protocol in links.
548 * @return string Filtered content with only allowed HTML elements
550 function wp_kses($string, $allowed_html, $allowed_protocols = array ()) {
551 if ( empty( $allowed_protocols ) )
552 $allowed_protocols = wp_allowed_protocols();
553 $string = wp_kses_no_null($string);
554 $string = wp_kses_js_entities($string);
555 $string = wp_kses_normalize_entities($string);
556 $allowed_html_fixed = wp_kses_array_lc($allowed_html);
557 $string = wp_kses_hook($string, $allowed_html_fixed, $allowed_protocols); // WP changed the order of these funcs and added args to wp_kses_hook
558 return wp_kses_split($string, $allowed_html_fixed, $allowed_protocols);
562 * You add any kses hooks here.
564 * There is currently only one kses WordPress hook and it is called here. All
565 * parameters are passed to the hooks and expected to receive a string.
569 * @param string $string Content to filter through kses
570 * @param array $allowed_html List of allowed HTML elements
571 * @param array $allowed_protocols Allowed protocol in links
572 * @return string Filtered content through 'pre_kses' hook
574 function wp_kses_hook($string, $allowed_html, $allowed_protocols) {
575 $string = apply_filters('pre_kses', $string, $allowed_html, $allowed_protocols);
580 * This function returns kses' version number.
584 * @return string KSES Version Number
586 function wp_kses_version() {
591 * Searches for HTML tags, no matter how malformed.
593 * It also matches stray ">" characters.
597 * @param string $string Content to filter
598 * @param array $allowed_html Allowed HTML elements
599 * @param array $allowed_protocols Allowed protocols to keep
600 * @return string Content with fixed HTML tags
602 function wp_kses_split($string, $allowed_html, $allowed_protocols) {
603 global $pass_allowed_html, $pass_allowed_protocols;
604 $pass_allowed_html = $allowed_html;
605 $pass_allowed_protocols = $allowed_protocols;
606 return preg_replace_callback( '%(<!--.*?(-->|$))|(<[^>]*(>|$)|>)%', '_wp_kses_split_callback', $string );
610 * Callback for wp_kses_split.
615 function _wp_kses_split_callback( $match ) {
616 global $pass_allowed_html, $pass_allowed_protocols;
617 return wp_kses_split2( $match[0], $pass_allowed_html, $pass_allowed_protocols );
621 * Callback for wp_kses_split for fixing malformed HTML tags.
623 * This function does a lot of work. It rejects some very malformed things like
624 * <:::>. It returns an empty string, if the element isn't allowed (look ma, no
625 * strip_tags()!). Otherwise it splits the tag into an element and an attribute
628 * After the tag is split into an element and an attribute list, it is run
629 * through another filter which will remove illegal attributes and once that is
630 * completed, will be returned.
634 * @uses wp_kses_attr()
636 * @param string $string Content to filter
637 * @param array $allowed_html Allowed HTML elements
638 * @param array $allowed_protocols Allowed protocols to keep
639 * @return string Fixed HTML element
641 function wp_kses_split2($string, $allowed_html, $allowed_protocols) {
642 $string = wp_kses_stripslashes($string);
644 if (substr($string, 0, 1) != '<')
646 # It matched a ">" character
648 if ( '<!--' == substr( $string, 0, 4 ) ) {
649 $string = str_replace( array('<!--', '-->'), '', $string );
650 while ( $string != ($newstring = wp_kses($string, $allowed_html, $allowed_protocols)) )
651 $string = $newstring;
654 // prevent multiple dashes in comments
655 $string = preg_replace('/--+/', '-', $string);
656 // prevent three dashes closing a comment
657 $string = preg_replace('/-$/', '', $string);
658 return "<!--{$string}-->";
660 # Allow HTML comments
662 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches))
664 # It's seriously malformed
666 $slash = trim($matches[1]);
668 $attrlist = $matches[3];
670 if ( ! isset($allowed_html[strtolower($elem)]) )
672 # They are using a not allowed HTML element
676 # No attributes are allowed for closing elements
678 return wp_kses_attr( $elem, $attrlist, $allowed_html, $allowed_protocols );
682 * Removes all attributes, if none are allowed for this element.
684 * If some are allowed it calls wp_kses_hair() to split them further, and then
685 * it builds up new HTML code from the data that kses_hair() returns. It also
686 * removes "<" and ">" characters, if there are any left. One more thing it does
687 * is to check if the tag has a closing XHTML slash, and if it does, it puts one
688 * in the returned code as well.
692 * @param string $element HTML element/tag
693 * @param string $attr HTML attributes from HTML element to closing HTML element tag
694 * @param array $allowed_html Allowed HTML elements
695 * @param array $allowed_protocols Allowed protocols to keep
696 * @return string Sanitized HTML element
698 function wp_kses_attr($element, $attr, $allowed_html, $allowed_protocols) {
699 # Is there a closing XHTML slash at the end of the attributes?
702 if (preg_match('%\s*/\s*$%', $attr))
705 # Are any attributes allowed at all for this element?
706 if ( ! isset($allowed_html[strtolower($element)]) || count($allowed_html[strtolower($element)]) == 0 )
707 return "<$element$xhtml_slash>";
710 $attrarr = wp_kses_hair($attr, $allowed_protocols);
712 # Go through $attrarr, and save the allowed attributes for this element
716 $allowed_attr = $allowed_html[strtolower($element)];
717 foreach ($attrarr as $arreach) {
718 if ( ! isset( $allowed_attr[strtolower($arreach['name'])] ) )
719 continue; # the attribute is not allowed
721 $current = $allowed_attr[strtolower($arreach['name'])];
722 if ( $current == '' )
723 continue; # the attribute is not allowed
725 if ( strtolower( $arreach['name'] ) == 'style' ) {
726 $orig_value = $arreach['value'];
727 $value = safecss_filter_attr( $orig_value );
729 if ( empty( $value ) )
732 $arreach['value'] = $value;
733 $arreach['whole'] = str_replace( $orig_value, $value, $arreach['whole'] );
736 if ( ! is_array($current) ) {
737 $attr2 .= ' '.$arreach['whole'];
738 # there are no checks
741 # there are some checks
743 foreach ($current as $currkey => $currval) {
744 if ( ! wp_kses_check_attr_val($arreach['value'], $arreach['vless'], $currkey, $currval) ) {
751 $attr2 .= ' '.$arreach['whole']; # it passed them
752 } # if !is_array($current)
755 # Remove any "<" or ">" characters
756 $attr2 = preg_replace('/[<>]/', '', $attr2);
758 return "<$element$attr2$xhtml_slash>";
762 * Builds an attribute list from string containing attributes.
764 * This function does a lot of work. It parses an attribute list into an array
765 * with attribute data, and tries to do the right thing even if it gets weird
766 * input. It will add quotes around attribute values that don't have any quotes
767 * or apostrophes around them, to make it easier to produce HTML code that will
768 * conform to W3C's HTML specification. It will also remove bad URL protocols
769 * from attribute values. It also reduces duplicate attributes by using the
770 * attribute defined first (foo='bar' foo='baz' will result in foo='bar').
774 * @param string $attr Attribute list from HTML element to closing HTML element tag
775 * @param array $allowed_protocols Allowed protocols to keep
776 * @return array List of attributes after parsing
778 function wp_kses_hair($attr, $allowed_protocols) {
782 $uris = array('xmlns', 'profile', 'href', 'src', 'cite', 'classid', 'codebase', 'data', 'usemap', 'longdesc', 'action');
784 # Loop through the whole attribute list
786 while (strlen($attr) != 0) {
787 $working = 0; # Was the last operation successful?
790 case 0 : # attribute name, href for instance
792 if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
793 $attrname = $match[1];
794 $working = $mode = 1;
795 $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
800 case 1 : # equals sign or valueless ("selected")
802 if (preg_match('/^\s*=\s*/', $attr)) # equals sign
806 $attr = preg_replace('/^\s*=\s*/', '', $attr);
810 if (preg_match('/^\s+/', $attr)) # valueless
814 if(false === array_key_exists($attrname, $attrarr)) {
815 $attrarr[$attrname] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y');
817 $attr = preg_replace('/^\s+/', '', $attr);
822 case 2 : # attribute value, a URL after href= for instance
824 if (preg_match('%^"([^"]*)"(\s+|/?$)%', $attr, $match))
827 $thisval = $match[1];
828 if ( in_array(strtolower($attrname), $uris) )
829 $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
831 if(false === array_key_exists($attrname, $attrarr)) {
832 $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n');
836 $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
840 if (preg_match("%^'([^']*)'(\s+|/?$)%", $attr, $match))
843 $thisval = $match[1];
844 if ( in_array(strtolower($attrname), $uris) )
845 $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
847 if(false === array_key_exists($attrname, $attrarr)) {
848 $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname='$thisval'", 'vless' => 'n');
852 $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
856 if (preg_match("%^([^\s\"']+)(\s+|/?$)%", $attr, $match))
859 $thisval = $match[1];
860 if ( in_array(strtolower($attrname), $uris) )
861 $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
863 if(false === array_key_exists($attrname, $attrarr)) {
864 $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n');
866 # We add quotes to conform to W3C's HTML spec.
869 $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
875 if ($working == 0) # not well formed, remove and try again
877 $attr = wp_kses_html_error($attr);
882 if ($mode == 1 && false === array_key_exists($attrname, $attrarr))
883 # special case, for when the attribute list ends with a valueless
884 # attribute like "selected"
885 $attrarr[$attrname] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y');
891 * Performs different checks for attribute values.
893 * The currently implemented checks are "maxlen", "minlen", "maxval", "minval"
898 * @param string $value Attribute value
899 * @param string $vless Whether the value is valueless. Use 'y' or 'n'
900 * @param string $checkname What $checkvalue is checking for.
901 * @param mixed $checkvalue What constraint the value should pass
902 * @return bool Whether check passes
904 function wp_kses_check_attr_val($value, $vless, $checkname, $checkvalue) {
907 switch (strtolower($checkname)) {
909 # The maxlen check makes sure that the attribute value has a length not
910 # greater than the given value. This can be used to avoid Buffer Overflows
911 # in WWW clients and various Internet servers.
913 if (strlen($value) > $checkvalue)
918 # The minlen check makes sure that the attribute value has a length not
919 # smaller than the given value.
921 if (strlen($value) < $checkvalue)
926 # The maxval check does two things: it checks that the attribute value is
927 # an integer from 0 and up, without an excessive amount of zeroes or
928 # whitespace (to avoid Buffer Overflows). It also checks that the attribute
929 # value is not greater than the given value.
930 # This check can be used to avoid Denial of Service attacks.
932 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
934 if ($value > $checkvalue)
939 # The minval check makes sure that the attribute value is a positive integer,
940 # and that it is not smaller than the given value.
942 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
944 if ($value < $checkvalue)
949 # The valueless check makes sure if the attribute has a value
950 # (like <a href="blah">) or not (<option selected>). If the given value
951 # is a "y" or a "Y", the attribute must not have a value.
952 # If the given value is an "n" or an "N", the attribute must have one.
954 if (strtolower($checkvalue) != $vless)
963 * Sanitize string from bad protocols.
965 * This function removes all non-allowed protocols from the beginning of
966 * $string. It ignores whitespace and the case of the letters, and it does
967 * understand HTML entities. It does its work in a while loop, so it won't be
968 * fooled by a string like "javascript:javascript:alert(57)".
972 * @param string $string Content to filter bad protocols from
973 * @param array $allowed_protocols Allowed protocols to keep
974 * @return string Filtered content
976 function wp_kses_bad_protocol($string, $allowed_protocols) {
977 $string = wp_kses_no_null($string);
981 $original_string = $string;
982 $string = wp_kses_bad_protocol_once($string, $allowed_protocols);
983 } while ( $original_string != $string && ++$iterations < 6 );
985 if ( $original_string != $string )
992 * Removes any null characters in $string.
996 * @param string $string
999 function wp_kses_no_null($string) {
1000 $string = preg_replace('/\0+/', '', $string);
1001 $string = preg_replace('/(\\\\0)+/', '', $string);
1007 * Strips slashes from in front of quotes.
1009 * This function changes the character sequence \" to just ". It leaves all
1010 * other slashes alone. It's really weird, but the quoting from
1011 * preg_replace(//e) seems to require this.
1015 * @param string $string String to strip slashes
1016 * @return string Fixed string with quoted slashes
1018 function wp_kses_stripslashes($string) {
1019 return preg_replace('%\\\\"%', '"', $string);
1023 * Goes through an array and changes the keys to all lower case.
1027 * @param array $inarray Unfiltered array
1028 * @return array Fixed array with all lowercase keys
1030 function wp_kses_array_lc($inarray) {
1031 $outarray = array ();
1033 foreach ( (array) $inarray as $inkey => $inval) {
1034 $outkey = strtolower($inkey);
1035 $outarray[$outkey] = array ();
1037 foreach ( (array) $inval as $inkey2 => $inval2) {
1038 $outkey2 = strtolower($inkey2);
1039 $outarray[$outkey][$outkey2] = $inval2;
1041 } # foreach $inarray
1047 * Removes the HTML JavaScript entities found in early versions of Netscape 4.
1051 * @param string $string
1054 function wp_kses_js_entities($string) {
1055 return preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
1059 * Handles parsing errors in wp_kses_hair().
1061 * The general plan is to remove everything to and including some whitespace,
1062 * but it deals with quotes and apostrophes as well.
1066 * @param string $string
1069 function wp_kses_html_error($string) {
1070 return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string);
1074 * Sanitizes content from bad protocols and other characters.
1076 * This function searches for URL protocols at the beginning of $string, while
1077 * handling whitespace and HTML entities.
1081 * @param string $string Content to check for bad protocols
1082 * @param string $allowed_protocols Allowed protocols
1083 * @return string Sanitized content
1085 function wp_kses_bad_protocol_once($string, $allowed_protocols, $count = 1 ) {
1086 $string2 = preg_split( '/:|�*58;|�*3a;/i', $string, 2 );
1087 if ( isset($string2[1]) && ! preg_match('%/\?%', $string2[0]) ) {
1088 $string = trim( $string2[1] );
1089 $protocol = wp_kses_bad_protocol_once2( $string2[0], $allowed_protocols );
1090 if ( 'feed:' == $protocol ) {
1093 $string = wp_kses_bad_protocol_once( $string, $allowed_protocols, ++$count );
1094 if ( empty( $string ) )
1097 $string = $protocol . $string;
1104 * Callback for wp_kses_bad_protocol_once() regular expression.
1106 * This function processes URL protocols, checks to see if they're in the
1107 * whitelist or not, and returns different data depending on the answer.
1112 * @param string $string URI scheme to check against the whitelist
1113 * @param string $allowed_protocols Allowed protocols
1114 * @return string Sanitized content
1116 function wp_kses_bad_protocol_once2( $string, $allowed_protocols ) {
1117 $string2 = wp_kses_decode_entities($string);
1118 $string2 = preg_replace('/\s/', '', $string2);
1119 $string2 = wp_kses_no_null($string2);
1120 $string2 = strtolower($string2);
1123 foreach ( (array) $allowed_protocols as $one_protocol )
1124 if ( strtolower($one_protocol) == $string2 ) {
1136 * Converts and fixes HTML entities.
1138 * This function normalizes HTML entities. It will convert "AT&T" to the correct
1139 * "AT&T", ":" to ":", "&#XYZZY;" to "&#XYZZY;" and so on.
1143 * @param string $string Content to normalize entities
1144 * @return string Content with normalized entities
1146 function wp_kses_normalize_entities($string) {
1147 # Disarm all entities by converting & to &
1149 $string = str_replace('&', '&', $string);
1151 # Change back the allowed entities in our entity whitelist
1153 $string = preg_replace_callback('/&([A-Za-z]{2,8});/', 'wp_kses_named_entities', $string);
1154 $string = preg_replace_callback('/&#(0*[0-9]{1,7});/', 'wp_kses_normalize_entities2', $string);
1155 $string = preg_replace_callback('/&#[Xx](0*[0-9A-Fa-f]{1,6});/', 'wp_kses_normalize_entities3', $string);
1161 * Callback for wp_kses_normalize_entities() regular expression.
1163 * This function only accepts valid named entity references, which are finite,
1164 * case-sensitive, and highly scrutinized by HTML and XML validators.
1168 * @param array $matches preg_replace_callback() matches array
1169 * @return string Correctly encoded entity
1171 function wp_kses_named_entities($matches) {
1172 global $allowedentitynames;
1174 if ( empty($matches[1]) )
1178 return ( ( ! in_array($i, $allowedentitynames) ) ? "&$i;" : "&$i;" );
1182 * Callback for wp_kses_normalize_entities() regular expression.
1184 * This function helps wp_kses_normalize_entities() to only accept 16-bit values
1185 * and nothing more for &#number; entities.
1190 * @param array $matches preg_replace_callback() matches array
1191 * @return string Correctly encoded entity
1193 function wp_kses_normalize_entities2($matches) {
1194 if ( empty($matches[1]) )
1198 if (valid_unicode($i)) {
1199 $i = str_pad(ltrim($i,'0'), 3, '0', STR_PAD_LEFT);
1209 * Callback for wp_kses_normalize_entities() for regular expression.
1211 * This function helps wp_kses_normalize_entities() to only accept valid Unicode
1212 * numeric entities in hex form.
1216 * @param array $matches preg_replace_callback() matches array
1217 * @return string Correctly encoded entity
1219 function wp_kses_normalize_entities3($matches) {
1220 if ( empty($matches[1]) )
1223 $hexchars = $matches[1];
1224 return ( ( ! valid_unicode(hexdec($hexchars)) ) ? "&#x$hexchars;" : '&#x'.ltrim($hexchars,'0').';' );
1228 * Helper function to determine if a Unicode value is valid.
1230 * @param int $i Unicode value
1231 * @return bool True if the value was a valid Unicode number
1233 function valid_unicode($i) {
1234 return ( $i == 0x9 || $i == 0xa || $i == 0xd ||
1235 ($i >= 0x20 && $i <= 0xd7ff) ||
1236 ($i >= 0xe000 && $i <= 0xfffd) ||
1237 ($i >= 0x10000 && $i <= 0x10ffff) );
1241 * Convert all entities to their character counterparts.
1243 * This function decodes numeric HTML entities (A and A). It doesn't do
1244 * anything with other entities like ä, but we don't need them in the URL
1245 * protocol whitelisting system anyway.
1249 * @param string $string Content to change entities
1250 * @return string Content after decoded entities
1252 function wp_kses_decode_entities($string) {
1253 $string = preg_replace_callback('/&#([0-9]+);/', '_wp_kses_decode_entities_chr', $string);
1254 $string = preg_replace_callback('/&#[Xx]([0-9A-Fa-f]+);/', '_wp_kses_decode_entities_chr_hexdec', $string);
1260 * Regex callback for wp_kses_decode_entities()
1262 * @param array $match preg match
1265 function _wp_kses_decode_entities_chr( $match ) {
1266 return chr( $match[1] );
1270 * Regex callback for wp_kses_decode_entities()
1272 * @param array $match preg match
1275 function _wp_kses_decode_entities_chr_hexdec( $match ) {
1276 return chr( hexdec( $match[1] ) );
1280 * Sanitize content with allowed HTML Kses rules.
1283 * @uses $allowedtags
1285 * @param string $data Content to filter, expected to be escaped with slashes
1286 * @return string Filtered content
1288 function wp_filter_kses($data) {
1289 global $allowedtags;
1290 return addslashes( wp_kses(stripslashes( $data ), $allowedtags) );
1294 * Sanitize content with allowed HTML Kses rules.
1297 * @uses $allowedtags
1299 * @param string $data Content to filter, expected to not be escaped
1300 * @return string Filtered content
1302 function wp_kses_data($data) {
1303 global $allowedtags;
1304 return wp_kses( $data , $allowedtags );
1308 * Sanitize content for allowed HTML tags for post content.
1310 * Post content refers to the page contents of the 'post' type and not $_POST
1314 * @uses $allowedposttags
1316 * @param string $data Post content to filter, expected to be escaped with slashes
1317 * @return string Filtered post content with allowed HTML tags and attributes intact.
1319 function wp_filter_post_kses($data) {
1320 global $allowedposttags;
1321 return addslashes ( wp_kses(stripslashes( $data ), $allowedposttags) );
1325 * Sanitize content for allowed HTML tags for post content.
1327 * Post content refers to the page contents of the 'post' type and not $_POST
1331 * @uses $allowedposttags
1333 * @param string $data Post content to filter
1334 * @return string Filtered post content with allowed HTML tags and attributes intact.
1336 function wp_kses_post($data) {
1337 global $allowedposttags;
1338 return wp_kses( $data , $allowedposttags );
1342 * Strips all of the HTML in the content.
1346 * @param string $data Content to strip all HTML from
1347 * @return string Filtered content without any HTML
1349 function wp_filter_nohtml_kses($data) {
1350 return addslashes ( wp_kses(stripslashes( $data ), array()) );
1354 * Adds all Kses input form content filters.
1356 * All hooks have default priority. The wp_filter_kses() function is added to
1357 * the 'pre_comment_content' and 'title_save_pre' hooks.
1359 * The wp_filter_post_kses() function is added to the 'content_save_pre',
1360 * 'excerpt_save_pre', and 'content_filtered_save_pre' hooks.
1363 * @uses add_filter() See description for what functions are added to what hooks.
1365 function kses_init_filters() {
1367 add_filter('title_save_pre', 'wp_filter_kses');
1369 // Comment filtering
1370 if ( current_user_can( 'unfiltered_html' ) )
1371 add_filter( 'pre_comment_content', 'wp_filter_post_kses' );
1373 add_filter( 'pre_comment_content', 'wp_filter_kses' );
1376 add_filter('content_save_pre', 'wp_filter_post_kses');
1377 add_filter('excerpt_save_pre', 'wp_filter_post_kses');
1378 add_filter('content_filtered_save_pre', 'wp_filter_post_kses');
1382 * Removes all Kses input form content filters.
1384 * A quick procedural method to removing all of the filters that kses uses for
1385 * content in WordPress Loop.
1387 * Does not remove the kses_init() function from 'init' hook (priority is
1388 * default). Also does not remove kses_init() function from 'set_current_user'
1389 * hook (priority is also default).
1393 function kses_remove_filters() {
1395 remove_filter('title_save_pre', 'wp_filter_kses');
1397 // Comment filtering
1398 remove_filter( 'pre_comment_content', 'wp_filter_post_kses' );
1399 remove_filter( 'pre_comment_content', 'wp_filter_kses' );
1402 remove_filter('content_save_pre', 'wp_filter_post_kses');
1403 remove_filter('excerpt_save_pre', 'wp_filter_post_kses');
1404 remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');
1408 * Sets up most of the Kses filters for input form content.
1410 * If you remove the kses_init() function from 'init' hook and
1411 * 'set_current_user' (priority is default), then none of the Kses filter hooks
1414 * First removes all of the Kses filters in case the current user does not need
1415 * to have Kses filter the content. If the user does not have unfiltered_html
1416 * capability, then Kses filters are added.
1418 * @uses kses_remove_filters() Removes the Kses filters
1419 * @uses kses_init_filters() Adds the Kses filters back if the user
1420 * does not have unfiltered HTML capability.
1423 function kses_init() {
1424 kses_remove_filters();
1426 if (current_user_can('unfiltered_html') == false)
1427 kses_init_filters();
1430 add_action('init', 'kses_init');
1431 add_action('set_current_user', 'kses_init');
1438 function safecss_filter_attr( $css, $deprecated = '' ) {
1439 if ( !empty( $deprecated ) )
1440 _deprecated_argument( __FUNCTION__, '2.8.1' ); // Never implemented
1442 $css = wp_kses_no_null($css);
1443 $css = str_replace(array("\n","\r","\t"), '', $css);
1445 if ( preg_match( '%[\\(&=}]|/\*%', $css ) ) // remove any inline css containing \ ( & } = or comments
1448 $css_array = explode( ';', trim( $css ) );
1449 $allowed_attr = apply_filters( 'safe_style_css', array( 'text-align', 'margin', 'color', 'float',
1450 'border', 'background', 'background-color', 'border-bottom', 'border-bottom-color',
1451 'border-bottom-style', 'border-bottom-width', 'border-collapse', 'border-color', 'border-left',
1452 'border-left-color', 'border-left-style', 'border-left-width', 'border-right', 'border-right-color',
1453 'border-right-style', 'border-right-width', 'border-spacing', 'border-style', 'border-top',
1454 'border-top-color', 'border-top-style', 'border-top-width', 'border-width', 'caption-side',
1455 'clear', 'cursor', 'direction', 'font', 'font-family', 'font-size', 'font-style',
1456 'font-variant', 'font-weight', 'height', 'letter-spacing', 'line-height', 'margin-bottom',
1457 'margin-left', 'margin-right', 'margin-top', 'overflow', 'padding', 'padding-bottom',
1458 'padding-left', 'padding-right', 'padding-top', 'text-decoration', 'text-indent', 'vertical-align',
1461 if ( empty($allowed_attr) )
1465 foreach ( $css_array as $css_item ) {
1466 if ( $css_item == '' )
1468 $css_item = trim( $css_item );
1470 if ( strpos( $css_item, ':' ) === false ) {
1473 $parts = explode( ':', $css_item );
1474 if ( in_array( trim( $parts[0] ), $allowed_attr ) )