<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 5.1.6 or newer
 *
 * @package        CodeIgniter
 * @author        ExpressionEngine Dev Team
 * @copyright    Copyright (c) 2008 - 2010, EllisLab, Inc.
 * @license        https://codeigniter.com/user_guide/license.html
 * @link        https://codeigniter.com
 * @since        Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Input Class
 *
 * Pre-processes global input data for security
 *
 * @package        CodeIgniter
 * @subpackage    Libraries
 * @category    Input
 * @author        ExpressionEngine Dev Team
 * @link        https://codeigniter.com/user_guide/libraries/input.html
 */
class CI_Input
{

    public $ip_address = FALSE;
    public $user_agent = FALSE;
    protected $_allow_get_array = FALSE;
    protected $_standardize_newlines = TRUE;
    protected $_enable_xss = FALSE; // Set automatically based on config setting
    protected $_enable_csrf = FALSE; // Set automatically based on config setting

    protected $headers = array();
    protected $security;
    protected $uni;


    /**
     * Constructor
     *
     * Sets whether to globally enable the XSS processing
     * and whether to allow the $_GET array
     *
     */
    public function __construct()
    {
        log_message('debug', "Input Class Initialized");

        $this->_allow_get_array = (config_item('enable_query_strings') === TRUE) ? TRUE : FALSE;
        $this->_enable_xss = (config_item('global_xss_filtering') === TRUE) ? TRUE : FALSE;
        $this->_enable_csrf = (config_item('csrf_protection') === TRUE) ? TRUE : FALSE;

        // Do we need to load the security class?
        if ($this->_enable_xss == TRUE or $this->_enable_csrf == TRUE) {
            $this->security =& load_class('Security');
        }

        // Do we need the Unicode class?
        if (UTF8_ENABLED === TRUE) {
            global $UNI;
            $this->uni =& $UNI;
        }

        // Sanitize global arrays
        $this->_sanitize_globals();
    }

    // --------------------------------------------------------------------

    /**
     * Fetch from array
     *
     * This is a helper function to retrieve values from global arrays
     *
     * @access    private
     * @param array
     * @param string
     * @param bool
     * @return    string
     */
    function _fetch_from_array(&$array, $index = '', $xss_clean = FALSE)
    {
        if (!isset($array[$index])) {
            return FALSE;
        }

        if ($xss_clean === TRUE) {
            $_security =& load_class('Security');
            return $_security->xss_clean($array[$index]);
        }

        return $array[$index];
    }

    // --------------------------------------------------------------------

    /**
     * Fetch an item from the GET array
     *
     * @access    public
     * @param string
     * @param bool
     * @return    string
     */
    function get($index = '', $xss_clean = FALSE)
    {
        return $this->_fetch_from_array($_GET, $index, $xss_clean);
    }

    // --------------------------------------------------------------------

    /**
     * Fetch an item from the POST array
     *
     * @access    public
     * @param string
     * @param bool
     * @return    string
     */
    function post($index = '', $xss_clean = FALSE)
    {
        return $this->_fetch_from_array($_POST, $index, $xss_clean);
    }


    // --------------------------------------------------------------------

    /**
     * Fetch an item from either the GET array or the POST
     *
     * @access    public
     * @param string    The index key
     * @param bool    XSS cleaning
     * @return    string
     */
    function get_post($index = '', $xss_clean = FALSE)
    {
        if (!isset($_POST[$index])) {
            return $this->get($index, $xss_clean);
        } else {
            return $this->post($index, $xss_clean);
        }
    }

    // --------------------------------------------------------------------

    /**
     * Fetch an item from the COOKIE array
     *
     * @access    public
     * @param string
     * @param bool
     * @return    string
     */
    function cookie($index = '', $xss_clean = FALSE)
    {
        return $this->_fetch_from_array($_COOKIE, $index, $xss_clean);
    }

    // ------------------------------------------------------------------------

