php5.class.kses.php 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. <?php
  2. /*
  3. * ==========================================================================================
  4. *
  5. * This program is free software and open source software; you can redistribute
  6. * it and/or modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation; either version 2 of the License,
  8. * or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful, but WITHOUT
  11. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  13. * more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or visit
  18. * http://www.gnu.org/licenses/gpl.html
  19. *
  20. * ==========================================================================================
  21. */
  22. /**
  23. * Class file for PHP5 OOP version of kses
  24. *
  25. * This is an updated version of kses to work with PHP5 that works under E_STRICT.
  26. *
  27. * This version is a bit of a rewrite to match my own coding style and use some of the
  28. * capabilities allowed in PHP5. Since this was a significant rewrite, but it still
  29. * maintains backward compatibility syntax-wise, the version number is now 1.0.0. Any
  30. * minor changes that do not break compatibility will be indicated in the second or third
  31. * digits. Anything that breaks compatibility will change the major version number.
  32. *
  33. * PHP5 specific changes:
  34. * + Private methods are now in place
  35. * + __construct() is now used rather then the standard class name 'kses()'
  36. * + Kses will not load in any version less that PHP5
  37. * Other modifications:
  38. * + PHPdoc style documentation has been added to the class. See http://www.phpdoc.org/ for more info.
  39. * + Method names have been changed to reflect status as verbs
  40. * + One line methods have been folded into the code
  41. * + Some methods are now deprecated due to nomenclature style change. See method documentation for specifics.
  42. * + Kses5 now works in E_STRICT
  43. * + Version number is 1.0.0 to reflect serious code changes
  44. * + Addition of methods AddProtocols(), filterKsestextHook(), RemoveProtocol(), RemoveProtocols() and SetProtocols()
  45. * + Deprecated _hook(), Protocols()
  46. *
  47. * @package kses
  48. * @subpackage kses5
  49. */
  50. if(substr(phpversion(), 0, 1) < 5)
  51. {
  52. die("Class kses requires PHP 5 or higher.");
  53. }
  54. /**
  55. * Only install KSES5 once
  56. */
  57. if(!defined('KSES_CLASS_PHP5'))
  58. {
  59. define('KSES_CLASS_PHP5', true);
  60. /**
  61. * Kses strips evil scripts!
  62. *
  63. * This class provides the capability for removing unwanted HTML/XHTML, attributes from
  64. * tags, and protocols contained in links. The net result is a much more powerful tool
  65. * than the PHP internal strip_tags()
  66. *
  67. * This is a fork of a slick piece of procedural code called 'kses' written by Ulf Harnhammar.
  68. *
  69. * The original class for PHP4 was basically a wrapper around all of the functions in
  70. * the procedural code written by Ulf, and was released 7/25/2003.
  71. *
  72. * This version is a bit of a rewrite to match my own coding style and use some of the
  73. * capabilities allowed in PHP5. Since this was a significant rewrite, but it still
  74. * maintains backward compatibility syntax-wise, the version number is now 1.0.0. Any
  75. * minor changes that do not break compatibility will be indicated in the second or third
  76. * digits. Anything that breaks compatibility will change the major version number.
  77. *
  78. * PHP5 specific changes:
  79. * + Private methods are now in place
  80. * + __construct() is now used rather then the standard class name 'kses()'
  81. * + Kses5 will not load in any version less that PHP5
  82. * Other modifications:
  83. * + PHPdoc style documentation has been added to the class. See http://www.phpdoc.org/ for more info.
  84. * + Method names have been changed to reflect status as verbs
  85. * + One line methods have been folded into the code
  86. * + Some methods are now deprecated due to nomenclature style change. See method documentation for specifics.
  87. * + Kses now works in E_STRICT
  88. * + Initial Version number set to 1.0.0 to reflect serious code changes
  89. * + Addition of methods AddProtocols(), filterKsestextHook(), RemoveProtocol(), RemoveProtocols() and SetProtocols()
  90. * + Deprecated _hook(), Protocols()
  91. * + Integrated code from kses 0.2.2 into class.
  92. * + Added methods DumpProtocols(), DumpMethods()
  93. *
  94. * @author Richard R. V�squez, Jr. (Original procedural code by Ulf H�rnhammar)
  95. * @link http://sourceforge.net/projects/kses/ Home Page for Kses
  96. * @link http://chaos.org/contact/ Contact page with current email address for Richard Vasquez
  97. * @copyright Richard R. V�squez, Jr. 2005
  98. * @version PHP5 OOP 1.0.2
  99. * @license http://www.gnu.org/licenses/gpl.html GNU Public License
  100. * @package kses
  101. */
  102. class kses5
  103. {
  104. /**#@+
  105. * @access private
  106. * @var array
  107. */
  108. private $allowed_protocols;
  109. private $allowed_html;
  110. /**#@-*/
  111. /**
  112. * Constructor for kses.
  113. *
  114. * This sets a default collection of protocols allowed in links, and creates an
  115. * empty set of allowed HTML tags.
  116. * @since PHP5 OOP 1.0.0
  117. */
  118. public function __construct()
  119. {
  120. /**
  121. * You could add protocols such as ftp, new, gopher, mailto, irc, etc.
  122. *
  123. * The base values the original kses provided were:
  124. * 'http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'gopher', 'mailto'
  125. */
  126. $this->allowed_protocols = array('http', 'ftp', 'mailto');
  127. $this->allowed_html = array();
  128. }
  129. /**
  130. * Basic task of kses - parses $string and strips it as required.
  131. *
  132. * This method strips all the disallowed (X)HTML tags, attributes
  133. * and protocols from the input $string.
  134. *
  135. * @access public
  136. * @param string $string String to be stripped of 'evil scripts'
  137. * @return string The stripped string
  138. * @since PHP4 OOP 0.0.1
  139. */
  140. public function Parse($string = "")
  141. {
  142. if (get_magic_quotes_gpc())
  143. {
  144. $string = stripslashes($string);
  145. }
  146. $string = $this->removeNulls($string);
  147. // Remove JavaScript entities from early Netscape 4 versions
  148. $string = preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
  149. $string = $this->normalizeEntities($string);
  150. $string = $this->filterKsesTextHook($string);
  151. $string = preg_replace('%(<' . '[^>]*' . '(>|$)' . '|>)%e', "\$this->stripTags('\\1')", $string);
  152. return $string;
  153. }
  154. /**
  155. * Allows for single/batch addition of protocols
  156. *
  157. * This method accepts one argument that can be either a string
  158. * or an array of strings. Invalid data will be ignored.
  159. *
  160. * The argument will be processed, and each string will be added
  161. * via AddProtocol().
  162. *
  163. * @access public
  164. * @param mixed , A string or array of protocols that will be added to the internal list of allowed protocols.
  165. * @return bool Status of adding valid protocols.
  166. * @see AddProtocol()
  167. * @since PHP5 OOP 1.0.0
  168. */
  169. public function AddProtocols()
  170. {
  171. $c_args = func_num_args();
  172. if($c_args != 1)
  173. {
  174. trigger_error("kses5::AddProtocols() did not receive an argument.", E_USER_WARNING);
  175. return false;
  176. }
  177. $protocol_data = func_get_arg(0);
  178. if(is_array($protocol_data) && count($protocol_data) > 0)
  179. {
  180. foreach($protocol_data as $protocol)
  181. {
  182. $this->AddProtocol($protocol);
  183. }
  184. return true;
  185. }
  186. elseif(is_string($protocol_data))
  187. {
  188. $this->AddProtocol($protocol_data);
  189. return true;
  190. }
  191. else
  192. {
  193. trigger_error("kses5::AddProtocols() did not receive a string or an array.", E_USER_WARNING);
  194. return false;
  195. }
  196. }
  197. /**
  198. * Allows for single/batch addition of protocols
  199. *
  200. * @deprecated Use AddProtocols()
  201. * @see AddProtocols()
  202. * @return bool
  203. * @since PHP4 OOP 0.0.1
  204. */
  205. public function Protocols()
  206. {
  207. $c_args = func_num_args();
  208. if($c_args != 1)
  209. {
  210. trigger_error("kses5::Protocols() did not receive an argument.", E_USER_WARNING);
  211. return false;
  212. }
  213. return $this->AddProtocols(func_get_arg(0));
  214. }
  215. /**
  216. * Adds a single protocol to $this->allowed_protocols.
  217. *
  218. * This method accepts a string argument and adds it to
  219. * the list of allowed protocols to keep when performing
  220. * Parse().
  221. *
  222. * @access public
  223. * @param string $protocol The name of the protocol to be added.
  224. * @return bool Status of adding valid protocol.
  225. * @since PHP4 OOP 0.0.1
  226. */
  227. public function AddProtocol($protocol = "")
  228. {
  229. if(!is_string($protocol))
  230. {
  231. trigger_error("kses5::AddProtocol() requires a string.", E_USER_WARNING);
  232. return false;
  233. }
  234. // Remove any inadvertent ':' at the end of the protocol.
  235. if(substr($protocol, strlen($protocol) - 1, 1) == ":")
  236. {
  237. $protocol = substr($protocol, 0, strlen($protocol) - 1);
  238. }
  239. $protocol = strtolower(trim($protocol));
  240. if($protocol == "")
  241. {
  242. trigger_error("kses5::AddProtocol() tried to add an empty/NULL protocol.", E_USER_WARNING);
  243. return false;
  244. }
  245. // prevent duplicate protocols from being added.
  246. if(!in_array($protocol, $this->allowed_protocols))
  247. {
  248. array_push($this->allowed_protocols, $protocol);
  249. sort($this->allowed_protocols);
  250. }
  251. return true;
  252. }
  253. /**
  254. * Removes a single protocol from $this->allowed_protocols.
  255. *
  256. * This method accepts a string argument and removes it from
  257. * the list of allowed protocols to keep when performing
  258. * Parse().
  259. *
  260. * @access public
  261. * @param string $protocol The name of the protocol to be removed.
  262. * @return bool Status of removing valid protocol.
  263. * @since PHP5 OOP 1.0.0
  264. */
  265. public function RemoveProtocol($protocol = "")
  266. {
  267. if(!is_string($protocol))
  268. {
  269. trigger_error("kses5::RemoveProtocol() requires a string.", E_USER_WARNING);
  270. return false;
  271. }
  272. // Remove any inadvertent ':' at the end of the protocol.
  273. if(substr($protocol, strlen($protocol) - 1, 1) == ":")
  274. {
  275. $protocol = substr($protocol, 0, strlen($protocol) - 1);
  276. }
  277. $protocol = strtolower(trim($protocol));
  278. if($protocol == "")
  279. {
  280. trigger_error("kses5::RemoveProtocol() tried to remove an empty/NULL protocol.", E_USER_WARNING);
  281. return false;
  282. }
  283. // Ensures that the protocol exists before removing it.
  284. if(in_array($protocol, $this->allowed_protocols))
  285. {
  286. $this->allowed_protocols = array_diff($this->allowed_protocols, array($protocol));
  287. sort($this->allowed_protocols);
  288. }
  289. return true;
  290. }
  291. /**
  292. * Allows for single/batch removal of protocols
  293. *
  294. * This method accepts one argument that can be either a string
  295. * or an array of strings. Invalid data will be ignored.
  296. *
  297. * The argument will be processed, and each string will be removed
  298. * via RemoveProtocol().
  299. *
  300. * @access public
  301. * @param mixed , A string or array of protocols that will be removed from the internal list of allowed protocols.
  302. * @return bool Status of removing valid protocols.
  303. * @see RemoveProtocol()
  304. * @since PHP5 OOP 1.0.0
  305. */
  306. public function RemoveProtocols()
  307. {
  308. $c_args = func_num_args();
  309. if($c_args != 1)
  310. {
  311. return false;
  312. }
  313. $protocol_data = func_get_arg(0);
  314. if(is_array($protocol_data) && count($protocol_data) > 0)
  315. {
  316. foreach($protocol_data as $protocol)
  317. {
  318. $this->RemoveProtocol($protocol);
  319. }
  320. }
  321. elseif(is_string($protocol_data))
  322. {
  323. $this->RemoveProtocol($protocol_data);
  324. return true;
  325. }
  326. else
  327. {
  328. trigger_error("kses5::RemoveProtocols() did not receive a string or an array.", E_USER_WARNING);
  329. return false;
  330. }
  331. }
  332. /**
  333. * Allows for single/batch replacement of protocols
  334. *
  335. * This method accepts one argument that can be either a string
  336. * or an array of strings. Invalid data will be ignored.
  337. *
  338. * Existing protocols will be removed, then the argument will be
  339. * processed, and each string will be added via AddProtocol().
  340. *
  341. * @access public
  342. * @param mixed , A string or array of protocols that will be the new internal list of allowed protocols.
  343. * @return bool Status of replacing valid protocols.
  344. * @since PHP5 OOP 1.0.1
  345. * @see AddProtocol()
  346. */
  347. public function SetProtocols()
  348. {
  349. $c_args = func_num_args();
  350. if($c_args != 1)
  351. {
  352. trigger_error("kses5::SetProtocols() did not receive an argument.", E_USER_WARNING);
  353. return false;
  354. }
  355. $protocol_data = func_get_arg(0);
  356. if(is_array($protocol_data) && count($protocol_data) > 0)
  357. {
  358. $this->allowed_protocols = array();
  359. foreach($protocol_data as $protocol)
  360. {
  361. $this->AddProtocol($protocol);
  362. }
  363. return true;
  364. }
  365. elseif(is_string($protocol_data))
  366. {
  367. $this->allowed_protocols = array();
  368. $this->AddProtocol($protocol_data);
  369. return true;
  370. }
  371. else
  372. {
  373. trigger_error("kses5::SetProtocols() did not receive a string or an array.", E_USER_WARNING);
  374. return false;
  375. }
  376. }
  377. /**
  378. * Raw dump of allowed protocols
  379. *
  380. * This returns an indexed array of allowed protocols for a particular KSES
  381. * instantiation.
  382. *
  383. * @access public
  384. * @return array The list of allowed protocols.
  385. * @since PHP5 OOP 1.0.2
  386. */
  387. public function DumpProtocols()
  388. {
  389. return $this->allowed_protocols;
  390. }
  391. /**
  392. * Raw dump of allowed (X)HTML elements
  393. *
  394. * This returns an indexed array of allowed (X)HTML elements and attributes
  395. * for a particular KSES instantiation.
  396. *
  397. * @access public
  398. * @return array The list of allowed elements.
  399. * @since PHP5 OOP 1.0.2
  400. */
  401. public function DumpElements()
  402. {
  403. return $this->allowed_html;
  404. }
  405. /**
  406. * Adds valid (X)HTML with corresponding attributes that will be kept when stripping 'evil scripts'.
  407. *
  408. * This method accepts one argument that can be either a string
  409. * or an array of strings. Invalid data will be ignored.
  410. *
  411. * @access public
  412. * @param string $tag (X)HTML tag that will be allowed after stripping text.
  413. * @param array $attribs Associative array of allowed attributes - key => attribute name - value => attribute parameter
  414. * @return bool Status of Adding (X)HTML and attributes.
  415. * @since PHP4 OOP 0.0.1
  416. */
  417. public function AddHTML($tag = "", $attribs = array())
  418. {
  419. if(!is_string($tag))
  420. {
  421. trigger_error("kses5::AddHTML() requires the tag to be a string", E_USER_WARNING);
  422. return false;
  423. }
  424. $tag = strtolower(trim($tag));
  425. if($tag == "")
  426. {
  427. trigger_error("kses5::AddHTML() tried to add an empty/NULL tag", E_USER_WARNING);
  428. return false;
  429. }
  430. if(!is_array($attribs))
  431. {
  432. trigger_error("kses5::AddHTML() requires an array (even an empty one) of attributes for '$tag'", E_USER_WARNING);
  433. return false;
  434. }
  435. $new_attribs = array();
  436. if(is_array($attribs) && count($attribs) > 0)
  437. {
  438. foreach($attribs as $idx1 => $val1)
  439. {
  440. $new_idx1 = strtolower($idx1);
  441. $new_val1 = $attribs[$idx1];
  442. if(is_array($new_val1) && count($attribs) > 0)
  443. {
  444. $tmp_val = array();
  445. foreach($new_val1 as $idx2 => $val2)
  446. {
  447. $new_idx2 = strtolower($idx2);
  448. $tmp_val[$new_idx2] = $val2;
  449. }
  450. $new_val1 = $tmp_val;
  451. }
  452. $new_attribs[$new_idx1] = $new_val1;
  453. }
  454. }
  455. $this->allowed_html[$tag] = $new_attribs;
  456. return true;
  457. }
  458. /**
  459. * This method removes any NULL characters in $string.
  460. *
  461. * @access private
  462. * @param string $string
  463. * @return string String without any NULL/chr(173)
  464. * @since PHP4 OOP 0.0.1
  465. */
  466. private function removeNulls($string)
  467. {
  468. $string = preg_replace('/\0+/', '', $string);
  469. $string = preg_replace('/(\\\\0)+/', '', $string);
  470. return $string;
  471. }
  472. /**
  473. * Normalizes HTML entities
  474. *
  475. * This function normalizes HTML entities. It will convert "AT&T" to the correct
  476. * "AT&amp;T", "&#00058;" to "&#58;", "&#XYZZY;" to "&amp;#XYZZY;" and so on.
  477. *
  478. * @access private
  479. * @param string $string
  480. * @return string String with normalized entities
  481. * @since PHP4 OOP 0.0.1
  482. */
  483. private function normalizeEntities($string)
  484. {
  485. # Disarm all entities by converting & to &amp;
  486. $string = str_replace('&', '&amp;', $string);
  487. # TODO: Change back (Keep?) the allowed entities in our entity white list
  488. # Keeps entities that start with [A-Za-z]
  489. $string = preg_replace(
  490. '/&amp;([A-Za-z][A-Za-z0-9]{0,19});/',
  491. '&\\1;',
  492. $string
  493. );
  494. # Change numeric entities to valid 16 bit values
  495. $string = preg_replace(
  496. '/&amp;#0*([0-9]{1,5});/e',
  497. '\$this->normalizeEntities16bit("\\1")',
  498. $string
  499. );
  500. # Change &XHHHHHHH (Hex digits) to 16 bit hex values
  501. $string = preg_replace(
  502. '/&amp;#([Xx])0*(([0-9A-Fa-f]{2}){1,2});/',
  503. '&#\\1\\2;',
  504. $string
  505. );
  506. return $string;
  507. }
  508. /**
  509. * Helper method used by normalizeEntites()
  510. *
  511. * This method helps normalizeEntities() to only accept 16 bit values
  512. * and nothing more for &#number; entities.
  513. *
  514. * This method helps normalize_entities() during a preg_replace()
  515. * where a &#(0)*XXXXX; occurs. The '(0)*XXXXXX' value is converted to
  516. * a number and the result is returned as a numeric entity if the number
  517. * is less than 65536. Otherwise, the value is returned 'as is'.
  518. *
  519. * @access private
  520. * @param string $i
  521. * @return string Normalized numeric entity
  522. * @see normalizeEntities()
  523. * @since PHP4 OOP 0.0.1
  524. */
  525. private function normalizeEntities16bit($i)
  526. {
  527. return (($i > 65535) ? "&amp;#$i;" : "&#$i;");
  528. }
  529. /**
  530. * Allows for additional user defined modifications to text.
  531. *
  532. * This method allows for additional modifications to be performed on
  533. * a string that's being run through Parse(). Currently, it returns the
  534. * input string 'as is'.
  535. *
  536. * This method is provided for users to extend the kses class for their own
  537. * requirements.
  538. *
  539. * @access public
  540. * @param string $string String to perfrom additional modifications on.
  541. * @return string User modified string.
  542. * @see Parse()
  543. * @since PHP5 OOP 1.0.0
  544. */
  545. private function filterKsesTextHook($string)
  546. {
  547. return $string;
  548. }
  549. /**
  550. * Allows for additional user defined modifications to text.
  551. *
  552. * @deprecated use filterKsesTextHook()
  553. * @param string $string
  554. * @return string
  555. * @see filterKsesTextHook()
  556. * @since PHP4 OOP 0.0.1
  557. */
  558. private function _hook($string)
  559. {
  560. return $this->filterKsesTextHook($string);
  561. }
  562. /**
  563. * This method goes through an array, and changes the keys to all lower case.
  564. *
  565. * @access private
  566. * @param array $in_array Associative array
  567. * @return array Modified array
  568. * @since PHP4 OOP 0.0.1
  569. */
  570. private function makeArrayKeysLowerCase($in_array)
  571. {
  572. $out_array = array();
  573. if(is_array($in_array) && count($in_array) > 0)
  574. {
  575. foreach ($in_array as $in_key => $in_val)
  576. {
  577. $out_key = strtolower($in_key);
  578. $out_array[$out_key] = array();
  579. if(is_array($in_val) && count($in_val) > 0)
  580. {
  581. foreach ($in_val as $in_key2 => $in_val2)
  582. {
  583. $out_key2 = strtolower($in_key2);
  584. $out_array[$out_key][$out_key2] = $in_val2;
  585. }
  586. }
  587. }
  588. }
  589. return $out_array;
  590. }
  591. /**
  592. * This method strips out disallowed and/or mangled (X)HTML tags along with assigned attributes.
  593. *
  594. * This method does a lot of work. It rejects some very malformed things
  595. * like <:::>. It returns an empty string if the element isn't allowed (look
  596. * ma, no strip_tags()!). Otherwise it splits the tag into an element and an
  597. * allowed attribute list.
  598. *
  599. * @access private
  600. * @param string $string
  601. * @return string Modified string minus disallowed/mangled (X)HTML and attributes
  602. * @since PHP4 OOP 0.0.1
  603. */
  604. private function stripTags($string)
  605. {
  606. $string = preg_replace('%\\\\"%', '"', $string);
  607. if (substr($string, 0, 1) != '<')
  608. {
  609. # It matched a ">" character
  610. return '&gt;';
  611. }
  612. if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches))
  613. {
  614. # It's seriously malformed
  615. return '';
  616. }
  617. $slash = trim($matches[1]);
  618. $elem = $matches[2];
  619. $attrlist = $matches[3];
  620. if (
  621. !isset($this->allowed_html[strtolower($elem)]) ||
  622. !is_array($this->allowed_html[strtolower($elem)]))
  623. {
  624. # Found an HTML element not in the white list
  625. return '';
  626. }
  627. if ($slash != '')
  628. {
  629. return "<$slash$elem>";
  630. }
  631. # No attributes are allowed for closing elements
  632. return $this->stripAttributes("$slash$elem", $attrlist);
  633. }
  634. /**
  635. * This method strips out disallowed attributes for (X)HTML tags.
  636. *
  637. * This method removes all attributes if none are allowed for this element.
  638. * If some are allowed it calls combAttributes() to split them further, and then it
  639. * builds up new HTML code from the data that combAttributes() returns. It also
  640. * removes "<" and ">" characters, if there are any left. One more thing it
  641. * does is to check if the tag has a closing XHTML slash, and if it does,
  642. * it puts one in the returned code as well.
  643. *
  644. * @access private
  645. * @param string $element (X)HTML tag to check
  646. * @param string $attr Text containing attributes to check for validity.
  647. * @return string Resulting valid (X)HTML or ''
  648. * @see combAttributes()
  649. * @since PHP4 OOP 0.0.1
  650. */
  651. private function stripAttributes($element, $attr)
  652. {
  653. # Is there a closing XHTML slash at the end of the attributes?
  654. $xhtml_slash = '';
  655. if (preg_match('%\s/\s*$%', $attr))
  656. {
  657. $xhtml_slash = ' /';
  658. }
  659. # Are any attributes allowed at all for this element?
  660. if (
  661. !isset($this->allowed_html[strtolower($element)]) ||
  662. count($this->allowed_html[strtolower($element)]) == 0
  663. )
  664. {
  665. return "<$element$xhtml_slash>";
  666. }
  667. # Split it
  668. $attrarr = $this->combAttributes($attr);
  669. # Go through $attrarr, and save the allowed attributes for this element
  670. # in $attr2
  671. $attr2 = '';
  672. if(is_array($attrarr) && count($attrarr) > 0)
  673. {
  674. foreach ($attrarr as $arreach)
  675. {
  676. if(!isset($this->allowed_html[strtolower($element)][strtolower($arreach['name'])]))
  677. {
  678. continue;
  679. }
  680. $current = $this->allowed_html[strtolower($element)][strtolower($arreach['name'])];
  681. if (!is_array($current))
  682. {
  683. # there are no checks
  684. $attr2 .= ' '.$arreach['whole'];
  685. }
  686. else
  687. {
  688. # there are some checks
  689. $ok = true;
  690. if(is_array($current) && count($current) > 0)
  691. {
  692. foreach ($current as $currkey => $currval)
  693. {
  694. if (!$this->checkAttributeValue($arreach['value'], $arreach['vless'], $currkey, $currval))
  695. {
  696. $ok = false;
  697. break;
  698. }
  699. }
  700. }
  701. if ($ok)
  702. {
  703. # it passed them
  704. $attr2 .= ' '.$arreach['whole'];
  705. }
  706. }
  707. }
  708. }
  709. # Remove any "<" or ">" characters
  710. $attr2 = preg_replace('/[<>]/', '', $attr2);
  711. return "<$element$attr2$xhtml_slash>";
  712. }
  713. /**
  714. * This method combs through an attribute list string and returns an associative array of attributes and values.
  715. *
  716. * This method does a lot of work. It parses an attribute list into an array
  717. * with attribute data, and tries to do the right thing even if it gets weird
  718. * input. It will add quotes around attribute values that don't have any quotes
  719. * or apostrophes around them, to make it easier to produce HTML code that will
  720. * conform to W3C's HTML specification. It will also remove bad URL protocols
  721. * from attribute values.
  722. *
  723. * @access private
  724. * @param string $attr Text containing tag attributes for parsing
  725. * @return array Associative array containing data on attribute and value
  726. * @since PHP4 OOP 0.0.1
  727. */
  728. private function combAttributes($attr)
  729. {
  730. $attrarr = array();
  731. $mode = 0;
  732. $attrname = '';
  733. # Loop through the whole attribute list
  734. while (strlen($attr) != 0)
  735. {
  736. # Was the last operation successful?
  737. $working = 0;
  738. switch ($mode)
  739. {
  740. case 0: # attribute name, href for instance
  741. if (preg_match('/^([-a-zA-Z]+)/', $attr, $match))
  742. {
  743. $attrname = $match[1];
  744. $working = $mode = 1;
  745. $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
  746. }
  747. break;
  748. case 1: # equals sign or valueless ("selected")
  749. if (preg_match('/^\s*=\s*/', $attr)) # equals sign
  750. {
  751. $working = 1;
  752. $mode = 2;
  753. $attr = preg_replace('/^\s*=\s*/', '', $attr);
  754. break;
  755. }
  756. if (preg_match('/^\s+/', $attr)) # valueless
  757. {
  758. $working = 1;
  759. $mode = 0;
  760. $attrarr[] = array(
  761. 'name' => $attrname,
  762. 'value' => '',
  763. 'whole' => $attrname,
  764. 'vless' => 'y'
  765. );
  766. $attr = preg_replace('/^\s+/', '', $attr);
  767. }
  768. break;
  769. case 2: # attribute value, a URL after href= for instance
  770. if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) # "value"
  771. {
  772. $thisval = $this->removeBadProtocols($match[1]);
  773. $attrarr[] = array(
  774. 'name' => $attrname,
  775. 'value' => $thisval,
  776. 'whole' => $attrname . '="' . $thisval . '"',
  777. 'vless' => 'n'
  778. );
  779. $working = 1;
  780. $mode = 0;
  781. $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
  782. break;
  783. }
  784. if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match)) # 'value'
  785. {
  786. $thisval = $this->removeBadProtocols($match[1]);
  787. $attrarr[] = array(
  788. 'name' => $attrname,
  789. 'value' => $thisval,
  790. 'whole' => "$attrname='$thisval'",
  791. 'vless' => 'n'
  792. );
  793. $working = 1;
  794. $mode = 0;
  795. $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
  796. break;
  797. }
  798. if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match)) # value
  799. {
  800. $thisval = $this->removeBadProtocols($match[1]);
  801. $attrarr[] = array(
  802. 'name' => $attrname,
  803. 'value' => $thisval,
  804. 'whole' => $attrname . '="' . $thisval . '"',
  805. 'vless' => 'n'
  806. );
  807. # We add quotes to conform to W3C's HTML spec.
  808. $working = 1;
  809. $mode = 0;
  810. $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
  811. }
  812. break;
  813. }
  814. if ($working == 0) # not well formed, remove and try again
  815. {
  816. $attr = preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $attr);
  817. $mode = 0;
  818. }
  819. }
  820. # special case, for when the attribute list ends with a valueless
  821. # attribute like "selected"
  822. if ($mode == 1)
  823. {
  824. $attrarr[] = array(
  825. 'name' => $attrname,
  826. 'value' => '',
  827. 'whole' => $attrname,
  828. 'vless' => 'y'
  829. );
  830. }
  831. return $attrarr;
  832. }
  833. /**
  834. * This method removes disallowed protocols.
  835. *
  836. * This method removes all non-allowed protocols from the beginning of
  837. * $string. It ignores whitespace and the case of the letters, and it does
  838. * understand HTML entities. It does its work in a while loop, so it won't be
  839. * fooled by a string like "javascript:javascript:alert(57)".
  840. *
  841. * @access private
  842. * @param string $string String to check for protocols
  843. * @return string String with removed protocols
  844. * @since PHP4 OOP 0.0.1
  845. */
  846. private function removeBadProtocols($string)
  847. {
  848. $string = $this->RemoveNulls($string);
  849. $string = preg_replace('/\xad+/', '', $string); # deals with Opera "feature"
  850. $string2 = $string . 'a';
  851. $string2 = preg_split('/:|&#58;|&#x3a;/i', $string, 2);
  852. if(isset($string2[1]) && !preg_match('%/\?%',$string2[0]))
  853. {
  854. $string = $this->filterProtocols($string2[0]).trim($string2[1]);
  855. }
  856. return $string;
  857. }
  858. /**
  859. * Helper method used by removeBadProtocols()
  860. *
  861. * This function processes URL protocols, checks to see if they're in the white-
  862. * list or not, and returns different data depending on the answer.
  863. *
  864. * @access private
  865. * @param string $string String to check for protocols
  866. * @return string String with removed protocols
  867. * @see removeBadProtocols()
  868. * @since PHP4 OOP 0.0.1
  869. */
  870. private function filterProtocols($string)
  871. {
  872. $string = $this->decodeEntities($string);
  873. $string = preg_replace('/\s/', '', $string);
  874. $string = $this->removeNulls($string);
  875. $string = preg_replace('/\xad+/', '', $string2); # deals with Opera "feature"
  876. $string = strtolower($string);
  877. if(is_array($this->allowed_protocols) && count($this->allowed_protocols) > 0)
  878. {
  879. foreach ($this->allowed_protocols as $one_protocol)
  880. {
  881. if (strtolower($one_protocol) == $string)
  882. {
  883. return "$string:";
  884. }
  885. }
  886. }
  887. return '';
  888. }
  889. /**
  890. * Controller method for performing checks on attribute values.
  891. *
  892. * This method calls the appropriate method as specified by $checkname with
  893. * the parameters $value, $vless, and $checkvalue, and returns the result
  894. * of the call.
  895. *
  896. * This method's functionality can be expanded by creating new methods
  897. * that would match checkAttributeValue[$checkname].
  898. *
  899. * Current checks implemented are: "maxlen", "minlen", "maxval", "minval" and "valueless"
  900. *
  901. * @access private
  902. * @param string $value The value of the attribute to be checked.
  903. * @param string $vless Indicates whether the the value is supposed to be valueless
  904. * @param string $checkname The check to be performed
  905. * @param string $checkvalue The value that is to be checked against
  906. * @return bool Indicates whether the check passed or not
  907. * @since PHP5 OOP 1.0.0
  908. */
  909. private function checkAttributeValue($value, $vless, $checkname, $checkvalue)
  910. {
  911. $ok = true;
  912. $check_attribute_method_name = 'checkAttributeValue' . ucfirst(strtolower($checkname));
  913. if(method_exists($this, $check_attribute_method_name))
  914. {
  915. $ok = $this->$check_attribute_method_name($value, $checkvalue, $vless);
  916. }
  917. return $ok;
  918. }
  919. /**
  920. * Helper method invoked by checkAttributeValue().
  921. *
  922. * The maxlen check makes sure that the attribute value has a length not
  923. * greater than the given value. This can be used to avoid Buffer Overflows
  924. * in WWW clients and various Internet servers.
  925. *
  926. * @access private
  927. * @param string $value The value of the attribute to be checked.
  928. * @param int $checkvalue The maximum value allowed
  929. * @return bool Indicates whether the check passed or not
  930. * @see checkAttributeValue()
  931. * @since PHP5 OOP 1.0.0
  932. */
  933. private function checkAttributeValueMaxlen($value, $checkvalue)
  934. {
  935. if (strlen($value) > intval($checkvalue))
  936. {
  937. return false;
  938. }
  939. return true;
  940. }
  941. /**
  942. * Helper method invoked by checkAttributeValue().
  943. *
  944. * The minlen check makes sure that the attribute value has a length not
  945. * smaller than the given value.
  946. *
  947. * @access private
  948. * @param string $value The value of the attribute to be checked.
  949. * @param int $checkvalue The minimum value allowed
  950. * @return bool Indicates whether the check passed or not
  951. * @see checkAttributeValue()
  952. * @since PHP5 OOP 1.0.0
  953. */
  954. private function checkAttributeValueMinlen($value, $checkvalue)
  955. {
  956. if (strlen($value) < intval($checkvalue))
  957. {
  958. return false;
  959. }
  960. return true;
  961. }
  962. /**
  963. * Helper method invoked by checkAttributeValue().
  964. *
  965. * The maxval check does two things: it checks that the attribute value is
  966. * an integer from 0 and up, without an excessive amount of zeroes or
  967. * whitespace (to avoid Buffer Overflows). It also checks that the attribute
  968. * value is not greater than the given value.
  969. *
  970. * This check can be used to avoid Denial of Service attacks.
  971. *
  972. * @access private
  973. * @param int $value The value of the attribute to be checked.
  974. * @param int $checkvalue The maximum numeric value allowed
  975. * @return bool Indicates whether the check passed or not
  976. * @see checkAttributeValue()
  977. * @since PHP5 OOP 1.0.0
  978. */
  979. private function checkAttributeValueMaxval($value, $checkvalue)
  980. {
  981. if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
  982. {
  983. return false;
  984. }
  985. if (intval($value) > intval($checkvalue))
  986. {
  987. return false;
  988. }
  989. return true;
  990. }
  991. /**
  992. * Helper method invoked by checkAttributeValue().
  993. *
  994. * The minval check checks that the attribute value is a positive integer,
  995. * and that it is not smaller than the given value.
  996. *
  997. * @access private
  998. * @param int $value The value of the attribute to be checked.
  999. * @param int $checkvalue The minimum numeric value allowed
  1000. * @return bool Indicates whether the check passed or not
  1001. * @see checkAttributeValue()
  1002. * @since PHP5 OOP 1.0.0
  1003. */
  1004. private function checkAttributeValueMinval($value, $checkvalue)
  1005. {
  1006. if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
  1007. {
  1008. return false;
  1009. }
  1010. if (intval($value) < ($checkvalue))
  1011. {
  1012. return false;
  1013. }
  1014. return true;
  1015. }
  1016. /**
  1017. * Helper method invoked by checkAttributeValue().
  1018. *
  1019. * The valueless check checks if the attribute has a value
  1020. * (like <a href="blah">) or not (<option selected>). If the given value
  1021. * is a "y" or a "Y", the attribute must not have a value.
  1022. *
  1023. * If the given value is an "n" or an "N", the attribute must have one.
  1024. *
  1025. * @access private
  1026. * @param int $value The value of the attribute to be checked.
  1027. * @param mixed $checkvalue This variable is ignored for this test
  1028. * @param string $vless Flag indicating if this attribute is not supposed to have an attribute
  1029. * @return bool Indicates whether the check passed or not
  1030. * @see checkAttributeValue()
  1031. * @since PHP5 OOP 1.0.0
  1032. */
  1033. private function checkAttributeValueValueless($value, $checkvalue, $vless)
  1034. {
  1035. if (strtolower($checkvalue) != $vless)
  1036. {
  1037. return false;
  1038. }
  1039. return true;
  1040. }
  1041. /**
  1042. * Decodes numeric HTML entities
  1043. *
  1044. * This method decodes numeric HTML entities (&#65; and &#x41;). It doesn't
  1045. * do anything with other entities like &auml;, but we don't need them in the
  1046. * URL protocol white listing system anyway.
  1047. *
  1048. * @access private
  1049. * @param string $value The entitiy to be decoded.
  1050. * @return string Decoded entity
  1051. * @since PHP4 OOP 0.0.1
  1052. */
  1053. private function decodeEntities($string)
  1054. {
  1055. $string = preg_replace('/&#([0-9]+);/e', 'chr("\\1")', $string);
  1056. $string = preg_replace('/&#[Xx]([0-9A-Fa-f]+);/e', 'chr(hexdec("\\1"))', $string);
  1057. return $string;
  1058. }
  1059. /**
  1060. * Returns PHP5 OOP version # of kses.
  1061. *
  1062. * Since this class has been refactored and documented and proven to work,
  1063. * I'm fixing the version number at 1.0.0.
  1064. *
  1065. * This version is syntax compatible with the PHP4 OOP version 0.0.2. Future
  1066. * versions may not be syntax compatible.
  1067. *
  1068. * @access public
  1069. * @return string Version number
  1070. * @since PHP4 OOP 0.0.1
  1071. */
  1072. public function Version()
  1073. {
  1074. return 'PHP5 OOP 1.0.2';
  1075. }
  1076. }
  1077. }
  1078. ?>