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.
37 * The wp_kses_allowed_html filter is more powerful and supplies context.
38 * CUSTOM_TAGS is not recommended and should be considered deprecated.
40 * @see wp_kses_allowed_html()
44 if ( ! defined( 'CUSTOM_TAGS' ) )
45 define( 'CUSTOM_TAGS', false );
47 // Ensure that these variables are added to the global namespace
48 // (e.g. if using namespaces / autoload in the current PHP environment).
49 global $allowedposttags, $allowedtags, $allowedentitynames;
51 if ( ! CUSTOM_TAGS ) {
53 * Kses global for default allowable HTML tags.
55 * Can be override by using CUSTOM_TAGS constant.
57 * @global array $allowedposttags
60 $allowedposttags = array(
101 'blockquote' => array(
159 'fieldset' => array(),
166 'figcaption' => array(
186 'accept-charset' => true,
310 'cellpadding' => true,
311 'cellspacing' => true,
414 * Kses allowed HTML elements.
416 * @global array $allowedtags
419 $allowedtags = array(
431 'blockquote' => array(
449 $allowedentitynames = array(
450 'nbsp', 'iexcl', 'cent', 'pound', 'curren', 'yen',
451 'brvbar', 'sect', 'uml', 'copy', 'ordf', 'laquo',
452 'not', 'shy', 'reg', 'macr', 'deg', 'plusmn',
453 'acute', 'micro', 'para', 'middot', 'cedil', 'ordm',
454 'raquo', 'iquest', 'Agrave', 'Aacute', 'Acirc', 'Atilde',
455 'Auml', 'Aring', 'AElig', 'Ccedil', 'Egrave', 'Eacute',
456 'Ecirc', 'Euml', 'Igrave', 'Iacute', 'Icirc', 'Iuml',
457 'ETH', 'Ntilde', 'Ograve', 'Oacute', 'Ocirc', 'Otilde',
458 'Ouml', 'times', 'Oslash', 'Ugrave', 'Uacute', 'Ucirc',
459 'Uuml', 'Yacute', 'THORN', 'szlig', 'agrave', 'aacute',
460 'acirc', 'atilde', 'auml', 'aring', 'aelig', 'ccedil',
461 'egrave', 'eacute', 'ecirc', 'euml', 'igrave', 'iacute',
462 'icirc', 'iuml', 'eth', 'ntilde', 'ograve', 'oacute',
463 'ocirc', 'otilde', 'ouml', 'divide', 'oslash', 'ugrave',
464 'uacute', 'ucirc', 'uuml', 'yacute', 'thorn', 'yuml',
465 'quot', 'amp', 'lt', 'gt', 'apos', 'OElig',
466 'oelig', 'Scaron', 'scaron', 'Yuml', 'circ', 'tilde',
467 'ensp', 'emsp', 'thinsp', 'zwnj', 'zwj', 'lrm',
468 'rlm', 'ndash', 'mdash', 'lsquo', 'rsquo', 'sbquo',
469 'ldquo', 'rdquo', 'bdquo', 'dagger', 'Dagger', 'permil',
470 'lsaquo', 'rsaquo', 'euro', 'fnof', 'Alpha', 'Beta',
471 'Gamma', 'Delta', 'Epsilon', 'Zeta', 'Eta', 'Theta',
472 'Iota', 'Kappa', 'Lambda', 'Mu', 'Nu', 'Xi',
473 'Omicron', 'Pi', 'Rho', 'Sigma', 'Tau', 'Upsilon',
474 'Phi', 'Chi', 'Psi', 'Omega', 'alpha', 'beta',
475 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta',
476 'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi',
477 'omicron', 'pi', 'rho', 'sigmaf', 'sigma', 'tau',
478 'upsilon', 'phi', 'chi', 'psi', 'omega', 'thetasym',
479 'upsih', 'piv', 'bull', 'hellip', 'prime', 'Prime',
480 'oline', 'frasl', 'weierp', 'image', 'real', 'trade',
481 'alefsym', 'larr', 'uarr', 'rarr', 'darr', 'harr',
482 'crarr', 'lArr', 'uArr', 'rArr', 'dArr', 'hArr',
483 'forall', 'part', 'exist', 'empty', 'nabla', 'isin',
484 'notin', 'ni', 'prod', 'sum', 'minus', 'lowast',
485 'radic', 'prop', 'infin', 'ang', 'and', 'or',
486 'cap', 'cup', 'int', 'sim', 'cong', 'asymp',
487 'ne', 'equiv', 'le', 'ge', 'sub', 'sup',
488 'nsub', 'sube', 'supe', 'oplus', 'otimes', 'perp',
489 'sdot', 'lceil', 'rceil', 'lfloor', 'rfloor', 'lang',
490 'rang', 'loz', 'spades', 'clubs', 'hearts', 'diams',
491 'sup1', 'sup2', 'sup3', 'frac14', 'frac12', 'frac34',
495 $allowedposttags = array_map( '_wp_add_global_attributes', $allowedposttags );
497 $allowedtags = wp_kses_array_lc( $allowedtags );
498 $allowedposttags = wp_kses_array_lc( $allowedposttags );
502 * Filters content and keeps only allowable HTML elements.
504 * This function makes sure that only the allowed HTML element names, attribute
505 * names and attribute values plus only sane HTML entities will occur in
506 * $string. You have to remove any slashes from PHP's magic quotes before you
507 * call this function.
509 * The default allowed protocols are 'http', 'https', 'ftp', 'mailto', 'news',
510 * 'irc', 'gopher', 'nntp', 'feed', 'telnet, 'mms', 'rtsp' and 'svn'. This
511 * covers all common link protocols, except for 'javascript' which should not
512 * be allowed for untrusted users.
516 * @param string $string Content to filter through kses
517 * @param array $allowed_html List of allowed HTML elements
518 * @param array $allowed_protocols Optional. Allowed protocol in links.
519 * @return string Filtered content with only allowed HTML elements
521 function wp_kses( $string, $allowed_html, $allowed_protocols = array() ) {
522 if ( empty( $allowed_protocols ) )
523 $allowed_protocols = wp_allowed_protocols();
524 $string = wp_kses_no_null($string);
525 $string = wp_kses_js_entities($string);
526 $string = wp_kses_normalize_entities($string);
527 $string = wp_kses_hook($string, $allowed_html, $allowed_protocols); // WP changed the order of these funcs and added args to wp_kses_hook
528 return wp_kses_split($string, $allowed_html, $allowed_protocols);
532 * Return a list of allowed tags and attributes for a given context.
536 * @param string $context The context for which to retrieve tags. Allowed values are
537 * post | strip | data | entities or the name of a field filter such as pre_user_description.
538 * @return array List of allowed tags and their allowed attributes.
540 function wp_kses_allowed_html( $context = '' ) {
541 global $allowedposttags, $allowedtags, $allowedentitynames;
543 if ( is_array( $context ) ) {
545 * Filter HTML elements allowed for a given context.
549 * @param string $tags Allowed tags, attributes, and/or entities.
550 * @param string $context Context to judge allowed tags by. Allowed values are 'post',
551 * 'data', 'strip', 'entities', 'explicit', or the name of a filter.
553 return apply_filters( 'wp_kses_allowed_html', $context, 'explicit' );
556 switch ( $context ) {
558 /** This filter is documented in wp-includes/kses.php */
559 return apply_filters( 'wp_kses_allowed_html', $allowedposttags, $context );
561 case 'user_description':
562 case 'pre_user_description':
563 $tags = $allowedtags;
564 $tags['a']['rel'] = true;
565 /** This filter is documented in wp-includes/kses.php */
566 return apply_filters( 'wp_kses_allowed_html', $tags, $context );
569 /** This filter is documented in wp-includes/kses.php */
570 return apply_filters( 'wp_kses_allowed_html', array(), $context );
573 /** This filter is documented in wp-includes/kses.php */
574 return apply_filters( 'wp_kses_allowed_html', $allowedentitynames, $context);
578 /** This filter is documented in wp-includes/kses.php */
579 return apply_filters( 'wp_kses_allowed_html', $allowedtags, $context );
584 * You add any kses hooks here.
586 * There is currently only one kses WordPress hook and it is called here. All
587 * parameters are passed to the hooks and expected to receive a string.
591 * @param string $string Content to filter through kses
592 * @param array $allowed_html List of allowed HTML elements
593 * @param array $allowed_protocols Allowed protocol in links
594 * @return string Filtered content through 'pre_kses' hook
596 function wp_kses_hook( $string, $allowed_html, $allowed_protocols ) {
598 * Filter content to be run through kses.
602 * @param string $string Content to run through kses.
603 * @param array $allowed_html Allowed HTML elements.
604 * @param array $allowed_protocols Allowed protocol in links.
606 $string = apply_filters( 'pre_kses', $string, $allowed_html, $allowed_protocols );
611 * This function returns kses' version number.
615 * @return string KSES Version Number
617 function wp_kses_version() {
622 * Searches for HTML tags, no matter how malformed.
624 * It also matches stray ">" characters.
628 * @param string $string Content to filter
629 * @param array $allowed_html Allowed HTML elements
630 * @param array $allowed_protocols Allowed protocols to keep
631 * @return string Content with fixed HTML tags
633 function wp_kses_split( $string, $allowed_html, $allowed_protocols ) {
634 global $pass_allowed_html, $pass_allowed_protocols;
635 $pass_allowed_html = $allowed_html;
636 $pass_allowed_protocols = $allowed_protocols;
637 return preg_replace_callback( '%(<!--.*?(-->|$))|(<[^>]*(>|$)|>)%', '_wp_kses_split_callback', $string );
641 * Callback for wp_kses_split.
646 function _wp_kses_split_callback( $match ) {
647 global $pass_allowed_html, $pass_allowed_protocols;
648 return wp_kses_split2( $match[0], $pass_allowed_html, $pass_allowed_protocols );
652 * Callback for wp_kses_split for fixing malformed HTML tags.
654 * This function does a lot of work. It rejects some very malformed things like
655 * <:::>. It returns an empty string, if the element isn't allowed (look ma, no
656 * strip_tags()!). Otherwise it splits the tag into an element and an attribute
659 * After the tag is split into an element and an attribute list, it is run
660 * through another filter which will remove illegal attributes and once that is
661 * completed, will be returned.
666 * @param string $string Content to filter
667 * @param array $allowed_html Allowed HTML elements
668 * @param array $allowed_protocols Allowed protocols to keep
669 * @return string Fixed HTML element
671 function wp_kses_split2($string, $allowed_html, $allowed_protocols) {
672 $string = wp_kses_stripslashes($string);
674 if (substr($string, 0, 1) != '<')
676 // It matched a ">" character
678 if ( '<!--' == substr( $string, 0, 4 ) ) {
679 $string = str_replace( array('<!--', '-->'), '', $string );
680 while ( $string != ($newstring = wp_kses($string, $allowed_html, $allowed_protocols)) )
681 $string = $newstring;
684 // prevent multiple dashes in comments
685 $string = preg_replace('/--+/', '-', $string);
686 // prevent three dashes closing a comment
687 $string = preg_replace('/-$/', '', $string);
688 return "<!--{$string}-->";
690 // Allow HTML comments
692 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches))
694 // It's seriously malformed
696 $slash = trim($matches[1]);
698 $attrlist = $matches[3];
700 if ( ! is_array( $allowed_html ) )
701 $allowed_html = wp_kses_allowed_html( $allowed_html );
703 if ( ! isset($allowed_html[strtolower($elem)]) )
705 // They are using a not allowed HTML element
709 // No attributes are allowed for closing elements
711 return wp_kses_attr( $elem, $attrlist, $allowed_html, $allowed_protocols );
715 * Removes all attributes, if none are allowed for this element.
717 * If some are allowed it calls wp_kses_hair() to split them further, and then
718 * it builds up new HTML code from the data that kses_hair() returns. It also
719 * removes "<" and ">" characters, if there are any left. One more thing it does
720 * is to check if the tag has a closing XHTML slash, and if it does, it puts one
721 * in the returned code as well.
725 * @param string $element HTML element/tag
726 * @param string $attr HTML attributes from HTML element to closing HTML element tag
727 * @param array $allowed_html Allowed HTML elements
728 * @param array $allowed_protocols Allowed protocols to keep
729 * @return string Sanitized HTML element
731 function wp_kses_attr($element, $attr, $allowed_html, $allowed_protocols) {
732 // Is there a closing XHTML slash at the end of the attributes?
734 if ( ! is_array( $allowed_html ) )
735 $allowed_html = wp_kses_allowed_html( $allowed_html );
738 if (preg_match('%\s*/\s*$%', $attr))
741 // Are any attributes allowed at all for this element?
742 if ( ! isset($allowed_html[strtolower($element)]) || count($allowed_html[strtolower($element)]) == 0 )
743 return "<$element$xhtml_slash>";
746 $attrarr = wp_kses_hair($attr, $allowed_protocols);
748 // Go through $attrarr, and save the allowed attributes for this element
752 $allowed_attr = $allowed_html[strtolower($element)];
753 foreach ($attrarr as $arreach) {
754 if ( ! isset( $allowed_attr[strtolower($arreach['name'])] ) )
755 continue; // the attribute is not allowed
757 $current = $allowed_attr[strtolower($arreach['name'])];
758 if ( $current == '' )
759 continue; // the attribute is not allowed
761 if ( strtolower( $arreach['name'] ) == 'style' ) {
762 $orig_value = $arreach['value'];
763 $value = safecss_filter_attr( $orig_value );
765 if ( empty( $value ) )
768 $arreach['value'] = $value;
769 $arreach['whole'] = str_replace( $orig_value, $value, $arreach['whole'] );
772 if ( ! is_array($current) ) {
773 $attr2 .= ' '.$arreach['whole'];
774 // there are no checks
777 // there are some checks
779 foreach ($current as $currkey => $currval) {
780 if ( ! wp_kses_check_attr_val($arreach['value'], $arreach['vless'], $currkey, $currval) ) {
787 $attr2 .= ' '.$arreach['whole']; // it passed them
788 } // if !is_array($current)
791 // Remove any "<" or ">" characters
792 $attr2 = preg_replace('/[<>]/', '', $attr2);
794 return "<$element$attr2$xhtml_slash>";
798 * Builds an attribute list from string containing attributes.
800 * This function does a lot of work. It parses an attribute list into an array
801 * with attribute data, and tries to do the right thing even if it gets weird
802 * input. It will add quotes around attribute values that don't have any quotes
803 * or apostrophes around them, to make it easier to produce HTML code that will
804 * conform to W3C's HTML specification. It will also remove bad URL protocols
805 * from attribute values. It also reduces duplicate attributes by using the
806 * attribute defined first (foo='bar' foo='baz' will result in foo='bar').
810 * @param string $attr Attribute list from HTML element to closing HTML element tag
811 * @param array $allowed_protocols Allowed protocols to keep
812 * @return array List of attributes after parsing
814 function wp_kses_hair($attr, $allowed_protocols) {
818 $uris = array('xmlns', 'profile', 'href', 'src', 'cite', 'classid', 'codebase', 'data', 'usemap', 'longdesc', 'action');
820 // Loop through the whole attribute list
822 while (strlen($attr) != 0) {
823 $working = 0; // Was the last operation successful?
826 case 0 : // attribute name, href for instance
828 if ( preg_match('/^([-a-zA-Z:]+)/', $attr, $match ) ) {
829 $attrname = $match[1];
830 $working = $mode = 1;
831 $attr = preg_replace( '/^[-a-zA-Z:]+/', '', $attr );
836 case 1 : // equals sign or valueless ("selected")
838 if (preg_match('/^\s*=\s*/', $attr)) // equals sign
842 $attr = preg_replace('/^\s*=\s*/', '', $attr);
846 if (preg_match('/^\s+/', $attr)) // valueless
850 if(false === array_key_exists($attrname, $attrarr)) {
851 $attrarr[$attrname] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y');
853 $attr = preg_replace('/^\s+/', '', $attr);
858 case 2 : // attribute value, a URL after href= for instance
860 if (preg_match('%^"([^"]*)"(\s+|/?$)%', $attr, $match))
863 $thisval = $match[1];
864 if ( in_array(strtolower($attrname), $uris) )
865 $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
867 if(false === array_key_exists($attrname, $attrarr)) {
868 $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n');
872 $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
876 if (preg_match("%^'([^']*)'(\s+|/?$)%", $attr, $match))
879 $thisval = $match[1];
880 if ( in_array(strtolower($attrname), $uris) )
881 $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
883 if(false === array_key_exists($attrname, $attrarr)) {
884 $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname='$thisval'", 'vless' => 'n');
888 $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
892 if (preg_match("%^([^\s\"']+)(\s+|/?$)%", $attr, $match))
895 $thisval = $match[1];
896 if ( in_array(strtolower($attrname), $uris) )
897 $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
899 if(false === array_key_exists($attrname, $attrarr)) {
900 $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n');
902 // We add quotes to conform to W3C's HTML spec.
905 $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
911 if ($working == 0) // not well formed, remove and try again
913 $attr = wp_kses_html_error($attr);
918 if ($mode == 1 && false === array_key_exists($attrname, $attrarr))
919 // special case, for when the attribute list ends with a valueless
920 // attribute like "selected"
921 $attrarr[$attrname] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y');
927 * Performs different checks for attribute values.
929 * The currently implemented checks are "maxlen", "minlen", "maxval", "minval"
934 * @param string $value Attribute value
935 * @param string $vless Whether the value is valueless. Use 'y' or 'n'
936 * @param string $checkname What $checkvalue is checking for.
937 * @param mixed $checkvalue What constraint the value should pass
938 * @return bool Whether check passes
940 function wp_kses_check_attr_val($value, $vless, $checkname, $checkvalue) {
943 switch (strtolower($checkname)) {
945 // The maxlen check makes sure that the attribute value has a length not
946 // greater than the given value. This can be used to avoid Buffer Overflows
947 // in WWW clients and various Internet servers.
949 if (strlen($value) > $checkvalue)
954 // The minlen check makes sure that the attribute value has a length not
955 // smaller than the given value.
957 if (strlen($value) < $checkvalue)
962 // The maxval check does two things: it checks that the attribute value is
963 // an integer from 0 and up, without an excessive amount of zeroes or
964 // whitespace (to avoid Buffer Overflows). It also checks that the attribute
965 // value is not greater than the given value.
966 // This check can be used to avoid Denial of Service attacks.
968 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
970 if ($value > $checkvalue)
975 // The minval check makes sure that the attribute value is a positive integer,
976 // and that it is not smaller than the given value.
978 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
980 if ($value < $checkvalue)
985 // The valueless check makes sure if the attribute has a value
986 // (like <a href="blah">) or not (<option selected>). If the given value
987 // is a "y" or a "Y", the attribute must not have a value.
988 // If the given value is an "n" or an "N", the attribute must have one.
990 if (strtolower($checkvalue) != $vless)
999 * Sanitize string from bad protocols.
1001 * This function removes all non-allowed protocols from the beginning of
1002 * $string. It ignores whitespace and the case of the letters, and it does
1003 * understand HTML entities. It does its work in a while loop, so it won't be
1004 * fooled by a string like "javascript:javascript:alert(57)".
1008 * @param string $string Content to filter bad protocols from
1009 * @param array $allowed_protocols Allowed protocols to keep
1010 * @return string Filtered content
1012 function wp_kses_bad_protocol($string, $allowed_protocols) {
1013 $string = wp_kses_no_null($string);
1017 $original_string = $string;
1018 $string = wp_kses_bad_protocol_once($string, $allowed_protocols);
1019 } while ( $original_string != $string && ++$iterations < 6 );
1021 if ( $original_string != $string )
1028 * Removes any invalid control characters in $string.
1030 * Also removes any instance of the '\0' string.
1034 * @param string $string
1037 function wp_kses_no_null($string) {
1038 $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $string);
1039 $string = preg_replace('/(\\\\0)+/', '', $string);
1045 * Strips slashes from in front of quotes.
1047 * This function changes the character sequence \" to just ". It leaves all
1048 * other slashes alone. It's really weird, but the quoting from
1049 * preg_replace(//e) seems to require this.
1053 * @param string $string String to strip slashes
1054 * @return string Fixed string with quoted slashes
1056 function wp_kses_stripslashes($string) {
1057 return preg_replace('%\\\\"%', '"', $string);
1061 * Goes through an array and changes the keys to all lower case.
1065 * @param array $inarray Unfiltered array
1066 * @return array Fixed array with all lowercase keys
1068 function wp_kses_array_lc($inarray) {
1069 $outarray = array ();
1071 foreach ( (array) $inarray as $inkey => $inval) {
1072 $outkey = strtolower($inkey);
1073 $outarray[$outkey] = array ();
1075 foreach ( (array) $inval as $inkey2 => $inval2) {
1076 $outkey2 = strtolower($inkey2);
1077 $outarray[$outkey][$outkey2] = $inval2;
1079 } // foreach $inarray
1085 * Removes the HTML JavaScript entities found in early versions of Netscape 4.
1089 * @param string $string
1092 function wp_kses_js_entities($string) {
1093 return preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
1097 * Handles parsing errors in wp_kses_hair().
1099 * The general plan is to remove everything to and including some whitespace,
1100 * but it deals with quotes and apostrophes as well.
1104 * @param string $string
1107 function wp_kses_html_error($string) {
1108 return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string);
1112 * Sanitizes content from bad protocols and other characters.
1114 * This function searches for URL protocols at the beginning of $string, while
1115 * handling whitespace and HTML entities.
1119 * @param string $string Content to check for bad protocols
1120 * @param string $allowed_protocols Allowed protocols
1121 * @return string Sanitized content
1123 function wp_kses_bad_protocol_once($string, $allowed_protocols, $count = 1 ) {
1124 $string2 = preg_split( '/:|�*58;|�*3a;/i', $string, 2 );
1125 if ( isset($string2[1]) && ! preg_match('%/\?%', $string2[0]) ) {
1126 $string = trim( $string2[1] );
1127 $protocol = wp_kses_bad_protocol_once2( $string2[0], $allowed_protocols );
1128 if ( 'feed:' == $protocol ) {
1131 $string = wp_kses_bad_protocol_once( $string, $allowed_protocols, ++$count );
1132 if ( empty( $string ) )
1135 $string = $protocol . $string;
1142 * Callback for wp_kses_bad_protocol_once() regular expression.
1144 * This function processes URL protocols, checks to see if they're in the
1145 * whitelist or not, and returns different data depending on the answer.
1150 * @param string $string URI scheme to check against the whitelist
1151 * @param string $allowed_protocols Allowed protocols
1152 * @return string Sanitized content
1154 function wp_kses_bad_protocol_once2( $string, $allowed_protocols ) {
1155 $string2 = wp_kses_decode_entities($string);
1156 $string2 = preg_replace('/\s/', '', $string2);
1157 $string2 = wp_kses_no_null($string2);
1158 $string2 = strtolower($string2);
1161 foreach ( (array) $allowed_protocols as $one_protocol )
1162 if ( strtolower($one_protocol) == $string2 ) {
1174 * Converts and fixes HTML entities.
1176 * This function normalizes HTML entities. It will convert `AT&T` to the correct
1177 * `AT&T`, `:` to `:`, `&#XYZZY;` to `&#XYZZY;` and so on.
1181 * @param string $string Content to normalize entities
1182 * @return string Content with normalized entities
1184 function wp_kses_normalize_entities($string) {
1185 // Disarm all entities by converting & to &
1187 $string = str_replace('&', '&', $string);
1189 // Change back the allowed entities in our entity whitelist
1191 $string = preg_replace_callback('/&([A-Za-z]{2,8}[0-9]{0,2});/', 'wp_kses_named_entities', $string);
1192 $string = preg_replace_callback('/&#(0*[0-9]{1,7});/', 'wp_kses_normalize_entities2', $string);
1193 $string = preg_replace_callback('/&#[Xx](0*[0-9A-Fa-f]{1,6});/', 'wp_kses_normalize_entities3', $string);
1199 * Callback for wp_kses_normalize_entities() regular expression.
1201 * This function only accepts valid named entity references, which are finite,
1202 * case-sensitive, and highly scrutinized by HTML and XML validators.
1206 * @param array $matches preg_replace_callback() matches array
1207 * @return string Correctly encoded entity
1209 function wp_kses_named_entities($matches) {
1210 global $allowedentitynames;
1212 if ( empty($matches[1]) )
1216 return ( ( ! in_array($i, $allowedentitynames) ) ? "&$i;" : "&$i;" );
1220 * Callback for wp_kses_normalize_entities() regular expression.
1222 * This function helps {@see wp_kses_normalize_entities()} to only accept 16-bit
1223 * values and nothing more for `&#number;` entities.
1228 * @param array $matches preg_replace_callback() matches array
1229 * @return string Correctly encoded entity
1231 function wp_kses_normalize_entities2($matches) {
1232 if ( empty($matches[1]) )
1236 if (valid_unicode($i)) {
1237 $i = str_pad(ltrim($i,'0'), 3, '0', STR_PAD_LEFT);
1247 * Callback for wp_kses_normalize_entities() for regular expression.
1249 * This function helps wp_kses_normalize_entities() to only accept valid Unicode
1250 * numeric entities in hex form.
1254 * @param array $matches preg_replace_callback() matches array
1255 * @return string Correctly encoded entity
1257 function wp_kses_normalize_entities3($matches) {
1258 if ( empty($matches[1]) )
1261 $hexchars = $matches[1];
1262 return ( ( ! valid_unicode(hexdec($hexchars)) ) ? "&#x$hexchars;" : '&#x'.ltrim($hexchars,'0').';' );
1266 * Helper function to determine if a Unicode value is valid.
1268 * @param int $i Unicode value
1269 * @return bool True if the value was a valid Unicode number
1271 function valid_unicode($i) {
1272 return ( $i == 0x9 || $i == 0xa || $i == 0xd ||
1273 ($i >= 0x20 && $i <= 0xd7ff) ||
1274 ($i >= 0xe000 && $i <= 0xfffd) ||
1275 ($i >= 0x10000 && $i <= 0x10ffff) );
1279 * Convert all entities to their character counterparts.
1281 * This function decodes numeric HTML entities (`A` and `A`).
1282 * It doesn't do anything with other entities like ä, but we don't
1283 * need them in the URL protocol whitelisting system anyway.
1287 * @param string $string Content to change entities
1288 * @return string Content after decoded entities
1290 function wp_kses_decode_entities($string) {
1291 $string = preg_replace_callback('/&#([0-9]+);/', '_wp_kses_decode_entities_chr', $string);
1292 $string = preg_replace_callback('/&#[Xx]([0-9A-Fa-f]+);/', '_wp_kses_decode_entities_chr_hexdec', $string);
1298 * Regex callback for wp_kses_decode_entities()
1300 * @param array $match preg match
1303 function _wp_kses_decode_entities_chr( $match ) {
1304 return chr( $match[1] );
1308 * Regex callback for wp_kses_decode_entities()
1310 * @param array $match preg match
1313 function _wp_kses_decode_entities_chr_hexdec( $match ) {
1314 return chr( hexdec( $match[1] ) );
1318 * Sanitize content with allowed HTML Kses rules.
1322 * @param string $data Content to filter, expected to be escaped with slashes
1323 * @return string Filtered content
1325 function wp_filter_kses( $data ) {
1326 return addslashes( wp_kses( stripslashes( $data ), current_filter() ) );
1330 * Sanitize content with allowed HTML Kses rules.
1334 * @param string $data Content to filter, expected to not be escaped
1335 * @return string Filtered content
1337 function wp_kses_data( $data ) {
1338 return wp_kses( $data , current_filter() );
1342 * Sanitize content for allowed HTML tags for post content.
1344 * Post content refers to the page contents of the 'post' type and not $_POST
1349 * @param string $data Post content to filter, expected to be escaped with slashes
1350 * @return string Filtered post content with allowed HTML tags and attributes intact.
1352 function wp_filter_post_kses($data) {
1353 return addslashes ( wp_kses( stripslashes( $data ), 'post' ) );
1357 * Sanitize content for allowed HTML tags for post content.
1359 * Post content refers to the page contents of the 'post' type and not $_POST
1364 * @param string $data Post content to filter
1365 * @return string Filtered post content with allowed HTML tags and attributes intact.
1367 function wp_kses_post($data) {
1368 return wp_kses( $data , 'post' );
1372 * Strips all of the HTML in the content.
1376 * @param string $data Content to strip all HTML from
1377 * @return string Filtered content without any HTML
1379 function wp_filter_nohtml_kses( $data ) {
1380 return addslashes ( wp_kses( stripslashes( $data ), 'strip' ) );
1384 * Adds all Kses input form content filters.
1386 * All hooks have default priority. The wp_filter_kses() function is added to
1387 * the 'pre_comment_content' and 'title_save_pre' hooks.
1389 * The wp_filter_post_kses() function is added to the 'content_save_pre',
1390 * 'excerpt_save_pre', and 'content_filtered_save_pre' hooks.
1394 function kses_init_filters() {
1396 add_filter('title_save_pre', 'wp_filter_kses');
1398 // Comment filtering
1399 if ( current_user_can( 'unfiltered_html' ) )
1400 add_filter( 'pre_comment_content', 'wp_filter_post_kses' );
1402 add_filter( 'pre_comment_content', 'wp_filter_kses' );
1405 add_filter('content_save_pre', 'wp_filter_post_kses');
1406 add_filter('excerpt_save_pre', 'wp_filter_post_kses');
1407 add_filter('content_filtered_save_pre', 'wp_filter_post_kses');
1411 * Removes all Kses input form content filters.
1413 * A quick procedural method to removing all of the filters that kses uses for
1414 * content in WordPress Loop.
1416 * Does not remove the kses_init() function from 'init' hook (priority is
1417 * default). Also does not remove kses_init() function from 'set_current_user'
1418 * hook (priority is also default).
1422 function kses_remove_filters() {
1424 remove_filter('title_save_pre', 'wp_filter_kses');
1426 // Comment filtering
1427 remove_filter( 'pre_comment_content', 'wp_filter_post_kses' );
1428 remove_filter( 'pre_comment_content', 'wp_filter_kses' );
1431 remove_filter('content_save_pre', 'wp_filter_post_kses');
1432 remove_filter('excerpt_save_pre', 'wp_filter_post_kses');
1433 remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');
1437 * Sets up most of the Kses filters for input form content.
1439 * If you remove the kses_init() function from 'init' hook and
1440 * 'set_current_user' (priority is default), then none of the Kses filter hooks
1443 * First removes all of the Kses filters in case the current user does not need
1444 * to have Kses filter the content. If the user does not have unfiltered_html
1445 * capability, then Kses filters are added.
1449 function kses_init() {
1450 kses_remove_filters();
1452 if (current_user_can('unfiltered_html') == false)
1453 kses_init_filters();
1461 function safecss_filter_attr( $css, $deprecated = '' ) {
1462 if ( !empty( $deprecated ) )
1463 _deprecated_argument( __FUNCTION__, '2.8.1' ); // Never implemented
1465 $css = wp_kses_no_null($css);
1466 $css = str_replace(array("\n","\r","\t"), '', $css);
1468 if ( preg_match( '%[\\\\(&=}]|/\*%', $css ) ) // remove any inline css containing \ ( & } = or comments
1471 $css_array = explode( ';', trim( $css ) );
1474 * Filter list of allowed CSS attributes.
1478 * @param array $attr List of allowed CSS attributes.
1480 $allowed_attr = apply_filters( 'safe_style_css', array( 'text-align', 'margin', 'color', 'float',
1481 'border', 'background', 'background-color', 'border-bottom', 'border-bottom-color',
1482 'border-bottom-style', 'border-bottom-width', 'border-collapse', 'border-color', 'border-left',
1483 'border-left-color', 'border-left-style', 'border-left-width', 'border-right', 'border-right-color',
1484 'border-right-style', 'border-right-width', 'border-spacing', 'border-style', 'border-top',
1485 'border-top-color', 'border-top-style', 'border-top-width', 'border-width', 'caption-side',
1486 'clear', 'cursor', 'direction', 'font', 'font-family', 'font-size', 'font-style',
1487 'font-variant', 'font-weight', 'height', 'letter-spacing', 'line-height', 'margin-bottom',
1488 'margin-left', 'margin-right', 'margin-top', 'overflow', 'padding', 'padding-bottom',
1489 'padding-left', 'padding-right', 'padding-top', 'text-decoration', 'text-indent', 'vertical-align',
1492 if ( empty($allowed_attr) )
1496 foreach ( $css_array as $css_item ) {
1497 if ( $css_item == '' )
1499 $css_item = trim( $css_item );
1501 if ( strpos( $css_item, ':' ) === false ) {
1504 $parts = explode( ':', $css_item );
1505 if ( in_array( trim( $parts[0] ), $allowed_attr ) )
1519 * Helper function to add global attributes to a tag in the allowed html list.
1524 * @param array $value An array of attributes.
1525 * @return array The array of attributes with global attributes added.
1527 function _wp_add_global_attributes( $value ) {
1528 $global_attributes = array(
1536 if ( true === $value )
1539 if ( is_array( $value ) )
1540 return array_merge( $value, $global_attributes );