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
32 * IP address of the current user
36 var $ip_address = FALSE;
38 * user agent (web browser) being used by the current user
42 var $user_agent = FALSE;
44 * If FALSE, then $_GET will be set to an empty array
48 var $_allow_get_array = TRUE;
50 * If TRUE, then newlines are standardized
54 var $_standardize_newlines = TRUE;
56 * Determines whether the XSS filter is always active when GET, POST or COOKIE data is encountered
57 * Set automatically based on config setting
61 var $_enable_xss = FALSE;
63 * Enables a CSRF cookie token to be set.
64 * Set automatically based on config setting
68 var $_enable_csrf = FALSE;
70 * List of all HTTP request headers
74 protected $headers = array();
79 * Sets whether to globally enable the XSS processing
80 * and whether to allow the $_GET array
84 public function __construct()
86 log_message('debug', "Input Class Initialized");
88 $this->_allow_get_array
= (config_item('allow_get_array') === TRUE);
89 $this->_enable_xss
= (config_item('global_xss_filtering') === TRUE);
90 $this->_enable_csrf
= (config_item('csrf_protection') === TRUE);
93 $this->security
=& $SEC;
95 // Do we need the UTF-8 class?
96 if (UTF8_ENABLED
=== TRUE)
102 // Sanitize global arrays
103 $this->_sanitize_globals();
106 // --------------------------------------------------------------------
111 * This is a helper function to retrieve values from global arrays
119 function _fetch_from_array(&$array, $index = '', $xss_clean = FALSE)
121 if ( ! isset($array[$index]))
126 if ($xss_clean === TRUE)
128 return $this->security
->xss_clean($array[$index]);
131 return $array[$index];
134 // --------------------------------------------------------------------
137 * Fetch an item from the GET array
144 function get($index = NULL, $xss_clean = FALSE)
146 // Check if a field has been provided
147 if ($index === NULL AND ! empty($_GET))
151 // loop through the full _GET array
152 foreach (array_keys($_GET) as $key)
154 $get[$key] = $this->_fetch_from_array($_GET, $key, $xss_clean);
159 return $this->_fetch_from_array($_GET, $index, $xss_clean);
162 // --------------------------------------------------------------------
165 * Fetch an item from the POST array
172 function post($index = NULL, $xss_clean = FALSE)
174 // Check if a field has been provided
175 if ($index === NULL AND ! empty($_POST))
179 // Loop through the full _POST array and return it
180 foreach (array_keys($_POST) as $key)
182 $post[$key] = $this->_fetch_from_array($_POST, $key, $xss_clean);
187 return $this->_fetch_from_array($_POST, $index, $xss_clean);
191 // --------------------------------------------------------------------
194 * Fetch an item from either the GET array or the POST
197 * @param string The index key
198 * @param bool XSS cleaning
201 function get_post($index = '', $xss_clean = FALSE)
203 if ( ! isset($_POST[$index]) )
205 return $this->get($index, $xss_clean);
209 return $this->post($index, $xss_clean);
213 // --------------------------------------------------------------------
216 * Fetch an item from the COOKIE array
223 function cookie($index = '', $xss_clean = FALSE)
225 return $this->_fetch_from_array($_COOKIE, $index, $xss_clean);
228 // ------------------------------------------------------------------------
233 * Accepts six parameter, or you can submit an associative
234 * array in the first parameter containing all the values.
238 * @param string the value of the cookie
239 * @param string the number of seconds until expiration
240 * @param string the cookie domain. Usually: .yourdomain.com
241 * @param string the cookie path
242 * @param string the cookie prefix
243 * @param bool true makes the cookie secure
246 function set_cookie($name = '', $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $secure = FALSE)
250 // always leave 'name' in last place, as the loop will break otherwise, due to $$item
251 foreach (array('value', 'expire', 'domain', 'path', 'prefix', 'secure', 'name') as $item)
253 if (isset($name[$item]))
255 $
$item = $name[$item];
260 if ($prefix == '' AND config_item('cookie_prefix') != '')
262 $prefix = config_item('cookie_prefix');
264 if ($domain == '' AND config_item('cookie_domain') != '')
266 $domain = config_item('cookie_domain');
268 if ($path == '/' AND config_item('cookie_path') != '/')
270 $path = config_item('cookie_path');
272 if ($secure == FALSE AND config_item('cookie_secure') != FALSE)
274 $secure = config_item('cookie_secure');
277 if ( ! is_numeric($expire))
279 $expire = time() - 86500;
283 $expire = ($expire > 0) ? time() +
$expire : 0;
286 setcookie($prefix.$name, $value, $expire, $path, $domain, $secure);
289 // --------------------------------------------------------------------
292 * Fetch an item from the SERVER array
299 function server($index = '', $xss_clean = FALSE)
301 return $this->_fetch_from_array($_SERVER, $index, $xss_clean);
304 // --------------------------------------------------------------------
307 * Fetch the IP Address
311 public function ip_address()
313 if ($this->ip_address
!== FALSE)
315 return $this->ip_address
;
318 $proxy_ips = config_item('proxy_ips');
319 if ( ! empty($proxy_ips))
321 $proxy_ips = explode(',', str_replace(' ', '', $proxy_ips));
322 foreach (array('HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP') as $header)
324 if (($spoof = $this->server($header)) !== FALSE)
326 // Some proxies typically list the whole chain of IP
327 // addresses through which the client has reached us.
328 // e.g. client_ip, proxy_ip1, proxy_ip2, etc.
329 if (strpos($spoof, ',') !== FALSE)
331 $spoof = explode(',', $spoof, 2);
335 if ( ! $this->valid_ip($spoof))
346 $this->ip_address
= ($spoof !== FALSE && in_array($_SERVER['REMOTE_ADDR'], $proxy_ips, TRUE))
347 ? $spoof : $_SERVER['REMOTE_ADDR'];
351 $this->ip_address
= $_SERVER['REMOTE_ADDR'];
354 if ( ! $this->valid_ip($this->ip_address
))
356 $this->ip_address
= '0.0.0.0';
359 return $this->ip_address
;
362 // --------------------------------------------------------------------
365 * Validate IP Address
369 * @param string ipv4 or ipv6
372 public function valid_ip($ip, $which = '')
374 $which = strtolower($which);
376 // First check if filter_var is available
377 if (is_callable('filter_var'))
381 $flag = FILTER_FLAG_IPV4
;
384 $flag = FILTER_FLAG_IPV6
;
391 return (bool) filter_var($ip, FILTER_VALIDATE_IP
, $flag);
394 if ($which !== 'ipv6' && $which !== 'ipv4')
396 if (strpos($ip, ':') !== FALSE)
400 elseif (strpos($ip, '.') !== FALSE)
410 $func = '_valid_'.$which;
411 return $this->$func($ip);
414 // --------------------------------------------------------------------
417 * Validate IPv4 Address
419 * Updated version suggested by Geert De Deckere
425 protected function _valid_ipv4($ip)
427 $ip_segments = explode('.', $ip);
429 // Always 4 segments needed
430 if (count($ip_segments) !== 4)
434 // IP can not start with 0
435 if ($ip_segments[0][0] == '0')
440 // Check each segment
441 foreach ($ip_segments as $segment)
443 // IP segments must be digits and can not be
444 // longer than 3 digits or greater then 255
445 if ($segment == '' OR preg_match("/[^0-9]/", $segment) OR $segment > 255 OR strlen($segment) > 3)
454 // --------------------------------------------------------------------
457 * Validate IPv6 Address
463 protected function _valid_ipv6($str)
465 // 8 groups, separated by :
467 // one set of consecutive 0 groups can be collapsed to ::
472 $chunks = array_filter(
473 preg_split('/(:{1,2})/', $str, NULL, PREG_SPLIT_DELIM_CAPTURE
)
476 // Rule out easy nonsense
477 if (current($chunks) == ':' OR end($chunks) == ':')
482 // PHP supports IPv4-mapped IPv6 addresses, so we'll expect those as well
483 if (strpos(end($chunks), '.') !== FALSE)
485 $ipv4 = array_pop($chunks);
487 if ( ! $this->_valid_ipv4($ipv4))
495 while ($seg = array_pop($chunks))
501 return FALSE; // too many groups
504 if (strlen($seg) > 2)
506 return FALSE; // long separator
513 return FALSE; // multiple collapsed
519 elseif (preg_match("/[^0-9a-f]/i", $seg) OR strlen($seg) > 4)
521 return FALSE; // invalid segment
525 return $collapsed OR $groups == 1;
528 // --------------------------------------------------------------------
536 function user_agent()
538 if ($this->user_agent
!== FALSE)
540 return $this->user_agent
;
543 $this->user_agent
= ( ! isset($_SERVER['HTTP_USER_AGENT'])) ? FALSE : $_SERVER['HTTP_USER_AGENT'];
545 return $this->user_agent
;
548 // --------------------------------------------------------------------
553 * This function does the following:
555 * Unsets $_GET data (if query strings are not enabled)
557 * Unsets all globals if register_globals is enabled
559 * Standardizes newline characters to \n
564 function _sanitize_globals()
566 // It would be "wrong" to unset any of these GLOBALS.
567 $protected = array('_SERVER', '_GET', '_POST', '_FILES', '_REQUEST',
568 '_SESSION', '_ENV', 'GLOBALS', 'HTTP_RAW_POST_DATA',
569 'system_folder', 'application_folder', 'BM', 'EXT',
570 'CFG', 'URI', 'RTR', 'OUT', 'IN');
572 // Unset globals for securiy.
573 // This is effectively the same as register_globals = off
574 foreach (array($_GET, $_POST, $_COOKIE) as $global)
576 if ( ! is_array($global))
578 if ( ! in_array($global, $protected))
586 foreach ($global as $key => $val)
588 if ( ! in_array($key, $protected))
597 // Is $_GET data allowed? If not we'll set the $_GET to an empty array
598 if ($this->_allow_get_array
== FALSE)
604 if (is_array($_GET) AND count($_GET) > 0)
606 foreach ($_GET as $key => $val)
608 $_GET[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
614 if (is_array($_POST) AND count($_POST) > 0)
616 foreach ($_POST as $key => $val)
618 $_POST[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
622 // Clean $_COOKIE Data
623 if (is_array($_COOKIE) AND count($_COOKIE) > 0)
625 // Also get rid of specially treated cookies that might be set by a server
626 // or silly application, that are of no use to a CI application anyway
627 // but that when present will trip our 'Disallowed Key Characters' alarm
628 // http://www.ietf.org/rfc/rfc2109.txt
629 // note that the key names below are single quoted strings, and are not PHP variables
630 unset($_COOKIE['$Version']);
631 unset($_COOKIE['$Path']);
632 unset($_COOKIE['$Domain']);
634 foreach ($_COOKIE as $key => $val)
636 $_COOKIE[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
641 $_SERVER['PHP_SELF
'] = strip_tags($_SERVER['PHP_SELF
']);
644 // CSRF Protection check on HTTP requests
645 if ($this->_enable_csrf == TRUE && ! $this->is_cli_request())
647 $this->security->csrf_verify();
650 log_message('debug
', "Global POST and COOKIE data sanitized");
653 // --------------------------------------------------------------------
658 * This is a helper function. It escapes data and
659 * standardizes newline characters to \n
665 function _clean_input_data($str)
669 $new_array = array();
670 foreach ($str as $key => $val)
672 $new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
677 /* We strip slashes if magic quotes is on to keep things consistent
679 NOTE: In PHP 5.4 get_magic_quotes_gpc() will always return 0 and
680 it will probably not exist in future versions at all.
682 if ( ! is_php('5.4') && get_magic_quotes_gpc())
684 $str = stripslashes($str);
687 // Clean UTF-8 if supported
688 if (UTF8_ENABLED === TRUE)
690 $str = $this->uni->clean_string($str);
693 // Remove control characters
694 $str = remove_invisible_characters($str);
696 // Should we filter the input data?
697 if ($this->_enable_xss === TRUE)
699 $str = $this->security->xss_clean($str);
702 // Standardize newlines if needed
703 if ($this->_standardize_newlines == TRUE)
705 if (strpos($str, "\r") !== FALSE)
707 $str = str_replace(array("\r\n", "\r", "\r\n\n"), PHP_EOL, $str);
714 // --------------------------------------------------------------------
719 * This is a helper function. To prevent malicious users
720 * from trying to exploit keys we make sure that keys are
721 * only named with alpha-numeric text and a few other items.
727 function _clean_input_keys($str)
729 if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
731 exit('Disallowed Key Characters
.');
734 // Clean UTF-8 if supported
735 if (UTF8_ENABLED === TRUE)
737 $str = $this->uni->clean_string($str);
743 // --------------------------------------------------------------------
748 * In Apache, you can simply call apache_request_headers(), however for
749 * people running other webservers the function is undefined.
751 * @param bool XSS cleaning
755 public function request_headers($xss_clean = FALSE)
757 // Look at Apache go!
758 if (function_exists('apache_request_headers
'))
760 $headers = apache_request_headers();
764 $headers['Content
-Type
'] = (isset($_SERVER['CONTENT_TYPE
'])) ? $_SERVER['CONTENT_TYPE
'] : @getenv('CONTENT_TYPE
');
766 foreach ($_SERVER as $key => $val)
768 if (strncmp($key, 'HTTP_
', 5) === 0)
770 $headers[substr($key, 5)] = $this->_fetch_from_array($_SERVER, $key, $xss_clean);
775 // take SOME_HEADER and turn it into Some-Header
776 foreach ($headers as $key => $val)
778 $key = str_replace('_
', ' ', strtolower($key));
779 $key = str_replace(' ', '-', ucwords($key));
781 $this->headers[$key] = $val;
784 return $this->headers;
787 // --------------------------------------------------------------------
792 * Returns the value of a single member of the headers class member
794 * @param string array key for $this->headers
795 * @param boolean XSS Clean or not
796 * @return mixed FALSE on failure, string on success
798 public function get_request_header($index, $xss_clean = FALSE)
800 if (empty($this->headers))
802 $this->request_headers();
805 if ( ! isset($this->headers[$index]))
810 if ($xss_clean === TRUE)
812 return $this->security->xss_clean($this->headers[$index]);
815 return $this->headers[$index];
818 // --------------------------------------------------------------------
823 * Test to see if a request contains the HTTP_X_REQUESTED_WITH header
827 public function is_ajax_request()
829 return ($this->server('HTTP_X_REQUESTED_WITH
') === 'XMLHttpRequest
');
832 // --------------------------------------------------------------------
837 * Test to see if a request was made from the command line
841 public function is_cli_request()
843 return (php_sapi_name() === 'cli
' OR defined('STDIN
'));
848 /* End of file Input.php */
849 /* Location: ./system/core/Input.php */