1 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
5 * An open source application development framework for PHP 5.1.6 or newer
8 * @author ExpressionEngine Dev Team
9 * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
10 * @license http://codeigniter.com/user_guide/license.html
11 * @link http://codeigniter.com
16 // ------------------------------------------------------------------------
21 * Pre-processes global input data for security
23 * @package CodeIgniter
24 * @subpackage Libraries
26 * @author ExpressionEngine Dev Team
27 * @link http://codeigniter.com/user_guide/libraries/input.html
31 var $ip_address = FALSE;
32 var $user_agent = FALSE;
33 var $_allow_get_array = TRUE;
34 var $_standardize_newlines = TRUE;
35 var $_enable_xss = FALSE; // Set automatically based on config setting
36 var $_enable_csrf = FALSE; // Set automatically based on config setting
38 protected $headers = array();
44 * Sets whether to globally enable the XSS processing
45 * and whether to allow the $_GET array
48 public function __construct()
50 log_message('debug', "Input Class Initialized");
52 $this->_allow_get_array = (config_item('allow_get_array') === TRUE);
53 $this->_enable_xss = (config_item('global_xss_filtering') === TRUE);
54 $this->_enable_csrf = (config_item('csrf_protection') === TRUE);
57 $this->security =& $SEC;
59 // Do we need the UTF-8 class?
60 if (UTF8_ENABLED === TRUE)
66 // Sanitize global arrays
67 $this->_sanitize_globals();
70 // --------------------------------------------------------------------
75 * This is a helper function to retrieve values from global arrays
83 function _fetch_from_array(&$array, $index = '', $xss_clean = FALSE)
85 if ( ! isset($array[$index]))
90 if ($xss_clean === TRUE)
92 return $this->security->xss_clean($array[$index]);
95 return $array[$index];
98 // --------------------------------------------------------------------
101 * Fetch an item from the GET array
108 function get($index = NULL, $xss_clean = FALSE)
110 // Check if a field has been provided
111 if ($index === NULL AND ! empty($_GET))
115 // loop through the full _GET array
116 foreach (array_keys($_GET) as $key)
118 $get[$key] = $this->_fetch_from_array($_GET, $key, $xss_clean);
123 return $this->_fetch_from_array($_GET, $index, $xss_clean);
126 // --------------------------------------------------------------------
129 * Fetch an item from the POST array
136 function post($index = NULL, $xss_clean = FALSE)
138 // Check if a field has been provided
139 if ($index === NULL AND ! empty($_POST))
143 // Loop through the full _POST array and return it
144 foreach (array_keys($_POST) as $key)
146 $post[$key] = $this->_fetch_from_array($_POST, $key, $xss_clean);
151 return $this->_fetch_from_array($_POST, $index, $xss_clean);
155 // --------------------------------------------------------------------
158 * Fetch an item from either the GET array or the POST
161 * @param string The index key
162 * @param bool XSS cleaning
165 function get_post($index = '', $xss_clean = FALSE)
167 if ( ! isset($_POST[$index]) )
169 return $this->get($index, $xss_clean);
173 return $this->post($index, $xss_clean);
177 // --------------------------------------------------------------------
180 * Fetch an item from the COOKIE array
187 function cookie($index = '', $xss_clean = FALSE)
189 return $this->_fetch_from_array($_COOKIE, $index, $xss_clean);
192 // ------------------------------------------------------------------------
197 * Accepts six parameter, or you can submit an associative
198 * array in the first parameter containing all the values.
202 * @param string the value of the cookie
203 * @param string the number of seconds until expiration
204 * @param string the cookie domain. Usually: .yourdomain.com
205 * @param string the cookie path
206 * @param string the cookie prefix
207 * @param bool true makes the cookie secure
210 function set_cookie($name = '', $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE)
214 // always leave 'name' in last place, as the loop will break otherwise, due to $$item
215 foreach (array('value', 'expire', 'domain', 'path', 'prefix', 'secure', 'name') as $item)
217 if (isset($name[$item]))
219 $$item = $name[$item];
224 if ($prefix == '' AND config_item('cookie_prefix') != '')
226 $prefix = config_item('cookie_prefix');
228 if ($domain == '' AND config_item('cookie_domain') != '')
230 $domain = config_item('cookie_domain');
232 if ($path == '/' AND config_item('cookie_path') != '/')
234 $path = config_item('cookie_path');
236 if ($secure == FALSE AND config_item('cookie_secure') != FALSE)
238 $secure = config_item('cookie_secure');
241 if ( ! is_numeric($expire))
243 $expire = time() - 86500;
247 $expire = ($expire > 0) ? time() + $expire : 0;
250 setcookie($prefix.$name, $value, $expire, $path, $domain, $secure);
253 // --------------------------------------------------------------------
256 * Fetch an item from the SERVER array
263 function server($index = '', $xss_clean = FALSE)
265 return $this->_fetch_from_array($_SERVER, $index, $xss_clean);
268 // --------------------------------------------------------------------
271 * Fetch the IP Address
276 function ip_address()
278 if ($this->ip_address !== FALSE)
280 return $this->ip_address;
283 if (config_item('proxy_ips') != '' && $this->server('HTTP_X_FORWARDED_FOR') && $this->server('REMOTE_ADDR'))
285 $proxies = preg_split('/[\s,]/', config_item('proxy_ips'), -1, PREG_SPLIT_NO_EMPTY);
286 $proxies = is_array($proxies) ? $proxies : array($proxies);
288 $this->ip_address = in_array($_SERVER['REMOTE_ADDR'], $proxies) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
290 elseif ($this->server('REMOTE_ADDR') AND $this->server('HTTP_CLIENT_IP'))
292 $this->ip_address = $_SERVER['HTTP_CLIENT_IP'];
294 elseif ($this->server('REMOTE_ADDR'))
296 $this->ip_address = $_SERVER['REMOTE_ADDR'];
298 elseif ($this->server('HTTP_CLIENT_IP'))
300 $this->ip_address = $_SERVER['HTTP_CLIENT_IP'];
302 elseif ($this->server('HTTP_X_FORWARDED_FOR'))
304 $this->ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
307 if ($this->ip_address === FALSE)
309 $this->ip_address = '0.0.0.0';
310 return $this->ip_address;
313 if (strpos($this->ip_address, ',') !== FALSE)
315 $x = explode(',', $this->ip_address);
316 $this->ip_address = trim(end($x));
319 if ( ! $this->valid_ip($this->ip_address))
321 $this->ip_address = '0.0.0.0';
324 return $this->ip_address;
327 // --------------------------------------------------------------------
330 * Validate IP Address
332 * Updated version suggested by Geert De Deckere
338 function valid_ip($ip)
340 $ip_segments = explode('.', $ip);
342 // Always 4 segments needed
343 if (count($ip_segments) != 4)
347 // IP can not start with 0
348 if ($ip_segments[0][0] == '0')
352 // Check each segment
353 foreach ($ip_segments as $segment)
355 // IP segments must be digits and can not be
356 // longer than 3 digits or greater then 255
357 if ($segment == '' OR preg_match("/[^0-9]/", $segment) OR $segment > 255 OR strlen($segment) > 3)
366 // --------------------------------------------------------------------
374 function user_agent()
376 if ($this->user_agent !== FALSE)
378 return $this->user_agent;
381 $this->user_agent = ( ! isset($_SERVER['HTTP_USER_AGENT'])) ? FALSE : $_SERVER['HTTP_USER_AGENT'];
383 return $this->user_agent;
386 // --------------------------------------------------------------------
391 * This function does the following:
393 * Unsets $_GET data (if query strings are not enabled)
395 * Unsets all globals if register_globals is enabled
397 * Standardizes newline characters to \n
402 function _sanitize_globals()
404 // It would be "wrong" to unset any of these GLOBALS.
405 $protected = array('_SERVER', '_GET', '_POST', '_FILES', '_REQUEST',
406 '_SESSION', '_ENV', 'GLOBALS', 'HTTP_RAW_POST_DATA',
407 'system_folder', 'application_folder', 'BM', 'EXT',
408 'CFG', 'URI', 'RTR', 'OUT', 'IN');
410 // Unset globals for securiy.
411 // This is effectively the same as register_globals = off
412 foreach (array($_GET, $_POST, $_COOKIE) as $global)
414 if ( ! is_array($global))
416 if ( ! in_array($global, $protected))
424 foreach ($global as $key => $val)
426 if ( ! in_array($key, $protected))
435 // Is $_GET data allowed? If not we'll set the $_GET to an empty array
436 if ($this->_allow_get_array == FALSE)
442 if (is_array($_GET) AND count($_GET) > 0)
444 foreach ($_GET as $key => $val)
446 $_GET[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
452 if (is_array($_POST) AND count($_POST) > 0)
454 foreach ($_POST as $key => $val)
456 $_POST[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
460 // Clean $_COOKIE Data
461 if (is_array($_COOKIE) AND count($_COOKIE) > 0)
463 // Also get rid of specially treated cookies that might be set by a server
464 // or silly application, that are of no use to a CI application anyway
465 // but that when present will trip our 'Disallowed Key Characters' alarm
466 // http://www.ietf.org/rfc/rfc2109.txt
467 // note that the key names below are single quoted strings, and are not PHP variables
468 unset($_COOKIE['$Version']);
469 unset($_COOKIE['$Path']);
470 unset($_COOKIE['$Domain']);
472 foreach ($_COOKIE as $key => $val)
474 $_COOKIE[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
479 $_SERVER['PHP_SELF'] = strip_tags($_SERVER['PHP_SELF']);
482 // CSRF Protection check
483 if ($this->_enable_csrf == TRUE)
485 $this->security->csrf_verify();
488 log_message('debug', "Global POST and COOKIE data sanitized");
491 // --------------------------------------------------------------------
496 * This is a helper function. It escapes data and
497 * standardizes newline characters to \n
503 function _clean_input_data($str)
507 $new_array = array();
508 foreach ($str as $key => $val)
510 $new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
515 // We strip slashes if magic quotes is on to keep things consistent
516 if (function_exists('get_magic_quotes_gpc') AND get_magic_quotes_gpc())
518 $str = stripslashes($str);
521 // Clean UTF-8 if supported
522 if (UTF8_ENABLED === TRUE)
524 $str = $this->uni->clean_string($str);
527 // Remove control characters
528 $str = remove_invisible_characters($str);
530 // Should we filter the input data?
531 if ($this->_enable_xss === TRUE)
533 $str = $this->security->xss_clean($str);
536 // Standardize newlines if needed
537 if ($this->_standardize_newlines == TRUE)
539 if (strpos($str, "\r") !== FALSE)
541 $str = str_replace(array("\r\n", "\r", "\r\n\n"), PHP_EOL, $str);
548 // --------------------------------------------------------------------
553 * This is a helper function. To prevent malicious users
554 * from trying to exploit keys we make sure that keys are
555 * only named with alpha-numeric text and a few other items.
561 function _clean_input_keys($str)
563 if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
565 exit('Disallowed Key Characters.');
568 // Clean UTF-8 if supported
569 if (UTF8_ENABLED === TRUE)
571 $str = $this->uni->clean_string($str);
577 // --------------------------------------------------------------------
582 * In Apache, you can simply call apache_request_headers(), however for
583 * people running other webservers the function is undefined.
587 public function request_headers($xss_clean = FALSE)
589 // Look at Apache go!
590 if (function_exists('apache_request_headers'))
592 $headers = apache_request_headers();
596 $headers['Content-Type'] = (isset($_SERVER['CONTENT_TYPE'])) ? $_SERVER['CONTENT_TYPE'] : @getenv('CONTENT_TYPE');
598 foreach ($_SERVER as $key => $val)
600 if (strncmp($key, 'HTTP_', 5) === 0)
602 $headers[substr($key, 5)] = $this->_fetch_from_array($_SERVER, $key, $xss_clean);
607 // take SOME_HEADER and turn it into Some-Header
608 foreach ($headers as $key => $val)
610 $key = str_replace('_', ' ', strtolower($key));
611 $key = str_replace(' ', '-', ucwords($key));
613 $this->headers[$key] = $val;
616 return $this->headers;
619 // --------------------------------------------------------------------
624 * Returns the value of a single member of the headers class member
626 * @param string array key for $this->headers
627 * @param boolean XSS Clean or not
628 * @return mixed FALSE on failure, string on success
630 public function get_request_header($index, $xss_clean = FALSE)
632 if (empty($this->headers))
634 $this->request_headers();
637 if ( ! isset($this->headers[$index]))
642 if ($xss_clean === TRUE)
644 return $this->security->xss_clean($this->headers[$index]);
647 return $this->headers[$index];
650 // --------------------------------------------------------------------
655 * Test to see if a request contains the HTTP_X_REQUESTED_WITH header
659 public function is_ajax_request()
661 return ($this->server('HTTP_X_REQUESTED_WITH') === 'XMLHttpRequest');
664 // --------------------------------------------------------------------
669 * Test to see if a request was made from the command line
673 public function is_cli_request()
675 return (bool) defined('STDIN');
681 /* End of file Input.php */
682 /* Location: ./system/core/Input.php */