<?php
/* Version 0.9, 6th April 2003 - Simon Willison ( http://simon.incutio.com/ )
   Manual: http://scripts.incutio.com/httpclient/
*/
class Common_HttpClient {
    // Request vars
    protected $host;
    protected $port;
    protected $path;
    protected $method;
    protected $postData = '';
    protected $cookies = array();
    protected $referer;
    protected $accept = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
    protected $acceptEncoding = 'gzip';
    protected $acceptLanguage = 'en-us';
    protected $userAgent = 'Incutio HttpClient v0.9';
    // Options
    protected $timeout = 30;
    protected $useGZip = true;
    protected $persistCookies = true;  // If true, received cookies are placed in the $this->cookies array ready for the next request
    // Note: This currently ignores the cookie path (and time) completely. Time is not important,
    //       but path could possibly lead to security problems.
    protected $persistReferers = true; // For each request, sends path of last request as referer
    protected $debug = false;
    protected $handleRedirects = true; // Auaomtically redirect if Location or URI header is found
    protected $maxRedirects = 5;
    protected $headersOnly = false;    // If true, stops receiving once headers have been read.
    // Basic authorization variables
    protected $username;
    protected $password;
    // Response vars
    protected $status;
    protected $headers = array();
    protected $content = '';
    protected $errorMsg;
    // Tracker variables
    protected $redirectCount = 0;
    protected $cookieHost = '';
    protected $contentType = 'application/x-www-form-urlencoded;charset=utf-8';
    protected $scheme = 'http';
    protected $server;

