php4.class.kses.php 33 KB

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