PageRenderTime 49ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Utility/Sanitize.php

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