    public function __construct($host, $port=80) {
        $this->setServer( $host );
        $this->port = $port;
    }
    public function setServer( $host ) {
        if( preg_match('/^(http\:\/\/|https\:\/\/)/', $host, $matches ) ) {
            $length = strlen( $matches[0] );
            $this->host = substr( $host, $length );

            if( $length == 8 ) {
                $this->scheme = 'https';
                $this->server = 'ssl://'.$this->host;
            } else {
                $this->scheme = 'http';
                $this->server = $this->host;
            }
            var_dump($this->scheme);
            var_dump($this->host);
            var_dump($this->server);
        } else {
            $this->host = $host;
            $this->server = $host;
        }
    }
    function get($path, $data = false) {
        try{
            $this->path = $path;
            $this->method = 'GET';
            if ($data) {
                $this->path .= '?'.$this->buildQueryString($data);
            }
            return $this->doRequest();
        } catch( Exception $e ) {
            $this->errorMsg = $e->getMessage();
            return false;
        }
    }
    function post($path, $data) {
        try{
            $this->path = $path;
            $this->method = 'POST';
            $this->postData = $this->buildQueryString($data);
            return $this->doRequest();
        } catch( Exception $e ) {
            $this->errorMsg = $e->getMessage();
            return false;
        }
    }
    protected function buildQueryString($data) {
        $queryString = '';
        if (is_array($data)) {
            // Change data in to postable data
            foreach ($data as $key => $val) {
                if (is_array($val)) {
                    foreach ($val as $val2) {
                        $queryString .= urlencode($key).'='.urlencode($val2).'&';
                    }
                } else {
                    $queryString .= urlencode($key).'='.urlencode($val).'&';
                }
            }
            $queryString = substr($queryString, 0, -1); // Eliminate unnecessary &
        } else {
            $queryString = $data;
        }
        return $queryString;
    }
    protected function doRequest() {
        // Performs the actual HTTP request, returning true or false depending on outcome
        if (!$fp = @fsockopen($this->server, $this->port, $errNo, $errStr, $this->timeout)) {
            // Set error message
            switch($errNo) {
                case -3:
                    $this->errorMsg = 'Socket creation failed (-3)';
                case -4:
                    $this->errorMsg = 'DNS lookup failure (-4)';
                case -5:
                    $this->errorMsg = 'Connection refused or timed out (-5)';
                default:
                    $this->errorMsg = 'Connection failed ('.$errNo.')';
                    $this->errorMsg .= ' '.$errStr;
                    $this->debug($this->errorMsg);
            }
            return false;
        }
        //var_dump($this->host);
        socket_set_timeout( $fp, $this->timeout );

        $request = $this->buildRequest();
        //var_dump($request);
        $this->debug('Request', $request);

        fwrite($fp, $request);

        // Reset all the variables that should not persist between requests
        $this->headers = array();
        $this->content = '';
        $this->errorMsg = '';
        // Set a couple of flags
        $inHeaders = true;
        $atStart = true;
        // Now start reading back the response
        while (!feof($fp)) {
            $line = fgets($fp, 4096);
            if ($atStart) {
                // Deal with first line of returned data
                $atStart = false;
                if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
                    $this->errorMsg = "Status code line invalid: ".htmlentities($line);
                    $this->debug($this->errorMsg);
                    return false;
                }
                $http_version = $m[1]; // not used
                $this->status = $m[2];
                $status_string = $m[3];
                if( "200" != $this->status ){
                    $this->errorMsg = "Response status code invalid: " . $this->status . " " . $status_string;
                    $this->debug($this->errorMsg);
                    return false;
                }
                $this->debug(trim($line));
                continue;
            }
            if ($inHeaders) {
                if (trim($line) == '') {
                    $inHeaders = false;
                    $this->debug('Received Headers', $this->headers);
                    if ($this->headersOnly) {
                        break; // Skip the rest of the input
                    }
                    continue;
                }
                if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) {
                    // Skip to the next header
                    continue;
                }
                $key = strtolower(trim($m[1]));
                $val = trim($m[2]);
                // Deal with the possibility of multiple headers of same name
                if (isset($this->headers[$key])) {
                    if (is_array($this->headers[$key])) {
                        $this->headers[$key][] = $val;
                    } else {
                        $this->headers[$key] = array($this->headers[$key], $val);
                    }
                } else {
                    $this->headers[$key] = $val;
                }
                continue;
            }
            // We're not in the headers, so append the line to the contents
            $this->content .= $line;
        }
        fclose($fp);
        // If data is compressed, uncompress it
        if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') {
            $this->debug('Content is gzip encoded, unzipping it');
            $this->content = substr($this->content, 10); // See http://www.php.net/manual/en/function.gzencode.php
            $this->content = gzinflate($this->content);
        }
        //var_dump($this->content);
        // If $persist_cookies, deal with any cookies
        if ($this->persistCookies && isset($this->headers['set-cookie']) && $this->host == $this->cookieHost) {
            $cookies = $this->headers['set-cookie'];
            if (!is_array($cookies)) {
                $cookies = array($cookies);
            }
            foreach ($cookies as $cookie) {
                if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) {
                    $this->cookies[$m[1]] = $m[2];
                }
            }
            // Record domain of cookies for security reasons
            $this->cookieHost = $this->host;
        }
        // If $persist_referers, set the referer ready for the next request
        if ($this->persistReferers) {
            $this->debug('Persisting referer: '.$this->getRequestURL());
            $this->referer = $this->getRequestURL();
        }
        // Finally, if handle_redirects and a redirect is sent, do that
        if ($this->handleRedirects) {
            if (++$this->redirectCount >= $this->maxRedirects) {
                $this->errorMsg = 'Number of redirects exceeded maximum ('.$this->maxRedirects.')';
                $this->debug($this->errorMsg);
                $this->redirectCount = 0;
                return false;
            }
            $location = isset($this->headers['location']) ? $this->headers['location'] : '';
            $uri = isset($this->headers['uri']) ? $this->headers['uri'] : '';
            if ($location || $uri) {
                $url = parse_url($location.$uri);
                // This will FAIL if redirect is to a different site
                return $this->get($url['path']);
            }
        }
        return true;
    }
    protected function buildRequest() {
        $headers = array();
        $headers[] = "{$this->method} {$this->path} HTTP/1.0"; // Using 1.1 leads to all manner of problems, such as "chunked" encoding
        $headers[] = "Host: {$this->host}";
        $headers[] = "User-Agent: {$this->userAgent}";
        $headers[] = "Accept: {$this->accept}";
        if ($this->useGZip) {
            $headers[] = "Accept-encoding: {$this->acceptEncoding}";
        }
        $headers[] = "Accept-language: {$this->acceptLanguage}";
        if ($this->referer) {
            $headers[] = "Referer: {$this->referer}";
        }
        // Cookies
        if ($this->cookies) {
            $cookie = 'Cookie: ';
            foreach ($this->cookies as $key => $value) {
                $cookie .= "$key=$value; ";
            }
            $headers[] = $cookie;
        }
        // Basic authentication
        if ($this->username && $this->password) {
            $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password);
        }
        // If this is a POST, set the content type and length
        if ($this->postData) {
            $headers[] = 'Content-Type: '.$this->contentType;
            $headers[] = 'Content-Length: '.strlen($this->postData);
        }
        $request = implode("\r\n", $headers)."\r\n\r\n".$this->postData;
        return $request;
    }
    function getStatus() {
        return $this->status;
    }
    function getContent() {
        return $this->content;
    }
    function getHeaders() {
        return $this->headers;
    }
    function getHeader($header) {
        $header = strtolower($header);
        if (isset($this->headers[$header])) {
            return $this->headers[$header];
        } else {
            return false;
        }
    }
    function getError() {
        return $this->errorMsg;
    }
    function getCookies() {
        return $this->cookies;
    }
    function getRequestURL() {
        $url = $this->scheme.'://'.$this->host;
        if ($this->port != 80) {
            $url .= ':'.$this->port;
        }
        $url .= $this->path;
        return $url;
    }
    // Setter methods
    function setUserAgent($string) {
        $this->userAgent = $string;
    }
    function setAuthorization($username, $password) {
        $this->username = $username;
        $this->password = $password;
    }
    function setCookies($array) {
        $this->cookies = $array;
    }
    // Option setting methods
    function useGzip($boolean) {
        $this->useGZip = $boolean;
    }
    function setPersistCookies($boolean) {
        $this->persistCookies = $boolean;
    }
    function setPersistReferers($boolean) {
        $this->persistReferers = $boolean;
    }
    function setHandleRedirects($boolean) {
        $this->handleRedirects = $boolean;
    }
    function setMaxRedirects($num) {
        $this->maxRedirects = $num;
    }
    function setHeadersOnly($boolean) {
        $this->headersOnly = $boolean;
    }
    function setDebug($boolean) {
        $this->debug = $boolean;
    }
    function setContentType( $type ) {
        $this->contentType = $type;
    }
    // "Quick" static methods
    function quickGet($url) {
        $bits = parse_url($url);
        $host = $bits['host'];
        $port = isset($bits['port']) ? $bits['port'] : 80;
        $path = isset($bits['path']) ? $bits['path'] : '/';
        if (isset($bits['query'])) {
            $path .= '?'.$bits['query'];
        }
        $client = new HttpClient($host, $port);
        if (!$client->get($path)) {
            return false;
        } else {
            return $client->getContent();
        }
    }
    function quickPost($url, $data) {
        $bits = parse_url($url);
        $host = $bits['host'];
        $port = isset($bits['port']) ? $bits['port'] : 80;
        $path = isset($bits['path']) ? $bits['path'] : '/';
        $client = new HttpClient($host, $port);
        if (!$client->post($path, $data)) {
            return false;
        } else {
            return $client->getContent();
        }
    }
    protected function debug($msg, $object = false) {
        if ($this->debug) {
            print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> '.$msg;
            if ($object) {
                ob_start();
                print_r($object);
                $content = htmlentities(ob_get_contents());
                ob_end_clean();
                print '<pre>'.$content.'</pre>';
            }
            print '</div>';
        }
    }
    function setTimeOut($timeOut){
        $this->timeout = $timeOut;
    }

}