    /**
     * Set cookie
     *
     * Accepts six parameter, or you can submit an associative
     * array in the first parameter containing all the values.
     *
     * @access    public
     * @param mixed
     * @param string    the value of the cookie
     * @param string    the number of seconds until expiration
     * @param string    the cookie domain.  Usually:  .yourdomain.com
     * @param string    the cookie path
     * @param string    the cookie prefix
     * @param bool    httponly
     * @return    void
     */
    function set_cookie($name = '', $value = '', $expire = '', $domain = '', $path = '/', $prefix = '', $httponly = true)
    {
        if (is_array($name)) {
            foreach (array('value', 'expire', 'domain', 'path', 'prefix', 'name') as $item) {
                if (isset($name[$item])) {
                    $$item = $name[$item];
                }
            }
        }

        if ($prefix == '' and config_item('cookie_prefix') != '') {
            $prefix = config_item('cookie_prefix');
        }
        if ($domain == '' and config_item('cookie_domain') != '') {
            $domain = config_item('cookie_domain');
        }
        if ($path == '/' and config_item('cookie_path') != '/') {
            $path = config_item('cookie_path');
        }

        if (!is_numeric($expire)) {
            $expire = time() - 86500;
        } else {
            if ($expire > 0) {
                $expire = time() + $expire;
            } else {
                $expire = 0;
            }
        }

        //@modified CK untermStrich - Add httponly to true and use cookie secure
        $cookie_secure = (config_item('cookie_secure') === true);
        if (!$cookie_secure) {
            $cookie_secure = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443);
        }

