<?php

/**
 * Communicates with a RESTful backend (i.e get, post, put and delete methods
 * of HTTP protocol) that understands JSON and answers JSON.
 */
class JsonHttpClient {
    // Request vars
    var $host;
    var $port;
    var $path;
    var $method;
    var $postdata = '';
    var $requestHeaders = array(
        'Accept' => 'application/json',
        'User-Agent' => 'JsonHttpClient'
    );
    // Options
    var $timeout = 30;
    var $debug = false;
    // Basic authorization variables
    var $username;
    var $password;
    // Response vars
    var $status;
    var $headers = array();
    var $content = '';
    var $errormsg;

    function __construct($host, $port=80) {
        $this->host = $host;
        $this->port = $port;
        $this->timeout = ini_get('max_execution_time');
        if (! $this->timeout) {
            $this->timeout = 30;
        }
    }
    //configure headers
    function setHeader($key, $value, $base64Encode = true) {
        if($base64Encode) {
            $this->requestHeaders[$key] = base64_encode($value);
        } else {
            $this->requestHeaders[$key] = $value;
        }
    }

    // configure authorization
    function setAuthentication($username, $password) {
        $this->username = $username;
        $this->password = $password;
    }
    // configure debug mode
    function setDebug($boolean) {
        $this->debug = $boolean;
    }

    function get($path, $data = false) {
        $this->path = $path;
        $this->method = 'GET';
        if ($data) {
            $this->path .= '?'.$this->buildQueryString($data);
        }
        return $this->doRequest();
    }
    function post($path, $data) {
        $this->path = $path;
        $this->method = 'POST';
        $this->postdata = $this->buildQueryBody($data);
        return $this->doRequest();
    }
    function put($path, $data, $buildQuery = true) {
        $this->path = $path;
        $this->method = 'PUT';
        $this->postdata = $buildQuery ? $this->buildQueryBody($data) : $data;
        return $this->doRequest($buildQuery);
    }
    function delete($path, $data = false) {
        $this->path = $path;
        $this->method = 'DELETE';
        if ($data) {
            $this->path .= '?'.$this->buildQueryString($data);
        }
        return $this->doRequest();
    }
    protected function buildQueryString($data) {
        $res = http_build_query($data, '', '&');
        //Other languages (in our case Java) allow access to multiple values for the same GET/POST
        //parameter without the use of the brace ([]) notation.
        //For example, we want to send something like this : ...?q=foo&q=bar
        //http_build_query() by itself would have given : ...?q[0]=foo&q[1]=bar
        //So, preg_replace to the rescue !
        //This works because the '=' character can't appear non-urlencoded except to separate args
        $res = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $res);
        return $res;
    }
    protected function buildQueryBody($data) {
        return json_encode($data);
    }
    protected function doRequest($buildQuery = true) {
        // Performs the actual HTTP request, returning true or false depending on outcome
        if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) {
            // Set error message
            switch($errno) {
                case -3:
                    $this->errormsg = 'Socket creation failed (-3)';
                    break ;
                case -4:
                    $this->errormsg = 'DNS lookup failure (-4)';
                    break ;
                case -5:
                    $this->errormsg = 'Connection refused or timed out (-5)';
                    break ;
                default:
                    $this->errormsg = 'Unknown error';
                    break ;
            }
            if ($this->errormsg) {
                $this->errormsg = 'Connection failed ('.$errno.')';
                $this->errormsg .= ' '.$errstr;
                $this->debug($this->errormsg);
            }
            return false;
        }
        socket_set_timeout($fp, $this->timeout);
        $request = $this->buildRequest($buildQuery);
        $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]; // not used
                $this->debug(trim($line));
                continue;
            }
            if ($inHeaders) {
                if (trim($line) == '') {
                    $inHeaders = false;
                    $this->debug('Received Headers', $this->headers);
                    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);
        }
        return true;
    }
    protected function buildRequest($buildQuery = true) {
        $headers = array();
        // Using 1.1 leads to all manner of problems, such as "chunked" encoding
        $headers[] = sprintf("%s %s HTTP/1.0", $this->method, $this->path);
		$host = str_replace('http://', '', $this->host);
        $headers[] = "Host: {$host}";
        foreach ($this->requestHeaders as $key => $value) {
            $headers[] = "{$key}: {$value}";
        }
        // Basic authentication
        if ($this->username && $this->password) {
            $headers[] = 'Authorization: Basic '.base64_encode($this->username.':'.$this->password);
        }
        // If this is a POST or a PUT, set the content type and length
        if ($this->postdata) {
            if ($buildQuery == true) {
                $headers[] = 'Content-Type: application/json';
            } else {
                $headers[] = 'Content-Type: application/x-www-form-urlencoded';
            }

            $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;
    }

    // DEBUG
    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>';
        }
    }
}

/**
 * JSON client handler supporting HTTPS
 */
class JsonHttpClientSsl extends JsonHttpClient {

    //configure headers WITHOUT base64 encoding
    function setHeader($key, $value) {
        $this->requestHeaders[$key] = $value;
    }

    function get($path, $data = false) {
        $this->path = $path;
        $this->method = 'GET';
        if ($data) {
            $this->path .= '?'.parent::buildQueryString($data);
        }
        return $this->doRequest();
    }
    function post($path, $data) {
        $this->path = $path;
        $this->method = 'POST';
        $this->postdata = parent::buildQueryBody($data);
        return $this->doRequest();
    }
    function put($path, $data) {
        $this->path = $path;
        $this->method = 'PUT';
        $this->postdata = parent::buildQueryBody($data);
        return $this->doRequest();
    }
    function delete($path, $data = false) {
        $this->path = $path;
        $this->method = 'DELETE';
        if ($data) {
            $this->path .= '?'.parent::buildQueryString($data);
        }
        return $this->doRequest();
    }
    protected function doRequest() {
        // Performs the actual HTTP CUrl request, returning true or false depending on outcome
        $headers = $this->buildRequest();
        $ch = curl_init($this->path);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->method);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        if ($this->postdata) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(json_decode($this->postdata, true)));
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        $infos = curl_getinfo($ch);
        curl_close($ch);
        $this->status = $infos['http_code'];
        $this->content = $response;
        if ($this->status == 200) {
            return true;
        }
        return false;
    }

    protected function buildRequest() {
        $headers = array();
        // Using 1.1 leads to all manner of problems, such as "chunked" encoding
		$host = str_replace('https://', '', $this->host);
        $headers[] = "Host: {$host}";
        foreach ($this->requestHeaders as $key => $value) {
            $headers[] = "{$key}: {$value}";
        }
        // Basic authentication
        if ($this->username && $this->password) {
            $headers[] = 'Authorization: Basic '.base64_encode($this->username.':'.$this->password);
        }
        // If this is a POST or a PUT, set the content type and length
        if ($this->postdata) {
            $headers[] = 'Content-Type: application/json';
        }
        return $headers;
    }
}