<?php

	/*
	*	Gekko - Open Source Web Development Framework
	*	------------------------------------------------------------------------
	*	Copyright (C) 2004-2005, J. Carlos Nieto <xiam@users.sourceforge.net>
	*	This program is Free Software.
	*
	*	@package	Gekko
	*	@license	http://www.gnu.org/copyleft/gpl.html GNU/GPL License 2.0
	*	@author		J. Carlos Nieto <xiam@users.sf.net>
	*	@version	CVS: $Id:$
	*	@link		http://www.gekkoware.org
	*/

	if (!defined("IN-GEKKO")) die("Get a life!");

	//header("content-type: text/plain");

	define("REMOTECONN_DEBUG", false);

	Class remoteConnection {

		var $socket;
		var $errno;
		var $errstr;
		var $timeout = 3;
		var $last_svr_response;
		var $status = 0;

		function remoteConnection($host, $port) {
			return $this->status = $this->open($host, $port);
		}

		// opens a new connection
		function open($host, $port) {

			$con_stat = 1;

			$key = cache_assign_key($host, $port);

			if ((($life = cache_check_life($key)) !== false) && ((time() - $life) < 300)) {
				// checking flag status
				cache_read($key, $con_stat);
			}

			if ($con_stat) {
				$this->socket = @fsockopen($host, $port, $this->errno, $this->errstr, $this->timeout);

			}
			// is $con_stat has changed...
			if ($con_stat != ($tmp_stat = intval(is_resource($this->socket)))) {
				cache_save($key, $tmp_stat);
			}

			return ($con_stat) ? $this->socket : false;
		}

		function status() {
			return is_resource($this->socket);
		}

		// writes a response to server
		function write($data) {
			if (!$this->socket) return -1;
			$this->debug("C", $data);
			return fwrite($this->socket, $data);
		}

		// prints debug messages if enabled.
		function debug($id, $string) {
			if (REMOTECONN_DEBUG  == 1) {
				echo "$id: ".trim($string)."\n";
			}
		}

		// returns|sets last server response.
		function last($svr_response = null) {
			if ($svr_response) $this->last_svr_response = $svr_response;
			return $this->last_svr_response;
		}

		// reads data from server
		function read($all = false) {

			$data = "";
			if ($this->status()) {
				stream_set_timeout($this->socket, $this->timeout);

				do {
					$buff = fread($this->socket, 1024*8);

					$data .= $buff;

					$meta = stream_get_meta_data($this->socket);

					if ($meta["timed_out"] || ($all && $meta["eof"]) || (!$all && !$meta["unread_bytes"])) {
						break;
					}

				} while (!feof($this->socket));

	/*
				while (strlen($buff = fread($this->socket, 1024*8))) {
					$data .= $buff;
				}
	*/
				$this->debug("S", $this->last($data));
			}

			return $data;

		}

		// closes remote connection
		function close() {
			fclose($this->socket);
		}
	}

?>