Source for file php4.class.kses.php
Documentation is available at php4.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 PHP4 OOP version of kses
* This is an updated version of kses to work with PHP4 that works under E_STRICT.
* This upgrade provides the following:
* + Version number synced to procedural version number
* + PHPdoc style documentation has been added to the class. See http://www.phpdoc.org/ for more info.
* + Some methods are now deprecated due to nomenclature style change. See method documentation for specifics.
* + Kses4 now works in E_STRICT
* + Addition of methods AddProtocols(), filterKsestextHook(), RemoveProtocol() and RemoveProtocols()
* + Deprecated _hook(), Protocols()
* + Integrated code from kses 0.2.2 into class.
* + Added methods DumpProtocols(), DumpMethods()
die("Class kses requires PHP 4 or higher.");
* Only install KSES4 once
define('KSES_CLASS_PHP4', 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 entire set of functions was wrapped in a PHP object with some internal modifications
* by Richard Vasquez (http://www.chaos.org/) 7/25/2003
* This upgrade provides the following:
* + Version number synced to procedural version number
* + PHPdoc style documentation has been added to the class. See http://www.phpdoc.org/ for more info.
* + Some methods are now deprecated due to nomenclature style change. See method documentation for specifics.
* + Kses4 now works in E_STRICT
* + Addition of methods AddProtocols(), filterKsestextHook(), RemoveProtocol(), RemoveProtocols() and SetProtocols()
* + Deprecated _hook(), Protocols()
* + Integrated code from kses 0.2.2 into class.
* @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. 2003-2005
* @version PHP4 OOP 0.2.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
function Parse($string = "")
return $this->_split($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("kses4::AddProtocols() did not receive an argument.", E_USER_WARNING);
foreach($protocol_data as $protocol)
trigger_error("kses4::AddProtocols() did not receive a string or an array.", E_USER_WARNING);
* Allows for single/batch addition of protocols
* @deprecated Use AddProtocols()
trigger_error("kses4::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("kses4::AddProtocol() requires a string.", E_USER_WARNING);
trigger_error("kses4::AddProtocol() tried to add an empty/NULL protocol.", E_USER_WARNING);
// Remove any inadvertent ':' at the end of the protocol.
* 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("kses4::SetProtocols() did not receive an argument.", E_USER_WARNING);
foreach($protocol_data as $protocol)
trigger_error("kses4::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.
function AddHTML($tag = "", $attribs = array())
trigger_error("kses4::AddHTML() requires the tag to be a string", E_USER_WARNING);
trigger_error("kses4::AddHTML() tried to add an empty/NULL tag", E_USER_WARNING);
trigger_error("kses4::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;
* 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("kses4::RemoveProtocol() requires a string.", E_USER_WARNING);
// Remove any inadvertent ':' at the end of the protocol.
trigger_error("kses4::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("kses4::RemoveProtocols() did not receive a string or an array.", E_USER_WARNING);
* This method removes any NULL or characters in $string.
* @return string String without any NULL/chr(173)
* This function removes the HTML JavaScript entities found in early versions of
* @return string String without any NULL/chr(173)
return preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
* 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 &
# Change back the allowed entities in our entity white list
$string = preg_replace('/&([A-Za-z][A-Za-z0-9]{0,19});/', '&\\1;', $string);
$string = preg_replace('/&#0*([0-9]{1,5});/e', '\$this->_normalize_entities2("\\1")', $string);
$string = preg_replace('/&#([Xx])0*(([0-9A-Fa-f]{2}){1,2});/', '&#\\1\\2;', $string);
* 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 _normalize_entities()
return (($i > 65535) ? "&#$i;" : "&#$i;");
* Allows for additional user defined modifications to text.
* @deprecated use filterKsesTextHook()
* @see filterKsesTextHook()
* 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.
* 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 ($inarray as $inkey => $inval)
$outarray[$outkey] = array();
foreach ($inval as $inkey2 => $inval2)
$outarray[$outkey][$outkey2] = $inval2;
* This method searched for HTML tags, no matter how malformed. It also
* matches stray ">" characters.
* @return string HTML tags
'[^>]*'. # things that aren't >
'(>|$)'. # > or end of string
"\$this->_split2('\\1')",
* 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]);
# They are using a not allowed HTML element
# No attributes are allowed for closing elements
return $this->_attr("$slash$elem", $attrlist);
* 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 $this->_hair() to split them further, and then it
* builds up new HTML code from the data that $this->_hair() 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 ''
function _attr($element, $attr)
# 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>";
$attrarr = $this->_hair($attr);
# Go through $attrarr, and save the allowed attributes for this element
foreach ($attrarr as $arreach)
# the attribute is not allowed
$attr2 .= ' '. $arreach['whole'];
foreach ($current as $currkey => $currval)
if (!$this->_check_attr_val($arreach['value'], $arreach['vless'], $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
# 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 = preg_replace('/\xad+/', '', $string); # deals with Opera "feature"
while ($string != $string2)
* Helper method used by _bad_protocol()
* This function searches for URL protocols at the beginning of $string, while
* handling whitespace and HTML entities.
* Function updated to fix security vulnerability (see http://projects.dokeos.com/index.php?do=details&task_id=2312)
* @param string $string String to check for protocols
* @return string String with removed protocols
$string2 = preg_split('/:|:|:/i', $string, 2);
if(isset ($string2[1]) && !preg_match('%/\?%',$string2[0]))
* Helper method used by _bad_protocol_once() regex
* 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 _bad_protocol_once()
$string = preg_replace('/\xad+/', '', $string); # deals with Opera "feature"
* This function performs different checks for attribute values.
* The currently implemented checks are "maxlen", "minlen", "maxval",
* "minval" and "valueless" with even more checks to come soon.
* @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
* 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.
if (strlen($value) > $checkvalue)
* The minlen check makes sure that the attribute value has a length not
* smaller than the given value.
if (strlen($value) < $checkvalue)
* 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.
if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
if ($value > $checkvalue)
* The minval check checks that the attribute value is a positive integer,
* and that it is not smaller than the given value.
if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
if ($value < $checkvalue)
* 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.
* This function changes the character sequence \" to just "
* It leaves all other slashes alone. It's really weird, but the quoting from
* preg_replace(//e) seems to require this.
* @param string $string The string to be stripped.
* @return string string stripped of \"
* helper method for _hair()
* This function deals with parsing errors in _hair(). The general plan is
* to remove everything to and including some whitespace, but it deals with
* quotes and apostrophes as well.
* @param string $string The string to be stripped.
* @return string string stripped of whitespace
return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string);
* 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 PHP4 OOP version # of kses.
* Since this class has been refactored and documented and proven to work,
* I'm syncing the version number to procedural kses.
* @return string Version number
return 'PHP4 0.2.2 (OOP fork of procedural kses 0.2.2)';
|