<?PHP
    // +----------------------------------------------------------------------+
    // | PHP version 4 Later                                                  |
    // +----------------------------------------------------------------------+
    // | Copyright (c) 2007 Nickname:Shin Gong Pyo                            |
    // +----------------------------------------------------------------------+
    // | This source file is subject to version 3.0 of the PHP license,       |
    // | that is bundled with this package in the file LICENSE, and is        |
    // | available through the world-wide-web at the following url:           |
    // | http://www.php.net/license/3_0.txt.                                  |
    // | If you did not receive a copy of the PHP license and are unable to   |
    // | obtain it through the world-wide-web, please send a note to          |
    // | license@php.net so we can mail you a copy immediately.               |
    // +----------------------------------------------------------------------+
    // | Author: Nickname:Shin Gong Pyo <chese9kim@paran.com>                 |
    // +----------------------------------------------------------------------+
    //
    // $Id: class.HttpEx.php,v 1.0 2007/05/07 Seoul Exp $
    /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

class HttpEx{

    var $address;
	var $headers;
    var $cookie;
    var $variable;
    var $RequestHeader;
    var $ResponseHeader;
    var $fsockstream;

    # constructor
    function HttpEx($url="") {
		$this->address = array();
		$this->headers = array();
		$this->cookie  = array();
        if(trim($url)) $this->setURL($url);

		$this->addRequestHeader("Host", "Host: ".$this->address['host']);
        $this->addRequestHeader("User-agent", "User-agent: ".$_SERVER['HTTP_USER_AGENT']);
		$this->addRequestHeader("Referer", "Referer: http://".$this->address['host'].$this->address['path']);
    }

    /**
     * URL ÁöÁ¤ÇÔ¼ö
	 *
     * @param string $url : URL
     * @return boolean
     */
    function setURL($url) {
        if(!trim($url)) return false;
		$this->address = parse_url($url);
        if(strtoupper($this->address['scheme']) != "HTTP") return false;

        if(is_null($this->address['port'])) $this->address['port'] = 80;
        if(is_null($this->address['path'])) $this->address['path'] = "/";
        if($this->address['query']) {
            $arr1 = explode("&", $this->address['query']);
            foreach($arr1 as $value) {
				$arr2 = explode("=", $value);
				$this->variable[$arr2[0]] = $arr2[1];
            }
        }
        return true;
    }

    /**
     * º¯¼ö°ªÀ» ÁöÁ¤ÇÑ´Ù.
     *
     * @param string $key : º¯¼ö¸í, ¹è¿­·Îµµ ³ÖÀ»¼ö ÀÖ´Ù.
     * @param string $value : º¯¼ö°ª
     */
    function setParam($key, $value="") {
        if(is_array($key)) 
			foreach($key as $k => $v) $this->variable[$k] = $v;
        else $this->variable[$key] = $value;
    }

    /**
     * Çì´õ È®Àå¿ë ÇÔ¼ö
     *
     * @param string $Status : º¯¼ö¸í, ¹è¿­·Îµµ ³ÖÀ»¼ö ÀÖ´Ù.
     * @param string $Contents : º¯¼ö°ª
     */
    function addRequestHeader($Status, $Contents="") {
        if(is_array($Status)) 
			foreach($Status as $k => $v) $this->headers[$k] = $v;
        else $this->headers[$Status] = $Contents;
    }

    /**
     * ÄíÅ°¸¦ ÁöÁ¤ÇÑ´Ù.
     *
     * @param string $key : ÄíÅ°º¯¼ö¸í, ¹è¿­·Îµµ ³ÖÀ»¼ö ÀÖ´Ù.
     * @param string $value : ÄíÅ°º¯¼ö°ª
     */
    function setCookie($key, $value="") {
        if(is_array($key)) foreach($key as $k => $v) $this->cookie[$key] = "$k=$v"; 
        else $this->cookie[$key] = "$key=$value";
		$this->addRequestHeader("Cookie", "Cookie: ".implode("; ", $this->cookie));
    }

    /**
     * ÀÎÁõ¼³Á¤ÇÔ¼ö
     *
     * @param string $id : ¾ÆÀÌµð
     * @param string $pass : ÆÐ½º¿öµå
     */
    function setAuth($id, $pass) {
		$this->addRequestHeader("Authorization", "Authorization: Basic ".base64_encode($id.":".$pass));
    }

    /**
     * ÆäÀÌÁö ÀÀ´äÇì´õ ¼³Á¤ÇÔ¼ö
     */
    function setResponseHeader() {
        // Çì´õ ºÎºÐÀ» ±¸ÇÑ´Ù.
        $this->ResponseHeader = ""; // Çì´õÀÇ ³»¿ëÀ» ÃÊ±âÈ­ ÇÑ´Ù.
        while(trim($buffer = fgets($this->fsockstream,1024)) != "") {
            $this->ResponseHeader .= $buffer;
        }
    }

