3 * HTML/XHTML filter that only allows some elements and attributes
5 * Added wp_ prefix to avoid conflicts with existing kses users
8 * @copyright (C) 2002, 2003, 2005
9 * @author Ulf Harnhammar <metaur@users.sourceforge.net>
15 * *** CONTACT INFORMATION ***
16 * E-mail: metaur at users dot sourceforge dot net
17 * Web page: http://sourceforge.net/projects/kses
18 * Paper mail: Ulf Harnhammar
23 * [kses strips evil scripts!]
27 * You can override this in your my-hacks.php file
28 * You can also override this in a plugin file. The
29 * my-hacks.php is deprecated in its usage.
33 if (!defined('CUSTOM_TAGS'))
34 define('CUSTOM_TAGS', false);
38 * Kses global for default allowable HTML tags
40 * Can be override by using CUSTOM_TAGS constant
41 * @global array $allowedposttags
44 $allowedposttags = array(
62 'blockquote' => array(
67 'xml:lang' => array()),
71 'disabled' => array (),
88 'charoff' => array (),
95 'datetime' => array ()),
103 'xml:lang' => array()),
107 'fieldset' => array(),
113 'action' => array (),
114 'accept' => array (),
115 'accept-charset' => array (),
116 'enctype' => array (),
117 'method' => array (),
119 'target' => array ()),
122 'class' => array ()),
125 'class' => array ()),
128 'class' => array ()),
131 'class' => array ()),
134 'class' => array ()),
137 'class' => array ()),
141 'noshade' => array (),
143 'width' => array ()),
148 'border' => array (),
150 'height' => array (),
151 'hspace' => array (),
152 'longdesc' => array (),
153 'vspace' => array (),
156 'width' => array ()),
158 'datetime' => array (),
164 'align' => array ()),
167 'class' => array ()),
174 'xml:lang' => array()),
177 'width' => array ()),
186 'title' => array ()),
193 'bgcolor' => array (),
194 'border' => array (),
195 'cellpadding' => array (),
196 'cellspacing' => array (),
202 'summary' => array (),
203 'width' => array ()),
207 'charoff' => array (),
208 'valign' => array ()),
213 'bgcolor' => array (),
215 'charoff' => array (),
217 'colspan' => array (),
219 'headers' => array (),
220 'height' => array (),
221 'nowrap' => array (),
222 'rowspan' => array (),
225 'valign' => array (),
226 'width' => array ()),
230 'disabled' => array (),
232 'readonly' => array ()),
237 'charoff' => array (),
238 'valign' => array ()),
243 'bgcolor' => array (),
245 'charoff' => array (),
247 'colspan' => array (),
248 'headers' => array (),
249 'height' => array (),
250 'nowrap' => array (),
251 'rowspan' => array (),
253 'valign' => array (),
254 'width' => array ()),
258 'charoff' => array (),
260 'valign' => array ()),
264 'bgcolor' => array (),
266 'charoff' => array (),
269 'valign' => array ()),
283 * Kses allowed HTML elements
285 * @global array $allowedtags
288 $allowedtags = array(
291 'title' => array ()),
293 'title' => array ()),
295 'title' => array ()),
297 'blockquote' => array(
303 'datetime' => array ()),
307 'em' => array (), 'i' => array (),
308 // 'ins' => array('datetime' => array(), 'cite' => array()),
324 * wp_kses() - Filters content and keeps only allowable HTML elements.
326 * This function makes sure that only the allowed HTML element names,
327 * attribute names and attribute values plus only sane HTML entities
328 * will occur in $string. You have to remove any slashes from PHP's
329 * magic quotes before you call this function.
331 * The default allowed protocols are 'http', 'https', 'ftp', 'mailto',
332 * 'news', 'irc', 'gopher', 'nntp', 'feed', and finally 'telnet. This
333 * covers all common link protocols, except for 'javascript' which
334 * should not be allowed for untrusted users.
338 * @param string $string Content to filter through kses
339 * @param array $allowed_html List of allowed HTML elements
340 * @param array $allowed_protocols Optional. Allowed protocol in links.
341 * @return string Filtered content with only allowed HTML elements
343 function wp_kses($string, $allowed_html, $allowed_protocols = array ('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet')) {
344 $string = wp_kses_no_null($string);
345 $string = wp_kses_js_entities($string);
346 $string = wp_kses_normalize_entities($string);
347 $allowed_html_fixed = wp_kses_array_lc($allowed_html);
348 $string = wp_kses_hook($string, $allowed_html_fixed, $allowed_protocols); // WP changed the order of these funcs and added args to wp_kses_hook
349 return wp_kses_split($string, $allowed_html_fixed, $allowed_protocols);
353 * wp_kses_hook() - You add any kses hooks here.
355 * There is currently only one kses WordPress hook and it is
356 * called here. All parameters are passed to the hooks and
357 * expected to recieve a string.
361 * @param string $string Content to filter through kses
362 * @param array $allowed_html List of allowed HTML elements
363 * @param array $allowed_protocols Allowed protocol in links
364 * @return string Filtered content through 'pre_kses' hook
366 function wp_kses_hook($string, $allowed_html, $allowed_protocols) {
367 $string = apply_filters('pre_kses', $string, $allowed_html, $allowed_protocols);
372 * wp_kses_version() - This function returns kses' version number.
376 * @return string Version Number
378 function wp_kses_version() {
383 * wp_kses_split() - Searches for HTML tags, no matter how malformed
385 * It also matches stray ">" characters.
389 * @param string $string Content to filter
390 * @param array $allowed_html Allowed HTML elements
391 * @param array $allowed_protocols Allowed protocols to keep
392 * @return string Content with fixed HTML tags
394 function wp_kses_split($string, $allowed_html, $allowed_protocols) {
395 return preg_replace('%((<!--.*?(-->|$))|(<[^>]*(>|$)|>))%e',
396 "wp_kses_split2('\\1', \$allowed_html, ".'$allowed_protocols)', $string);
400 * wp_kses_split2() - Callback for wp_kses_split for fixing malformed HTML tags
402 * This function does a lot of work. It rejects some very malformed things
403 * like <:::>. It returns an empty string, if the element isn't allowed (look
404 * ma, no strip_tags()!). Otherwise it splits the tag into an element and an
407 * After the tag is split into an element and an attribute list, it is run
408 * through another filter which will remove illegal attributes and once
409 * that is completed, will be returned.
412 * @uses wp_kses_attr()
414 * @param string $string Content to filter
415 * @param array $allowed_html Allowed HTML elements
416 * @param array $allowed_protocols Allowed protocols to keep
417 * @return string Fixed HTML element
419 function wp_kses_split2($string, $allowed_html, $allowed_protocols) {
420 $string = wp_kses_stripslashes($string);
422 if (substr($string, 0, 1) != '<')
424 # It matched a ">" character
426 if (preg_match('%^<!--(.*?)(-->)?$%', $string, $matches)) {
427 $string = str_replace(array('<!--', '-->'), '', $matches[1]);
428 while ( $string != $newstring = wp_kses($string, $allowed_html, $allowed_protocols) )
429 $string = $newstring;
432 return "<!--{$string}-->";
434 # Allow HTML comments
436 if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches))
438 # It's seriously malformed
440 $slash = trim($matches[1]);
442 $attrlist = $matches[3];
444 if (!@isset($allowed_html[strtolower($elem)]))
446 # They are using a not allowed HTML element
449 return "<$slash$elem>";
450 # No attributes are allowed for closing elements
452 return wp_kses_attr("$slash$elem", $attrlist, $allowed_html, $allowed_protocols);
456 * wp_kses_attr() - Removes all attributes, if none are allowed for this element
458 * If some are allowed it calls wp_kses_hair() to split them further, and then
459 * it builds up new HTML code from the data that kses_hair() returns. It also
460 * removes "<" and ">" characters, if there are any left. One more thing it
461 * does is to check if the tag has a closing XHTML slash, and if it does, it
462 * puts one in the returned code as well.
466 * @param string $element HTML element/tag
467 * @param string $attr HTML attributes from HTML element to closing HTML element tag
468 * @param array $allowed_html Allowed HTML elements
469 * @param array $allowed_protocols Allowed protocols to keep
470 * @return string Sanitized HTML element
472 function wp_kses_attr($element, $attr, $allowed_html, $allowed_protocols) {
473 # Is there a closing XHTML slash at the end of the attributes?
476 if (preg_match('%\s/\s*$%', $attr))
479 # Are any attributes allowed at all for this element?
481 if (@ count($allowed_html[strtolower($element)]) == 0)
482 return "<$element$xhtml_slash>";
486 $attrarr = wp_kses_hair($attr, $allowed_protocols);
488 # Go through $attrarr, and save the allowed attributes for this element
493 foreach ($attrarr as $arreach) {
494 if (!@ isset ($allowed_html[strtolower($element)][strtolower($arreach['name'])]))
495 continue; # the attribute is not allowed
497 $current = $allowed_html[strtolower($element)][strtolower($arreach['name'])];
499 continue; # the attribute is not allowed
501 if (!is_array($current))
502 $attr2 .= ' '.$arreach['whole'];
503 # there are no checks
506 # there are some checks
508 foreach ($current as $currkey => $currval)
509 if (!wp_kses_check_attr_val($arreach['value'], $arreach['vless'], $currkey, $currval)) {
515 $attr2 .= ' '.$arreach['whole']; # it passed them
516 } # if !is_array($current)
519 # Remove any "<" or ">" characters
521 $attr2 = preg_replace('/[<>]/', '', $attr2);
523 return "<$element$attr2$xhtml_slash>";
527 * wp_kses_hair() - Builds an attribute list from string containing attributes.
529 * This function does a lot of work. It parses an attribute list into an array
530 * with attribute data, and tries to do the right thing even if it gets weird
531 * input. It will add quotes around attribute values that don't have any quotes
532 * or apostrophes around them, to make it easier to produce HTML code that will
533 * conform to W3C's HTML specification. It will also remove bad URL protocols
534 * from attribute values.
538 * @param string $attr Attribute list from HTML element to closing HTML element tag
539 * @param array $allowed_protocols Allowed protocols to keep
540 * @return array List of attributes after parsing
542 function wp_kses_hair($attr, $allowed_protocols) {
547 # Loop through the whole attribute list
549 while (strlen($attr) != 0) {
550 $working = 0; # Was the last operation successful?
553 case 0 : # attribute name, href for instance
555 if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
556 $attrname = $match[1];
557 $working = $mode = 1;
558 $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
563 case 1 : # equals sign or valueless ("selected")
565 if (preg_match('/^\s*=\s*/', $attr)) # equals sign
569 $attr = preg_replace('/^\s*=\s*/', '', $attr);
573 if (preg_match('/^\s+/', $attr)) # valueless
577 $attrarr[] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y');
578 $attr = preg_replace('/^\s+/', '', $attr);
583 case 2 : # attribute value, a URL after href= for instance
585 if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match))
588 $thisval = wp_kses_bad_protocol($match[1], $allowed_protocols);
590 $attrarr[] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n');
593 $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
597 if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match))
600 $thisval = wp_kses_bad_protocol($match[1], $allowed_protocols);
602 $attrarr[] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname='$thisval'", 'vless' => 'n');
605 $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
609 if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match))
612 $thisval = wp_kses_bad_protocol($match[1], $allowed_protocols);
614 $attrarr[] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n');
615 # We add quotes to conform to W3C's HTML spec.
618 $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
624 if ($working == 0) # not well formed, remove and try again
626 $attr = wp_kses_html_error($attr);
632 # special case, for when the attribute list ends with a valueless
633 # attribute like "selected"
634 $attrarr[] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y');
640 * wp_kses_check_attr_val() - Performs different checks for attribute values.
642 * The currently implemented checks are "maxlen", "minlen", "maxval", "minval"
643 * and "valueless" with even more checks to come soon.
647 * @param string $value Attribute value
648 * @param string $vless Whether the value is valueless or not. Use 'y' or 'n'
649 * @param string $checkname What $checkvalue is checking for.
650 * @param mixed $checkvalue What constraint the value should pass
651 * @return bool Whether check passes (true) or not (false)
653 function wp_kses_check_attr_val($value, $vless, $checkname, $checkvalue) {
656 switch (strtolower($checkname)) {
658 # The maxlen check makes sure that the attribute value has a length not
659 # greater than the given value. This can be used to avoid Buffer Overflows
660 # in WWW clients and various Internet servers.
662 if (strlen($value) > $checkvalue)
667 # The minlen check makes sure that the attribute value has a length not
668 # smaller than the given value.
670 if (strlen($value) < $checkvalue)
675 # The maxval check does two things: it checks that the attribute value is
676 # an integer from 0 and up, without an excessive amount of zeroes or
677 # whitespace (to avoid Buffer Overflows). It also checks that the attribute
678 # value is not greater than the given value.
679 # This check can be used to avoid Denial of Service attacks.
681 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
683 if ($value > $checkvalue)
688 # The minval check checks that the attribute value is a positive integer,
689 # and that it is not smaller than the given value.
691 if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
693 if ($value < $checkvalue)
698 # The valueless check checks if the attribute has a value
699 # (like <a href="blah">) or not (<option selected>). If the given value
700 # is a "y" or a "Y", the attribute must not have a value.
701 # If the given value is an "n" or an "N", the attribute must have one.
703 if (strtolower($checkvalue) != $vless)
712 * wp_kses_bad_protocol() - Sanitize string from bad protocols
714 * This function removes all non-allowed protocols from the beginning
715 * of $string. It ignores whitespace and the case of the letters, and
716 * it does understand HTML entities. It does its work in a while loop,
717 * so it won't be fooled by a string like "javascript:javascript:alert(57)".
721 * @param string $string Content to filter bad protocols from
722 * @param array $allowed_protocols Allowed protocols to keep
723 * @return string Filtered content
725 function wp_kses_bad_protocol($string, $allowed_protocols) {
726 $string = wp_kses_no_null($string);
727 $string = preg_replace('/\xad+/', '', $string); # deals with Opera "feature"
728 $string2 = $string.'a';
730 while ($string != $string2) {
732 $string = wp_kses_bad_protocol_once($string, $allowed_protocols);
739 * wp_kses_no_null() - Removes any NULL characters in $string.
743 * @param string $string
746 function wp_kses_no_null($string) {
747 $string = preg_replace('/\0+/', '', $string);
748 $string = preg_replace('/(\\\\0)+/', '', $string);
754 * wp_kses_stripslashes() - Strips slashes from in front of quotes
756 * This function changes the character sequence \" to just "
757 * It leaves all other slashes alone. It's really weird, but the
758 * quoting from preg_replace(//e) seems to require this.
762 * @param string $string String to strip slashes
763 * @return string Fixed strings with quoted slashes
765 function wp_kses_stripslashes($string) {
766 return preg_replace('%\\\\"%', '"', $string);
770 * wp_kses_array_lc() - Goes through an array and changes the keys to all lower case.
774 * @param array $inarray Unfiltered array
775 * @return array Fixed array with all lowercase keys
777 function wp_kses_array_lc($inarray) {
778 $outarray = array ();
780 foreach ($inarray as $inkey => $inval) {
781 $outkey = strtolower($inkey);
782 $outarray[$outkey] = array ();
784 foreach ($inval as $inkey2 => $inval2) {
785 $outkey2 = strtolower($inkey2);
786 $outarray[$outkey][$outkey2] = $inval2;
794 * wp_kses_js_entities() - Removes the HTML JavaScript entities found in early versions of Netscape 4.
798 * @param string $string
801 function wp_kses_js_entities($string) {
802 return preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
806 * wp_kses_html_error() - Handles parsing errors in wp_kses_hair()
808 * The general plan is to remove everything to and including some
809 * whitespace, but it deals with quotes and apostrophes as well.
813 * @param string $string
816 function wp_kses_html_error($string) {
817 return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string);
821 * wp_kses_bad_protocol_once() - Sanitizes content from bad protocols and other characters
823 * This function searches for URL protocols at the beginning of $string,
824 * while handling whitespace and HTML entities.
828 * @param string $string Content to check for bad protocols
829 * @param string $allowed_protocols Allowed protocols
830 * @return string Sanitized content
832 function wp_kses_bad_protocol_once($string, $allowed_protocols) {
833 global $_kses_allowed_protocols;
834 $_kses_allowed_protocols = $allowed_protocols;
836 $string2 = preg_split('/:|:|:/i', $string, 2);
837 if ( isset($string2[1]) && !preg_match('%/\?%', $string2[0]) )
838 $string = wp_kses_bad_protocol_once2($string2[0], $allowed_protocols) . trim($string2[1]);
840 $string = preg_replace_callback('/^((&[^;]*;|[\sA-Za-z0-9])*)'.'(:|:|&#[Xx]3[Aa];)\s*/', create_function('$matches', 'global $_kses_allowed_protocols; return wp_kses_bad_protocol_once2($matches[1], $_kses_allowed_protocols);'), $string);
846 * wp_kses_bad_protocol_once2() - Callback for wp_kses_bad_protocol_once() regular expression.
848 * This function processes URL protocols, checks to see if they're in the
849 * white-list or not, and returns different data depending on the answer.
853 * @param string $string Content to check for bad protocols
854 * @param array $allowed_protocols Allowed protocols
855 * @return string Sanitized content
857 function wp_kses_bad_protocol_once2($string, $allowed_protocols) {
858 $string2 = wp_kses_decode_entities($string);
859 $string2 = preg_replace('/\s/', '', $string2);
860 $string2 = wp_kses_no_null($string2);
861 $string2 = preg_replace('/\xad+/', '', $string2);
862 # deals with Opera "feature"
863 $string2 = strtolower($string2);
866 foreach ($allowed_protocols as $one_protocol)
867 if (strtolower($one_protocol) == $string2) {
879 * wp_kses_normalize_entities() - Converts and fixes HTML entities
881 * This function normalizes HTML entities. It will convert "AT&T" to the
882 * correct "AT&T", ":" to ":", "&#XYZZY;" to "&#XYZZY;"
887 * @param string $string Content to normalize entities
888 * @return string Content with normalized entities
890 function wp_kses_normalize_entities($string) {
891 # Disarm all entities by converting & to &
893 $string = str_replace('&', '&', $string);
895 # Change back the allowed entities in our entity whitelist
897 $string = preg_replace('/&([A-Za-z][A-Za-z0-9]{0,19});/', '&\\1;', $string);
898 $string = preg_replace_callback('/&#0*([0-9]{1,5});/', create_function('$matches', 'return wp_kses_normalize_entities2($matches[1]);'), $string);
899 $string = preg_replace('/&#([Xx])0*(([0-9A-Fa-f]{2}){1,2});/', '&#\\1\\2;', $string);
905 * wp_kses_normalize_entities2() - Callback for wp_kses_normalize_entities() regular expression
907 * This function helps wp_kses_normalize_entities() to only accept 16 bit
908 * values and nothing more for &#number; entities.
912 * @param int $i Number encoded entity
913 * @return string Correctly encoded entity
915 function wp_kses_normalize_entities2($i) {
916 return (($i > 65535) ? "&#$i;" : "&#$i;");
920 * wp_kses_decode_entities() - Convert all entities to their character counterparts.
922 * This function decodes numeric HTML entities (A and A). It
923 * doesn't do anything with other entities like ä, but we don't need
924 * them in the URL protocol whitelisting system anyway.
928 * @param string $string Content to change entities
929 * @return string Content after decoded entities
931 function wp_kses_decode_entities($string) {
932 $string = preg_replace('/&#([0-9]+);/e', 'chr("\\1")', $string);
933 $string = preg_replace('/&#[Xx]([0-9A-Fa-f]+);/e', 'chr(hexdec("\\1"))', $string);
939 * wp_filter_kses() - Sanitize content with allowed HTML Kses rules
944 * @param string $data Content to filter
945 * @return string Filtered content
947 function wp_filter_kses($data) {
949 return addslashes( wp_kses(stripslashes( $data ), $allowedtags) );
953 * wp_filter_post_kses() - Sanitize content for allowed HTML tags for post content
955 * Post content refers to the page contents of the 'post' type and not
956 * $_POST data from forms.
959 * @uses $allowedposttags
961 * @param string $data Post content to filter
962 * @return string Filtered post content with allowed HTML tags and attributes intact.
964 function wp_filter_post_kses($data) {
965 global $allowedposttags;
966 return addslashes ( wp_kses(stripslashes( $data ), $allowedposttags) );
970 * wp_filter_nohtml_kses() - Strips all of the HTML in the content
974 * @param string $data Content to strip all HTML from
975 * @return string Filtered content without any HTML
977 function wp_filter_nohtml_kses($data) {
978 return addslashes ( wp_kses(stripslashes( $data ), array()) );
982 * kses_init_filters() - Adds all Kses input form content filters
984 * All hooks have default priority. The wp_filter_kses() fucntion
985 * is added to the 'pre_comment_content' and 'title_save_pre'
986 * hooks. The wp_filter_post_kses() function is added to the
987 * 'content_save_pre', 'excerpt_save_pre', and 'content_filtered_save_pre'
991 * @uses add_filter() See description for what functions are added to what hooks.
993 function kses_init_filters() {
995 add_filter('pre_comment_content', 'wp_filter_kses');
996 add_filter('title_save_pre', 'wp_filter_kses');
999 add_filter('content_save_pre', 'wp_filter_post_kses');
1000 add_filter('excerpt_save_pre', 'wp_filter_post_kses');
1001 add_filter('content_filtered_save_pre', 'wp_filter_post_kses');
1005 * kses_remove_filters() - Removes all Kses input form content filters
1007 * A quick procedural method to removing all of the filters
1008 * that kses uses for content in WordPress Loop.
1010 * Does not remove the kses_init() function from 'init' hook
1011 * (priority is default). Also does not remove kses_init()
1012 * function from 'set_current_user' hook (priority is also
1017 function kses_remove_filters() {
1018 // Normal filtering.
1019 remove_filter('pre_comment_content', 'wp_filter_kses');
1020 remove_filter('title_save_pre', 'wp_filter_kses');
1023 remove_filter('content_save_pre', 'wp_filter_post_kses');
1024 remove_filter('excerpt_save_pre', 'wp_filter_post_kses');
1025 remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');
1029 * kses_init() - Sets up most of the Kses filters for input form content
1031 * If you remove the kses_init() function from 'init' hook and
1032 * 'set_current_user' (priority is default), then none of the
1033 * Kses filter hooks will be added.
1035 * First removes all of the Kses filters in case the current user
1036 * does not need to have Kses filter the content. If the user does
1037 * not have unfiltered html capability, then Kses filters are added.
1039 * @uses kses_remove_filters() Removes the Kses filters
1040 * @uses kses_init_filters() Adds the Kses filters back if the user
1041 * does not have unfiltered HTML capability.
1044 function kses_init() {
1045 kses_remove_filters();
1047 if (current_user_can('unfiltered_html') == false)
1048 kses_init_filters();
1051 add_action('init', 'kses_init');
1052 add_action('set_current_user', 'kses_init');