<?php
/**
 * Based on http://github.com/shuber/curl/blob/master/lib/curl.php 
 **/
class Curl {
    
    public 
$cookie;
    public 
$follow_redirects     true;
    public 
$headers             = array();
    public 
$options             = array();
    public 
$referer;
    public 
$user_agent;
    protected 
$error             '';
    protected 
$request;
    
    private 
$CI;                // CodeIgniter instance
    
    
public function __construct() 
    {
        
$this->CI =& get_instance();
        
log_message('debug''cURL Class Initialized');
        
        if (!
function_exists('curl_init')) 
        {
            die(
'Please Install CURL pluggin');
        }
        
//$this->cookie_file = APPPATH.'temp/'.session_id();
        
$this->cookie_file APPPATH.'temp/Cookie'.session_id();
        
$this->user_agent 'CURL-CLIENT USER AGENT';
    }
    
    public function 
set_cookies($params = array())
    {
        if(
is_array($params))
        {
            
$params http_build_query($params);
        }
        
        
$this->option(CURLOPT_COOKIE$params);
        return 
$this;
    }
    
    public function 
http_header($header_string)
    {
        
$this->headers[] = $header_string;
    }
    
    public function 
http_method($method)
    {
        
$this->options[CURLOPT_CUSTOMREQUEST] = strtoupper($method);
        return 
$this;
    }
    
    public function 
http_login($username ''$password ''$type 'any')
    {
        
$this->option(CURLOPT_HTTPAUTHconstant('CURLAUTH_'.strtoupper($type) ));
        
$this->option(CURLOPT_USERPWD$username.':'.$password);
        return 
$this;
    }
    
    public function 
proxy($url ''$port 80)
    {
        
$this->option(CURLOPT_HTTPPROXYTUNNELTRUE);
        
$this->option(CURLOPT_PROXY$url.':'$port);
        return 
$this;
    }
    
    public function 
proxy_login($username ''$password '')
    {
        
$this->option(CURLOPT_PROXYUSERPWD$username.':'.$password);
        return 
$this;
    }
    
 
    
    public function 
option($code$value)
    {
        if(
is_string($code) && !is_numeric($code))
        {
            
$code constant('CURLOPT_' strtoupper($code));
        }
        
        
$this->options[$code] = $value;
        return 
$this;
    }
    
/**
     * Do Get Request
     *
     * @param string $url
     * @param array|string $vars 
     * @return Curl_response
    **/
    
public function get($url$vars = array()) 
    {
        if (!empty(
$vars)) 
        {
            
$url .= (stripos($url'?') !== false) ? '&' '?';
            
$url .= (is_string($vars)) ? $vars http_build_query($vars'''&');
        }
        return 
$this->request('GET'$url);
    }
    
    
    
/**
     * Do Post request
     *
     * @param string $url
     * @param array|string $vars 
     * @return sso_response|boolean
    **/
    
public function post($url$vars = array()) 
    {
        return 
$this->request('POST'$url$vars);
    }
    
    
/**
     * Do request to server
     *
     * @param string $method
     * @param string $url
     * @param array|string $vars
     * @return sso_response|boolean
    **/
    
public function request($method$url$vars = array()) {
        
$this->error '';
        
        
        
$this->request curl_init();
        if (
is_array($vars)) $vars http_build_query($vars'''&');
        
        
$this->set_request_method($method);
        
$this->set_request_options($url$vars);
        
$this->set_request_headers();
        
        
$response curl_exec($this->request);
        
        if (
$response) {
            
$response $this->handle_response($response);
        } else {
            
$this->error curl_errno($this->request).' - '.curl_error($this->request);
        }
        
        
curl_close($this->request);
        
        
        return 
$response;
    }
    
    
/**
     * Formats and adds custom headers to the current request
     *
     * @return void
     * @access protected
    **/
    
protected function set_request_headers() {
        
$headers = array();
        foreach (
$this->headers as $key => $value) {
            
$headers[] = $key.': '.$value;
        }
        
curl_setopt($this->requestCURLOPT_HTTPHEADER$headers);
    }
    
    
/**
     * Set the associated CURL options for a request method
     *
     * @param string $method
     * @return void
     * @access protected
    **/
    
protected function set_request_method($method) {
        switch (
strtoupper($method)) {
            case 
'HEAD':
                
curl_setopt($this->requestCURLOPT_NOBODYtrue);
                break;
            case 
'GET':
                
curl_setopt($this->requestCURLOPT_HTTPGETtrue);
                break;
            case 
'POST':
                
curl_setopt($this->requestCURLOPT_POSTtrue);
                break;
            default:
                
curl_setopt($this->requestCURLOPT_CUSTOMREQUEST$method);
        }
    }
    
    
/**
     * Sets the CURLOPT options for the current request
     *
     * @param string $url
     * @param string $vars
     * @return void
     * @access protected
    **/
    
protected function set_request_options($url$vars) {
        
curl_setopt($this->requestCURLOPT_URL$url);
        if (!empty(
$vars)) curl_setopt($this->requestCURLOPT_POSTFIELDS$vars);
        
        
        
curl_setopt($this->requestCURLOPT_HEADERfalse);
        
curl_setopt($this->requestCURLOPT_RETURNTRANSFERtrue);
        
curl_setopt($this->requestCURLOPT_USERAGENT$this->user_agent);
        
        if (
$this->cookie_file) {
            
curl_setopt($this->requestCURLOPT_COOKIEFILE$this->cookie_file);
            
curl_setopt($this->requestCURLOPT_COOKIEJAR$this->cookie_file);
        }
        
        if (
$this->cookie){
            
$strCookie 'PHPSESSID=' session_name() . '; path=/';
            
curl_setopt$this->requestCURLOPT_COOKIE$strCookie );
        
        }
        if (
$this->follow_redirectscurl_setopt($this->requestCURLOPT_FOLLOWLOCATIONtrue);
        if (
$this->referercurl_setopt($this->requestCURLOPT_REFERER$this->referer);
        
        foreach (
$this->options as $option => $value) {
            
curl_setopt($this->requestconstant('CURLOPT_'.str_replace('CURLOPT_'''strtoupper($option))), $value);
        }
    }
    
    private function 
handle_response($response
    {
       
        
# Headers regex
        
$pattern '#HTTP/\d\.\d.*?$.*?\r\n\r\n#ims';
        
        
# Extract headers from response
        
preg_match_all($pattern$response$matches);
        
$headers_string array_pop($matches[0]);
        
$headers explode("\r\n"str_replace("\r\n\r\n"''$headers_string));
        
        
# Remove headers from the response body
        
$out['body']= str_replace($headers_string''$response);
        
        
# Extract the version and status from the first header
        
$version_and_status array_shift($headers);
        
preg_match('#HTTP/(\d\.\d)\s(\d\d\d)\s(.*)#'$version_and_status$matches);
        
$out['headers']['Http-Version'] = $matches[1];
        
$out['headers']['Status-Code'] = $matches[2];
        
$out['headers']['Status'] = $matches[2].' '.$matches[3];
        
        
# Convert headers into an associative array
        
foreach ($headers as $header
        {
            
preg_match('#(.*?)\:\s(.*)#'$header$matches);
            
$out['headers'][$matches[1]] = $matches[2];
        }
        
        return 
$out;
    }
    
}