    /**
     * ÆäÀÌÁö ÀÀ´ä³»¿ë ¼³Á¤ÇÔ¼ö
     */
    function setResponseBody() {
        // ¹Ùµð ºÎºÐÀ» ±¸ÇÑ´Ù.
		$ResponseBody = "";
        while(!feof($this->fsockstream)) {
            $ResponseBody .= fgets($this->fsockstream,1024);
        }
		return $ResponseBody;
    }

    /**
     * ÆäÀÌÁö ¿äÃ»Çì´õ ±¸¼ºÇÔ¼ö
     *
     * @param string $Methode : POST, GET Áß ÇÏ³ª¸¦ ÀÔ·ÂÇÑ´Ù.
     * @return string
     */
    function setRequestHeader($Methode) {
		$query = (strtoupper($Methode) == "POST")?"\r\n":"?";
        if(is_array($this->variable)) {
			$parameter = array();
            foreach($this->variable as $key => $val)
				$parameter[] = trim($key)."=".urlencode(trim($val));
			$query.= implode("&", $parameter);
			if(strtoupper($Methode) == "POST") $query .= "\r\n";
        }
		if($query == "?") $query = "";

		$this->RequestHeader  = $Methode." ".$this->address['path'];
		$this->RequestHeader .= (strtoupper($Methode) == "POST")?" HTTP/1.0\r\n":$query." HTTP/1.0\r\n";

		$this->RequestHeader .= implode("\r\n", $this->headers)."\r\n";

        // GET, POST ¹æ½Ä¿¡ µû¶ó Çì´õ¸¦ ´Ù¸£°Ô ±¸¼ºÇÑ´Ù.
		if(strtoupper($Methode) == "POST") {
			$this->RequestHeader .= "Content-type: application/x-www-form-urlencoded\r\n";
			if($query) {
				$this->RequestHeader .= "Content-length: ".strlen($query)."\r\n";
				$this->RequestHeader .= $query;
			}
		}
		$this->RequestHeader .= "\r\n";
    }

    /**
     * Á¢¼Ó½Ãµµ
     *
     * @param string $mode : POST, GET Áß ÇÏ³ª¸¦ ÀÔ·ÂÇÑ´Ù.
     * @return bool
     */
    function Open($Methode="GET") {
        // À¥¼­¹ö¿¡ Á¢¼ÓÇÑ´Ù.
        if(!$this->fsockstream = fsockopen($this->address['host'], $this->address['port'], $errno, $errstr, 10))
			return false;
			//return "error[".$errno."] : ".$errstr;
		$this->setRequestHeader($Methode);
        fputs($this->fsockstream, $this->RequestHeader);
		return true;
    }

    /**
     * µ¥ÀÌÅ¸ Àü¼ÛÇÔ¼ö
     */
    function SendRequestHeader() {
        // Çì´õ ºÎºÐÀ» ±¸ÇÑ´Ù.
        $this->setResponseHeader();
    }

    /**
     * µ¥ÀÌÅ¸ Àü¼ÛÇÔ¼ö
     *
     * @return string
     */
    function SendRequestBody() {
        // Çì´õ ºÎºÐÀ» ±¸ÇÑ´Ù.
        $this->setResponseHeader();

        // ¹Ùµð ºÎºÐÀ» ±¸ÇÑ´Ù.
		$ResponseBody = $this->setResponseBody();

        return $ResponseBody;
    }

    /**
     * Çì´õ¸¦ ±¸ÇÏ´Â ÇÔ¼ö
     *
     * @param string $Status : ¿äÃ»Status°¡ ¾øÀ¸¸é Çì´õÀüÃ¼¸¦ ¹ÝÈ¯
     * @return string
     */
    function getResponseHeader($Status="") {
		if($Status && preg_match("/".$Status.": ([^\n]+)/", $this->ResponseHeader, $ret))
			return $ret[0];
        return $this->ResponseHeader;
    }

    /**
     * ÄíÅ°°ªÀ» ±¸ÇÏ´Â ÇÔ¼ö
     *
     * @param string $key : ÄíÅ°º¯¼ö
     * @return string or array
     */
    function getCookie($key="") {
        if($key && preg_match("/".$key."=([^;]+)/", $this->ResponseHeader, $ret)){
			return $ret[1];
        } else {
            preg_match_all("/Set-Cookie: [^\n]+/", $this->ResponseHeader, $ret);
            return $ret[0];
        }
    }

	function Close() {
        // Á¢¼ÓÀ» ÇØÁ¦ÇÑ´Ù.
        fclose($this->fsockstream);
	}
}
?>