Source for file php5.class.kses.php
Documentation is available at php5.class.kses.php
* ==========================================================================================
* This program is free software and open source software; you can redistribute
* it and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or visit
* http://www.gnu.org/licenses/gpl.html
* ==========================================================================================
* Class file for PHP5 OOP version of kses
* This is an updated version of kses to work with PHP5 that works under E_STRICT.
* This version is a bit of a rewrite to match my own coding style and use some of the
* capabilities allowed in PHP5. Since this was a significant rewrite, but it still
* maintains backward compatibility syntax-wise, the version number is now 1.0.0. Any
* minor changes that do not break compatibility will be indicated in the second or third
* digits. Anything that breaks compatibility will change the major version number.
* + Private methods are now in place
* + __construct() is now used rather then the standard class name 'kses()'
* + Kses will not load in any version less that PHP5
* + PHPdoc style documentation has been added to the class. See http://www.phpdoc.org/ for more info.
* + Method names have been changed to reflect status as verbs
* + One line methods have been folded into the code
* + Some methods are now deprecated due to nomenclature style change. See method documentation for specifics.
* + Kses5 now works in E_STRICT
* + Version number is 1.0.0 to reflect serious code changes
* + Addition of methods AddProtocols(), filterKsestextHook(), RemoveProtocol(), RemoveProtocols() and SetProtocols()
* + Deprecated _hook(), Protocols()
die("Class kses requires PHP 5 or higher.");
* Only install KSES5 once
define('KSES_CLASS_PHP5', true);
* Kses strips evil scripts!
* This class provides the capability for removing unwanted HTML/XHTML, attributes from
* tags, and protocols contained in links. The net result is a much more powerful tool
* than the PHP internal strip_tags()
* This is a fork of a slick piece of procedural code called 'kses' written by Ulf Harnhammar.
* The original class for PHP4 was basically a wrapper around all of the functions in
* the procedural code written by Ulf, and was released 7/25/2003.
* This version is a bit of a rewrite to match my own coding style and use some of the
* capabilities allowed in PHP5. Since this was a significant rewrite, but it still
* maintains backward compatibility syntax-wise, the version number is now 1.0.0. Any
* minor changes that do not break compatibility will be indicated in the second or third
* digits. Anything that breaks compatibility will change the major version number.
* + Private methods are now in place
* + __construct() is now used rather then the standard class name 'kses()'
* + Kses5 will not load in any version less that PHP5
* + PHPdoc style documentation has been added to the class. See http://www.phpdoc.org/ for more info.
* + Method names have been changed to reflect status as verbs
* + One line methods have been folded into the code
* + Some methods are now deprecated due to nomenclature style change. See method documentation for specifics.
* + Kses now works in E_STRICT
* + Initial Version number set to 1.0.0 to reflect serious code changes
* + Addition of methods AddProtocols(), filterKsestextHook(), RemoveProtocol(), RemoveProtocols() and SetProtocols()
* + Deprecated _hook(), Protocols()
* + Integrated code from kses 0.2.2 into class.
* + Added methods DumpProtocols(), DumpMethods()
* @author Richard R. V�squez, Jr. (Original procedural code by Ulf H�rnhammar)
* @link http://sourceforge.net/projects/kses/ Home Page for Kses
* @link http://chaos.org/contact/ Contact page with current email address for Richard Vasquez
* @copyright Richard R. V�squez, Jr. 2005
* @version PHP5 OOP 1.0.2
* @license http://www.gnu.org/licenses/gpl.html GNU Public License
* This sets a default collection of protocols allowed in links, and creates an
* empty set of allowed HTML tags.
* You could add protocols such as ftp, new, gopher, mailto, irc, etc.
* The base values the original kses provided were:
* 'http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'gopher', 'mailto'
* Basic task of kses - parses $string and strips it as required.
* This method strips all the disallowed (X)HTML tags, attributes
* and protocols from the input $string.
* @param string $string String to be stripped of 'evil scripts'
* @return string The stripped string
public function Parse($string = "")
// Remove JavaScript entities from early Netscape 4 versions
$string = preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
$string = preg_replace('%(<' . '[^>]*' . '(>|$)' . '|>)%e', "\$this->stripTags('\\1')", $string);
* Allows for single/batch addition of protocols
* This method accepts one argument that can be either a string
* or an array of strings. Invalid data will be ignored.
* The argument will be processed, and each string will be added
* @param mixed , A string or array of protocols that will be added to the internal list of allowed protocols.
* @return bool Status of adding valid protocols.
trigger_error("kses5::AddProtocols() did not receive an argument.", E_USER_WARNING);
foreach($protocol_data as $protocol)
trigger_error("kses5::AddProtocols() did not receive a string or an array.", E_USER_WARNING);
* Allows for single/batch addition of protocols
* @deprecated Use AddProtocols()
trigger_error("kses5::Protocols() did not receive an argument.", E_USER_WARNING);
* Adds a single protocol to $this->allowed_protocols.
* This method accepts a string argument and adds it to
* the list of allowed protocols to keep when performing
* @param string $protocol The name of the protocol to be added.
* @return bool Status of adding valid protocol.
trigger_error("kses5::AddProtocol() requires a string.", E_USER_WARNING);
// Remove any inadvertent ':' at the end of the protocol.
trigger_error("kses5::AddProtocol() tried to add an empty/NULL protocol.", E_USER_WARNING);
// prevent duplicate protocols from being added.
* Removes a single protocol from $this->allowed_protocols.
* This method accepts a string argument and removes it from
* the list of allowed protocols to keep when performing
* @param string $protocol The name of the protocol to be removed.
* @return bool Status of removing valid protocol.
trigger_error("kses5::RemoveProtocol() requires a string.", E_USER_WARNING);
// Remove any inadvertent ':' at the end of the protocol.
trigger_error("kses5::RemoveProtocol() tried to remove an empty/NULL protocol.", E_USER_WARNING);
// Ensures that the protocol exists before removing it.
* Allows for single/batch removal of protocols
* This method accepts one argument that can be either a string
* or an array of strings. Invalid data will be ignored.
* The argument will be processed, and each string will be removed
* @param mixed , A string or array of protocols that will be removed from the internal list of allowed protocols.
* @return bool Status of removing valid protocols.
foreach($protocol_data as $protocol)
trigger_error("kses5::RemoveProtocols() did not receive a string or an array.", E_USER_WARNING);
* Allows for single/batch replacement of protocols
* This method accepts one argument that can be either a string
* or an array of strings. Invalid data will be ignored.
* Existing protocols will be removed, then the argument will be
* processed, and each string will be added via AddProtocol().
* @param mixed , A string or array of protocols that will be the new internal list of allowed protocols.
* @return bool Status of replacing valid protocols.
trigger_error("kses5::SetProtocols() did not receive an argument.", E_USER_WARNING);
foreach($protocol_data as $protocol)
trigger_error("kses5::SetProtocols() did not receive a string or an array.", E_USER_WARNING);
* Raw dump of allowed protocols
* This returns an indexed array of allowed protocols for a particular KSES
* @return array The list of allowed protocols.
* Raw dump of allowed (X)HTML elements
* This returns an indexed array of allowed (X)HTML elements and attributes
* for a particular KSES instantiation.
* @return array The list of allowed elements.
* Adds valid (X)HTML with corresponding attributes that will be kept when stripping 'evil scripts'.
* This method accepts one argument that can be either a string
* or an array of strings. Invalid data will be ignored.
* @param string $tag (X)HTML tag that will be allowed after stripping text.
* @param array $attribs Associative array of allowed attributes - key => attribute name - value => attribute parameter
* @return bool Status of Adding (X)HTML and attributes.
public function AddHTML($tag = "", $attribs = array())
trigger_error("kses5::AddHTML() requires the tag to be a string", E_USER_WARNING);
trigger_error("kses5::AddHTML() tried to add an empty/NULL tag", E_USER_WARNING);
trigger_error("kses5::AddHTML() requires an array (even an empty one) of attributes for '$tag'", E_USER_WARNING);
foreach($attribs as $idx1 => $val1)
$new_val1 = $attribs[$idx1];
foreach($new_val1 as $idx2 => $val2)
$tmp_val[$new_idx2] = $val2;
$new_attribs[$new_idx1] = $new_val1;
* This method removes any NULL characters in $string.
* @return string String without any NULL/chr(173)
* Normalizes HTML entities
* This function normalizes HTML entities. It will convert "AT&T" to the correct
* "AT&T", ":" to ":", "&#XYZZY;" to "&#XYZZY;" and so on.
* @return string String with normalized entities
# Disarm all entities by converting & to &
# TODO: Change back (Keep?) the allowed entities in our entity white list
# Keeps entities that start with [A-Za-z]
'/&([A-Za-z][A-Za-z0-9]{0,19});/',
# Change numeric entities to valid 16 bit values
'/&#0*([0-9]{1,5});/e',
'\$this->normalizeEntities16bit("\\1")',
# Change &XHHHHHHH (Hex digits) to 16 bit hex values
'/&#([Xx])0*(([0-9A-Fa-f]{2}){1,2});/',
* Helper method used by normalizeEntites()
* This method helps normalizeEntities() to only accept 16 bit values
* and nothing more for &#number; entities.
* This method helps normalize_entities() during a preg_replace()
* where a &#(0)*XXXXX; occurs. The '(0)*XXXXXX' value is converted to
* a number and the result is returned as a numeric entity if the number
* is less than 65536. Otherwise, the value is returned 'as is'.
* @return string Normalized numeric entity
* @see normalizeEntities()
return (($i > 65535) ? "&#$i;" : "&#$i;");
* Allows for additional user defined modifications to text.
* This method allows for additional modifications to be performed on
* a string that's being run through Parse(). Currently, it returns the
* This method is provided for users to extend the kses class for their own
* @param string $string String to perfrom additional modifications on.
* @return string User modified string.
* Allows for additional user defined modifications to text.
* @deprecated use filterKsesTextHook()
* @see filterKsesTextHook()
private function _hook($string)
* This method goes through an array, and changes the keys to all lower case.
* @param array $in_array Associative array
* @return array Modified array
foreach ($in_array as $in_key => $in_val)
$out_array[$out_key] = array();
foreach ($in_val as $in_key2 => $in_val2)
$out_array[$out_key][$out_key2] = $in_val2;
* This method strips out disallowed and/or mangled (X)HTML tags along with assigned attributes.
* This method does a lot of work. It rejects some very malformed things
* like <:::>. It returns an empty string if the element isn't allowed (look
* ma, no strip_tags()!). Otherwise it splits the tag into an element and an
* allowed attribute list.
* @return string Modified string minus disallowed/mangled (X)HTML and attributes
if (substr($string, 0, 1) != '<')
# It matched a ">" character
if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches))
# It's seriously malformed
$slash = trim($matches[1]);
# Found an HTML element not in the white list
# No attributes are allowed for closing elements
* This method strips out disallowed attributes for (X)HTML tags.
* This method removes all attributes if none are allowed for this element.
* If some are allowed it calls combAttributes() to split them further, and then it
* builds up new HTML code from the data that combAttributes() returns. It also
* removes "<" and ">" characters, if there are any left. One more thing it
* does is to check if the tag has a closing XHTML slash, and if it does,
* it puts one in the returned code as well.
* @param string $element (X)HTML tag to check
* @param string $attr Text containing attributes to check for validity.
* @return string Resulting valid (X)HTML or ''
# Is there a closing XHTML slash at the end of the attributes?
# Are any attributes allowed at all for this element?
return "<$element$xhtml_slash>";
# Go through $attrarr, and save the allowed attributes for this element
foreach ($attrarr as $arreach)
$attr2 .= ' '. $arreach['whole'];
foreach ($current as $currkey => $currval)
$attr2 .= ' '. $arreach['whole'];
# Remove any "<" or ">" characters
return "<$element$attr2$xhtml_slash>";
* This method combs through an attribute list string and returns an associative array of attributes and values.
* This method does a lot of work. It parses an attribute list into an array
* with attribute data, and tries to do the right thing even if it gets weird
* input. It will add quotes around attribute values that don't have any quotes
* or apostrophes around them, to make it easier to produce HTML code that will
* conform to W3C's HTML specification. It will also remove bad URL protocols
* @param string $attr Text containing tag attributes for parsing
* @return array Associative array containing data on attribute and value
# Loop through the whole attribute list
# Was the last operation successful?
case 0: # attribute name, href for instance
case 1: # equals sign or valueless ("selected")
if (preg_match('/^\s*=\s*/', $attr)) # equals sign
case 2: # attribute value, a URL after href= for instance
if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) # "value"
'whole' => $attrname . '="' . $thisval . '"',
if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match)) # 'value'
'whole' => "$attrname='$thisval'",
if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match)) # value
'whole' => $attrname . '="' . $thisval . '"',
# We add quotes to conform to W3C's HTML spec.
if ($working == 0) # not well formed, remove and try again
$attr = preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $attr);
# special case, for when the attribute list ends with a valueless
# attribute like "selected"
* This method removes disallowed protocols.
* This method removes all non-allowed protocols from the beginning of
* $string. It ignores whitespace and the case of the letters, and it does
* understand HTML entities. It does its work in a while loop, so it won't be
* fooled by a string like "javascript:javascript:alert(57)".
* @param string $string String to check for protocols
* @return string String with removed protocols
$string = $this->RemoveNulls($string);
$string = preg_replace('/\xad+/', '', $string); # deals with Opera "feature"
$string2 = $string . 'a';
$string2 = preg_split('/:|:|:/i', $string, 2);
if(isset ($string2[1]) && !preg_match('%/\?%',$string2[0]))
* Helper method used by removeBadProtocols()
* This function processes URL protocols, checks to see if they're in the white-
* list or not, and returns different data depending on the answer.
* @param string $string String to check for protocols
* @return string String with removed protocols
* @see removeBadProtocols()
$string = preg_replace('/\xad+/', '', $string2); # deals with Opera "feature"
* Controller method for performing checks on attribute values.
* This method calls the appropriate method as specified by $checkname with
* the parameters $value, $vless, and $checkvalue, and returns the result
* This method's functionality can be expanded by creating new methods
* that would match checkAttributeValue[$checkname].
* Current checks implemented are: "maxlen", "minlen", "maxval", "minval" and "valueless"
* @param string $value The value of the attribute to be checked.
* @param string $vless Indicates whether the the value is supposed to be valueless
* @param string $checkname The check to be performed
* @param string $checkvalue The value that is to be checked against
* @return bool Indicates whether the check passed or not
$check_attribute_method_name = 'checkAttributeValue' . ucfirst(strtolower($checkname));
$ok = $this->$check_attribute_method_name($value, $checkvalue, $vless);
* Helper method invoked by checkAttributeValue().
* The maxlen check makes sure that the attribute value has a length not
* greater than the given value. This can be used to avoid Buffer Overflows
* in WWW clients and various Internet servers.
* @param string $value The value of the attribute to be checked.
* @param int $checkvalue The maximum value allowed
* @return bool Indicates whether the check passed or not
* @see checkAttributeValue()
* Helper method invoked by checkAttributeValue().
* The minlen check makes sure that the attribute value has a length not
* smaller than the given value.
* @param string $value The value of the attribute to be checked.
* @param int $checkvalue The minimum value allowed
* @return bool Indicates whether the check passed or not
* @see checkAttributeValue()
* Helper method invoked by checkAttributeValue().
* The maxval check does two things: it checks that the attribute value is
* an integer from 0 and up, without an excessive amount of zeroes or
* whitespace (to avoid Buffer Overflows). It also checks that the attribute
* value is not greater than the given value.
* This check can be used to avoid Denial of Service attacks.
* @param int $value The value of the attribute to be checked.
* @param int $checkvalue The maximum numeric value allowed
* @return bool Indicates whether the check passed or not
* @see checkAttributeValue()
if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
* Helper method invoked by checkAttributeValue().
* The minval check checks that the attribute value is a positive integer,
* and that it is not smaller than the given value.
* @param int $value The value of the attribute to be checked.
* @param int $checkvalue The minimum numeric value allowed
* @return bool Indicates whether the check passed or not
* @see checkAttributeValue()
if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
if (intval($value) < ($checkvalue))
* Helper method invoked by checkAttributeValue().
* The valueless check checks if the attribute has a value
* (like <a href="blah">) or not (<option selected>). If the given value
* is a "y" or a "Y", the attribute must not have a value.
* If the given value is an "n" or an "N", the attribute must have one.
* @param int $value The value of the attribute to be checked.
* @param mixed $checkvalue This variable is ignored for this test
* @param string $vless Flag indicating if this attribute is not supposed to have an attribute
* @return bool Indicates whether the check passed or not
* @see checkAttributeValue()
* Decodes numeric HTML entities
* This method decodes numeric HTML entities (A and A). It doesn't
* do anything with other entities like ä, but we don't need them in the
* URL protocol white listing system anyway.
* @param string $value The entitiy to be decoded.
* @return string Decoded entity
$string = preg_replace('/&#([0-9]+);/e', 'chr("\\1")', $string);
$string = preg_replace('/&#[Xx]([0-9A-Fa-f]+);/e', 'chr(hexdec("\\1"))', $string);
* Returns PHP5 OOP version # of kses.
* Since this class has been refactored and documented and proven to work,
* I'm fixing the version number at 1.0.0.
* This version is syntax compatible with the PHP4 OOP version 0.0.2. Future
* versions may not be syntax compatible.
* @return string Version number
|