Sanitize.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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-2011, 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-2011, 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. $cleaned = array();
  47. foreach ($string as $key => $clean) {
  48. $cleaned[$key] = preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $clean);
  49. }
  50. } else {
  51. $cleaned = preg_replace("/[^{$allow}a-zA-Z0-9]/", '', $string);
  52. }
  53. return $cleaned;
  54. }
  55. /**
  56. * Makes a string SQL-safe.
  57. *
  58. * @param string $string String to sanitize
  59. * @param string $connection Database connection being used
  60. * @return string SQL safe string
  61. */
  62. public static function escape($string, $connection = 'default') {
  63. $db = ConnectionManager::getDataSource($connection);
  64. if (is_numeric($string) || $string === null || is_bool($string)) {
  65. return $string;
  66. }
  67. $string = $db->value($string, 'string');
  68. if ($string[0] === 'N') {
  69. $string = substr($string, 2);
  70. } else {
  71. $string = substr($string, 1);
  72. }
  73. $string = substr($string, 0, -1);
  74. return $string;
  75. }
  76. /**
  77. * Returns given string safe for display as HTML. Renders entities.
  78. *
  79. * strip_tags() does not validating HTML syntax or structure, so it might strip whole passages
  80. * with broken HTML.
  81. *
  82. * ### Options:
  83. *
  84. * - remove (boolean) if true strips all HTML tags before encoding
  85. * - charset (string) the charset used to encode the string
  86. * - quotes (int) see http://php.net/manual/en/function.htmlentities.php
  87. * - double (boolean) doube encode html entities
  88. *
  89. * @param string $string String from where to strip tags
  90. * @param array $options Array of options to use.
  91. * @return string Sanitized string
  92. */
  93. public static function html($string, $options = array()) {
  94. static $defaultCharset = false;
  95. if ($defaultCharset === false) {
  96. $defaultCharset = Configure::read('App.encoding');
  97. if ($defaultCharset === null) {
  98. $defaultCharset = 'UTF-8';
  99. }
  100. }
  101. $default = array(
  102. 'remove' => false,
  103. 'charset' => $defaultCharset,
  104. 'quotes' => ENT_QUOTES,
  105. 'double' => true
  106. );
  107. $options = array_merge($default, $options);
  108. if ($options['remove']) {
  109. $string = strip_tags($string);
  110. }
  111. return htmlentities($string, $options['quotes'], $options['charset'], $options['double']);
  112. }
  113. /**
  114. * Strips extra whitespace from output
  115. *
  116. * @param string $str String to sanitize
  117. * @return string whitespace sanitized string
  118. */
  119. public static function stripWhitespace($str) {
  120. $r = preg_replace('/[\n\r\t]+/', '', $str);
  121. return preg_replace('/\s{2,}/u', ' ', $r);
  122. }
  123. /**
  124. * Strips image tags from output
  125. *
  126. * @param string $str String to sanitize
  127. * @return string Sting with images stripped.
  128. */
  129. public static function stripImages($str) {
  130. $str = preg_replace('/(<a[^>]*>)(<img[^>]+alt=")([^"]*)("[^>]*>)(<\/a>)/i', '$1$3$5<br />', $str);
  131. $str = preg_replace('/(<img[^>]+alt=")([^"]*)("[^>]*>)/i', '$2<br />', $str);
  132. $str = preg_replace('/<img[^>]*>/i', '', $str);
  133. return $str;
  134. }
  135. /**
  136. * Strips scripts and stylesheets from output
  137. *
  138. * @param string $str String to sanitize
  139. * @return string String with <script>, <style>, <link>, <img> elements removed.
  140. */
  141. public static function stripScripts($str) {
  142. return preg_replace('/(<link[^>]+rel="[^"]*stylesheet"[^>]*>|<img[^>]*>|style="[^"]*")|<script[^>]*>.*?<\/script>|<style[^>]*>.*?<\/style>|<!--.*?-->/is', '', $str);
  143. }
  144. /**
  145. * Strips extra whitespace, images, scripts and stylesheets from output
  146. *
  147. * @param string $str String to sanitize
  148. * @return string sanitized string
  149. */
  150. public static function stripAll($str) {
  151. $str = Sanitize::stripWhitespace($str);
  152. $str = Sanitize::stripImages($str);
  153. $str = Sanitize::stripScripts($str);
  154. return $str;
  155. }
  156. /**
  157. * Strips the specified tags from output. First parameter is string from
  158. * where to remove tags. All subsequent parameters are tags.
  159. *
  160. * Ex.`$clean = Sanitize::stripTags($dirty, 'b', 'p', 'div');`
  161. *
  162. * Will remove all `<b>`, `<p>`, and `<div>` tags from the $dirty string.
  163. *
  164. * @param string $str,... String to sanitize
  165. * @return string sanitized String
  166. */
  167. public static function stripTags($str) {
  168. $params = func_get_args();
  169. for ($i = 1, $count = count($params); $i < $count; $i++) {
  170. $str = preg_replace('/<' . $params[$i] . '\b[^>]*>/i', '', $str);
  171. $str = preg_replace('/<\/' . $params[$i] . '[^>]*>/i', '', $str);
  172. }
  173. return $str;
  174. }
  175. /**
  176. * Sanitizes given array or value for safe input. Use the options to specify
  177. * the connection to use, and what filters should be applied (with a boolean
  178. * value). Valid filters:
  179. *
  180. * - odd_spaces - removes any non space whitespace characters
  181. * - encode - Encode any html entities. Encode must be true for the `remove_html` to work.
  182. * - dollar - Escape `$` with `\$`
  183. * - carriage - Remove `\r`
  184. * - unicode -
  185. * - escape - Should the string be SQL escaped.
  186. * - backslash -
  187. * - remove_html - Strip HTML with strip_tags. `encode` must be true for this option to work.
  188. *
  189. * @param mixed $data Data to sanitize
  190. * @param mixed $options If string, DB connection being used, otherwise set of options
  191. * @return mixed Sanitized data
  192. */
  193. public static function clean($data, $options = array()) {
  194. if (empty($data)) {
  195. return $data;
  196. }
  197. if (is_string($options)) {
  198. $options = array('connection' => $options);
  199. } else if (!is_array($options)) {
  200. $options = array();
  201. }
  202. $options = array_merge(array(
  203. 'connection' => 'default',
  204. 'odd_spaces' => true,
  205. 'remove_html' => false,
  206. 'encode' => true,
  207. 'dollar' => true,
  208. 'carriage' => true,
  209. 'unicode' => true,
  210. 'escape' => true,
  211. 'backslash' => true
  212. ), $options);
  213. if (is_array($data)) {
  214. foreach ($data as $key => $val) {
  215. $data[$key] = Sanitize::clean($val, $options);
  216. }
  217. return $data;
  218. } else {
  219. if ($options['odd_spaces']) {
  220. $data = str_replace(chr(0xCA), '', $data);
  221. }
  222. if ($options['encode']) {
  223. $data = Sanitize::html($data, array('remove' => $options['remove_html']));
  224. }
  225. if ($options['dollar']) {
  226. $data = str_replace("\\\$", "$", $data);
  227. }
  228. if ($options['carriage']) {
  229. $data = str_replace("\r", "", $data);
  230. }
  231. if ($options['unicode']) {
  232. $data = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $data);
  233. }
  234. if ($options['escape']) {
  235. $data = Sanitize::escape($data, $options['connection']);
  236. }
  237. if ($options['backslash']) {
  238. $data = preg_replace("/\\\(?!&amp;#|\?#)/", "\\", $data);
  239. }
  240. return $data;
  241. }
  242. }
  243. }