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