        setcookie($prefix . $name, $value, $expire, $path, $domain, $cookie_secure, $httponly);
    }

    // --------------------------------------------------------------------

    /**
     * Fetch an item from the SERVER array
     *
     * @access    public
     * @param string
     * @param bool
     * @return    string
     */
    function server($index = '', $xss_clean = FALSE)
    {
        return $this->_fetch_from_array($_SERVER, $index, $xss_clean);
    }

    // --------------------------------------------------------------------

    /**
     * Fetch the IP Address
     *
     * Determines and validates the visitor's IP address.
     *
     * @return    string    IP address
     */
    public function ip_address()
    {
        if ($this->ip_address !== FALSE) {
            return $this->ip_address;
        }

        $proxy_ips = config_item('proxy_ips');
        if (!empty($proxy_ips) && !is_array($proxy_ips)) {
            $proxy_ips = explode(',', str_replace(' ', '', $proxy_ips));
        }

        $this->ip_address = $this->server('REMOTE_ADDR');

        if ($proxy_ips) {
            foreach (array('HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP') as $header) {
                if (($spoof = $this->server($header)) !== NULL) {
                    // Some proxies typically list the whole chain of IP
                    // addresses through which the client has reached us.
                    // e.g. client_ip, proxy_ip1, proxy_ip2, etc.
                    sscanf($spoof, '%[^,]', $spoof);

                    if (!$this->valid_ip($spoof)) {
                        $spoof = NULL;
                    } else {
                        break;
                    }
                }
            }

            if ($spoof) {
                for ($i = 0, $c = count($proxy_ips); $i < $c; $i++) {
                    // Check if we have an IP address or a subnet
                    if (strpos($proxy_ips[$i], '/') === FALSE) {
                        // An IP address (and not a subnet) is specified.
                        // We can compare right away.
                        if ($proxy_ips[$i] === $this->ip_address) {
                            $this->ip_address = $spoof;
                            break;
                        }

                        continue;
                    }

                    // We have a subnet ... now the heavy lifting begins
                    isset($separator) or $separator = $this->valid_ip($this->ip_address, 'ipv6') ? ':' : '.';

                    // If the proxy entry doesn't match the IP protocol - skip it
                    if (strpos($proxy_ips[$i], $separator) === FALSE) {
                        continue;
                    }

                    // Convert the REMOTE_ADDR IP address to binary, if needed
                    if (!isset($ip, $sprintf)) {
                        if ($separator === ':') {
                            // Make sure we're have the "full" IPv6 format
                            $ip = explode(':',
                                str_replace('::',
                                    str_repeat(':', 9 - substr_count($this->ip_address, ':')),
                                    $this->ip_address
                                )
                            );

                            for ($j = 0; $j < 8; $j++) {
                                $ip[$j] = intval($ip[$j], 16);
                            }

                            $sprintf = '%016b%016b%016b%016b%016b%016b%016b%016b';
                        } else {
                            $ip = explode('.', $this->ip_address);
                            $sprintf = '%08b%08b%08b%08b';
                        }

                        $ip = vsprintf($sprintf, $ip);
                    }

                    // Split the netmask length off the network address
                    sscanf($proxy_ips[$i], '%[^/]/%d', $netaddr, $masklen);

                    // Again, an IPv6 address is most likely in a compressed form
                    if ($separator === ':') {
                        $netaddr = explode(':', str_replace('::', str_repeat(':', 9 - substr_count($netaddr, ':')), $netaddr));
                        for ($j = 0; $j < 8; $j++) {
                            $netaddr[$j] = intval($netaddr[$j], 16);
                        }
                    } else {
                        $netaddr = explode('.', $netaddr);
                    }

                    // Convert to binary and finally compare
                    if (strncmp($ip, vsprintf($sprintf, $netaddr), $masklen) === 0) {
                        $this->ip_address = $spoof;
                        break;
                    }
                }
            }
        }

        if (!$this->valid_ip($this->ip_address)) {
            return $this->ip_address = '0.0.0.0';
        }

        return $this->ip_address;
    }

    // --------------------------------------------------------------------

    /**
     * Validate IP Address
     *
     * Updated version suggested by Geert De Deckere
     *
     * @access    public
     * @param string
     * @return    string
     */
    public function valid_ip($ip, $which = '')
    {
        switch (strtolower($which)) {
            case 'ipv4':
                return (bool)filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
            case 'ipv6':
                return (bool)filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
            default:
                return (bool)filter_var($ip, FILTER_VALIDATE_IP);
        }
    }

    // --------------------------------------------------------------------

    /**
     * Fetch User Agent string
     *
     * @return    string|null    User Agent string or NULL if it doesn't exist
     */
    public function user_agent($xss_clean = FALSE)
    {
        if ($this->user_agent !== FALSE) {
            return $this->user_agent;
        }

        $this->user_agent = $this->_fetch_from_array($_SERVER, 'HTTP_USER_AGENT', $xss_clean);

        return $this->user_agent;
    }

    // --------------------------------------------------------------------

    /**
     * Sanitize Globals
     *
     * This function does the following:
     *
     * Unsets $_GET data (if query strings are not enabled)
     *
     * Unsets all globals if register_globals is enabled
     *
     * Standardizes newline characters to \n
     *
     * @access    private
     * @return    void
     */
    function _sanitize_globals()
    {
        // It would be "wrong" to unset any of these GLOBALS.
        $protected = array('_SERVER', '_GET', '_POST', '_FILES', '_REQUEST',
            '_SESSION', '_ENV', 'GLOBALS', 'HTTP_RAW_POST_DATA',
            'system_folder', 'application_folder', 'BM', 'EXT',
            'CFG', 'URI', 'RTR', 'OUT', 'IN');

        // Unset globals for securiy.
        // This is effectively the same as register_globals = off
        foreach (array($_GET, $_POST, $_COOKIE) as $global) {
            if (!is_array($global)) {
                if (!in_array($global, $protected)) {
                    global $$global;
                    $$global = NULL;
                }
            } else {
                foreach ($global as $key => $val) {
                    if (!in_array($key, $protected)) {
                        global $$key;
                        $$key = NULL;
                    }
                }
            }
        }

        // Is $_GET data allowed? If not we'll set the $_GET to an empty array
        if ($this->_allow_get_array == FALSE) {
            $_GET = array();
        } else {
            if (is_array($_GET) and count($_GET) > 0) {
                foreach ($_GET as $key => $val) {
                    $_GET[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
                }
            }
        }

        // Clean $_POST Data
        if (is_array($_POST) and count($_POST) > 0) {
            foreach ($_POST as $key => $val) {
                $_POST[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
            }
        }

        // Clean $_COOKIE Data
        if (is_array($_COOKIE) and count($_COOKIE) > 0) {
            // Also get rid of specially treated cookies that might be set by a server
            // or silly application, that are of no use to a CI application anyway
            // but that when present will trip our 'Disallowed Key Characters' alarm
            // http://www.ietf.org/rfc/rfc2109.txt
            // note that the key names below are single quoted strings, and are not PHP variables
            unset($_COOKIE['$Version']);
            unset($_COOKIE['$Path']);
            unset($_COOKIE['$Domain']);

            //Remove cookies which does not start with defined cookie prefix
            $_COOKIE = array_filter($_COOKIE, function ($key) {
                $cookie_prefix = config_item('cookie_prefix');
                return (substr($key, 0, strlen($cookie_prefix)) === $cookie_prefix) ? true : false;
            }, ARRAY_FILTER_USE_KEY);

            foreach ($_COOKIE as $key => $val) {
                $_COOKIE[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
            }
        }

        // Sanitize PHP_SELF
        $_SERVER['PHP_SELF'] = strip_tags($_SERVER['PHP_SELF']);


        // CSRF Protection check
        if ($this->_enable_csrf == TRUE) {
            $this->security->csrf_verify();
        }

        log_message('debug', "Global POST and COOKIE data sanitized");
    }

    // --------------------------------------------------------------------

    /**
     * Clean Input Data
     *
     * This is a helper function. It escapes data and
     * standardizes newline characters to \n
     *
     * @access    private
     * @param string
     * @return    string
     */
    function _clean_input_data($str)
    {
        if (is_array($str)) {
            $new_array = array();
            foreach ($str as $key => $val) {
                $new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
            }
            return $new_array;
        }

        // Clean UTF-8 if supported
        if (UTF8_ENABLED === TRUE) {
            $str = $this->uni->clean_string($str);
        }

        // Should we filter the input data?
        if ($this->_enable_xss === TRUE) {
            $str = $this->security->xss_clean($str);
        }

        // Standardize newlines if needed
        if ($this->_standardize_newlines == TRUE) {
            if (strpos($str, "\r") !== FALSE) {
                $str = str_replace(array("\r\n", "\r"), "\n", $str);
            }
        }

        return $str;
    }

    // --------------------------------------------------------------------

    /**
     * Clean Keys
     *
     * This is a helper function. To prevent malicious users
     * from trying to exploit keys we make sure that keys are
     * only named with alpha-numeric text and a few other items.
     *
     * @access    private
     * @param string
     * @return    string
     */
    function _clean_input_keys($str)
    {
        if (!preg_match("/^[a-z0-9:_\/-{}]+$/i", $str)) {
            exit('Disallowed Key Characters.');
        }

        // Clean UTF-8 if supported
        if (UTF8_ENABLED === TRUE) {
            $str = $this->uni->clean_string($str);
        }

        return $str;
    }

    // --------------------------------------------------------------------

    /**
     * Request Headers
     *
     * In Apache, you can simply call apache_request_headers(), however for
     * people running other webservers the function is undefined.
     *
     * @return array
     */
    public function request_headers($xss_clean = FALSE)
    {
        // Look at Apache go!
        if (function_exists('apache_request_headers')) {
            $headers = apache_request_headers();
        } else {
            $headers['Content-Type'] = (isset($_SERVER['CONTENT_TYPE'])) ? $_SERVER['CONTENT_TYPE'] : @getenv('CONTENT_TYPE');

            foreach ($_SERVER as $key => $val) {
                if (strncmp($key, 'HTTP_', 5) === 0) {
                    $headers[substr($key, 5)] = $this->_fetch_from_array($_SERVER, $key, $xss_clean);
                }
            }
        }

        // take SOME_HEADER and turn it into Some-Header
        foreach ($headers as $key => $val) {
            $key = str_replace('_', ' ', strtolower($key));
            $key = str_replace(' ', '-', ucwords($key));

            $this->headers[$key] = $val;
        }

        return $this->headers;
    }

    // --------------------------------------------------------------------

    /**
     * Get Request Header
     *
     * Returns the value of a single member of the headers class member
     *
     * @param string        array key for $this->headers
     * @param boolean        XSS Clean or not
     * @return    mixed        FALSE on failure, string on success
     */
    public function get_request_header($index, $xss_clean = FALSE)
    {
        if (empty($this->headers)) {
            $this->request_headers();
        }

        if (!isset($this->headers[$index])) {
            return FALSE;
        }

        if ($xss_clean === TRUE) {
            $_security =& load_class('Security');
            return $_security->xss_clean($this->headers[$index]);
        }

        return $this->headers[$index];
    }

    // --------------------------------------------------------------------

    /**
     * Is ajax Request?
     *
     * Test to see if a request contains the HTTP_X_REQUESTED_WITH header
     *
     * @return    boolean
     */
    public function is_ajax_request()
    {
        $req_source = $this->server('HTTP_X_REQUESTED_WITH');
        return ($req_source == 'XMLHttpRequest') ? TRUE : FALSE;
    }

}
// END Input class

/* End of file Input.php */
/* Location: ./system/core/Input.php */
