Sanitize.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. <?php
  2. /**
  3. * Washes strings from unwanted noise.
  4. *
  5. * Helpful methods to make unsafe strings usable.
  6. *
  7. * PHP 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package Cake.Utility
  18. * @since CakePHP(tm) v 0.10.0.1076
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. App::import('Model', 'ConnectionManager');
  22. /**
  23. * Data Sanitization.
  24. *
  25. * Removal of alphanumeric characters, SQL-safe slash-added strings, HTML-friendly strings,
  26. * and all of the above on arrays.
  27. *
  28. * @package Cake.Utility
  29. */
  30. class Sanitize {
  31. /**
  32. * Removes any non-alphanumeric characters.
  33. *
  34. * @param string $string String to sanitize
  35. * @param array $allowed An array of additional characters that are not to be removed.
  36. * @return string Sanitized string
  37. */
  38. public static function paranoid($string, $allowed = array()) {
  39. $allow = null;
  40. if (!empty($allowed)) {
  41. foreach ($allowed as $value) {
  42. $allow .= "\\$value";
  43. }
  44. }
  45. if (!is_array($string)) {
  46. return preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $string);
  47. }
  48. $cleaned = array();
  49. foreach ($string as $key => $clean) {
  50. $cleaned[$key] = preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $clean);
  51. }
  52. return $cleaned;
  53. }
  54. /**
  55. * Makes a string SQL-safe.
  56. *
  57. * @param string $string String to sanitize
  58. * @param string $connection Database connection being used
  59. * @return string SQL safe string
  60. */
  61. public static function escape($string, $connection = 'default') {
  62. $db = ConnectionManager::getDataSource($connection);
  63. if (is_numeric($string) || $string === null || is_bool($string)) {
  64. return $string;
  65. }
  66. $string = $db->value($string, 'string');
  67. $start = 1;
  68. if ($string{0} === 'N') {
  69. $start = 2;
  70. }
  71. return substr(substr($string, 1), 0, -1);
  72. }
  73. /**
  74. * Returns given string safe for display as HTML. Renders entities.
  75. *
  76. * strip_tags() does not validating HTML syntax or structure, so it might strip whole passages
  77. * with broken HTML.
  78. *
  79. * ### Options:
  80. *
  81. * - remove (boolean) if true strips all HTML tags before encoding
  82. * - charset (string) the charset used to encode the string
  83. * - quotes (int) see http://php.net/manual/en/function.htmlentities.php
  84. * - double (boolean) doube encode html entities
  85. *
  86. * @param string $string String from where to strip tags
  87. * @param array $options Array of options to use.
  88. * @return string Sanitized string
  89. */
  90. public static function html($string, $options = array()) {
  91. static $defaultCharset = false;
  92. if ($defaultCharset === false) {
  93. $defaultCharset = Configure::read('App.encoding');
  94. if ($defaultCharset === null) {
  95. $defaultCharset = 'UTF-8';
  96. }
  97. }
  98. $default = array(
  99. 'remove' => false,
  100. 'charset' => $defaultCharset,
  101. 'quotes' => ENT_QUOTES,
  102. 'double' => true
  103. );
  104. $options = array_merge($default, $options);
  105. if ($options['remove']) {
  106. $string = strip_tags($string);
  107. }
  108. return htmlentities($string, $options['quotes'], $options['charset'], $options['double']);
  109. }
  110. /**
  111. * Strips extra whitespace from output
  112. *
  113. * @param string $str String to sanitize
  114. * @return string whitespace sanitized string
  115. */
  116. public static function stripWhitespace($str) {
  117. return preg_replace('/\s{2,}/u', ' ', preg_replace('/[\n\r\t]+/', '', $str));
  118. }
  119. /**
  120. * Strips image tags from output
  121. *
  122. * @param string $str String to sanitize
  123. * @return string Sting with images stripped.
  124. */
  125. public static function stripImages($str) {
  126. $preg = array(
  127. '/(<a[^>]*>)(<img[^>]+alt=")([^"]*)("[^>]*>)(<\/a>)/i' => '$1$3$5<br />',
  128. '/(<img[^>]+alt=")([^"]*)("[^>]*>)/i' => '$2<br />',
  129. '/<img[^>]*>/i' => ''
  130. );
  131. return preg_replace(array_keys($preg), array_values($preg), $str);
  132. }
  133. /**
  134. * Strips scripts and stylesheets from output
  135. *
  136. * @param string $str String to sanitize
  137. * @return string String with <link>, <img>, <script>, <style> elements and html comments removed.
  138. */
  139. public static function stripScripts($str) {
  140. $regex =
  141. '/(<link[^>]+rel="[^"]*stylesheet"[^>]*>|' .
  142. '<img[^>]*>|style="[^"]*")|' .
  143. '<script[^>]*>.*?<\/script>|' .
  144. '<style[^>]*>.*?<\/style>|' .
  145. '<!--.*?-->/is';
  146. return preg_replace($regex, '', $str);
  147. }
  148. /**
  149. * Strips extra whitespace, images, scripts and stylesheets from output
  150. *
  151. * @param string $str String to sanitize
  152. * @return string sanitized string
  153. */
  154. public static function stripAll($str) {
  155. return Sanitize::stripScripts(
  156. Sanitize::stripImages(
  157. Sanitize::stripWhitespace($str)
  158. )
  159. );
  160. }
  161. /**
  162. * Strips the specified tags from output. First parameter is string from
  163. * where to remove tags. All subsequent parameters are tags.
  164. *
  165. * Ex.`$clean = Sanitize::stripTags($dirty, 'b', 'p', 'div');`
  166. *
  167. * Will remove all `<b>`, `<p>`, and `<div>` tags from the $dirty string.
  168. *
  169. * @param string $str,... String to sanitize
  170. * @return string sanitized String
  171. */
  172. public static function stripTags($str) {
  173. $params = func_get_args();
  174. for ($i = 1, $count = count($params); $i < $count; $i++) {
  175. $str = preg_replace('/<' . $params[$i] . '\b[^>]*>/i', '', $str);
  176. $str = preg_replace('/<\/' . $params[$i] . '[^>]*>/i', '', $str);
  177. }
  178. return $str;
  179. }
  180. /**
  181. * Sanitizes given array or value for safe input. Use the options to specify
  182. * the connection to use, and what filters should be applied (with a boolean
  183. * value). Valid filters:
  184. *
  185. * - odd_spaces - removes any non space whitespace characters
  186. * - encode - Encode any html entities. Encode must be true for the `remove_html` to work.
  187. * - dollar - Escape `$` with `\$`
  188. * - carriage - Remove `\r`
  189. * - unicode -
  190. * - escape - Should the string be SQL escaped.
  191. * - backslash -
  192. * - remove_html - Strip HTML with strip_tags. `encode` must be true for this option to work.
  193. *
  194. * @param string|array $data Data to sanitize
  195. * @param string|array $options If string, DB connection being used, otherwise set of options
  196. * @return mixed Sanitized data
  197. */
  198. public static function clean($data, $options = array()) {
  199. if (empty($data)) {
  200. return $data;
  201. }
  202. if (!is_array($options)) {
  203. $options = array('connection' => $options);
  204. }
  205. $options = array_merge(array(
  206. 'connection' => 'default',
  207. 'odd_spaces' => true,
  208. 'remove_html' => false,
  209. 'encode' => true,
  210. 'dollar' => true,
  211. 'carriage' => true,
  212. 'unicode' => true,
  213. 'escape' => true,
  214. 'backslash' => true
  215. ), $options);
  216. if (is_array($data)) {
  217. foreach ($data as $key => $val) {
  218. $data[$key] = Sanitize::clean($val, $options);
  219. }
  220. return $data;
  221. }
  222. if ($options['odd_spaces']) {
  223. $data = str_replace(chr(0xCA), '', $data);
  224. }
  225. if ($options['encode']) {
  226. $data = Sanitize::html($data, array('remove' => $options['remove_html']));
  227. }
  228. if ($options['dollar']) {
  229. $data = str_replace("\\\$", "$", $data);
  230. }
  231. if ($options['carriage']) {
  232. $data = str_replace("\r", "", $data);
  233. }
  234. if ($options['unicode']) {
  235. $data = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $data);
  236. }
  237. if ($options['escape']) {
  238. $data = Sanitize::escape($data, $options['connection']);
  239. }
  240. if ($options['backslash']) {
  241. $data = preg_replace("/\\\(?!&amp;#|\?#)/", "\\", $data);
  242. }
  243. return $data;
  244. }
  245. }