<?php
GLOBAL $ROOT_PATH, $TOOLS_PATH, $COMMON_VARS;
include_once($ROOT_PATH.'/engine/Tools/class.curl.php');
include_once($ROOT_PATH.'/engine/Tools/func.php');
include_once($TOOLS_PATH.'/func.php');
include_once($ROOT_PATH.'/engine/Tools/data_class.php');

class Transfer extends curl {
	
	var $src_path;
	var $file;
	var $dest_path;
	var $variables = array();
	var $errors = array();
	var $min_speed = 0;
	var $timeout = 0;
	var $delete = false;
	
	function Transfer(){
		$this->curl();
	}
	
	function setOptions($options = array()){
		foreach($options as $key => $value)
			if(!$this->setopt($key, $value)){
				$this->errors[] = 'Cannot set transfer option "'.$key.'" = "'.$value.'"';
				return false;
			}
		return true;
	}
	
	function sendFile(){
		if ($this->m_handle == NULL)
			$this->curl();
		$res = @fopen($this->src_path.$this->file, 'r');
		if ($res === false){
			$this->errors[] = 'Cannot get resource of file "'.$this->src_path.$this->file.'"';
			return false;
		}
		$filesize = filesize($this->src_path.$this->file);
		if($this->min_speed){
			$timeout = (int)($filesize / $this->min_speed) + 15;
			$this->setopt(CURLOPT_TIMEOUT, $timeout);
		}
		if($this->timeout)
			$this->setopt(CURLOPT_TIMEOUT, $this->timeout);
		$this->setopt(CURLOPT_INFILE, $res);
		$this->setopt(CURLOPT_INFILESIZE, $filesize);
		$this->setopt('CURLOPT_FTPASCII', 0);
		$this->setopt(CURLOPT_RETURNTRANSFER, 1);
		$this->setopt(CURLOPT_UPLOAD, 1);
		$this->setopt(CURLOPT_URL, $this->dest_path.$this->file);
		$this->exec();
		fclose($res);
		if($this->delete)
			mysystem('rm -rf '.$this->src_path.$this->file);
		if(!empty($this->m_status['error'])){
			$this->errors[] = $this->m_status['error'];
			return false;
		}
		if(!empty($this->m_status['errno'])){
			$this->errors[] = 'Unexpected transfer error #'.$this->m_status['errno'];
			return false;
		}
		return true;
	}
	
	function launchScript(){
		if ($this->m_handle == NULL)
			$this->curl();
		$url = $this->dest_path.$this->file;
		if(!empty($this->variables)){
			$this->setopt(CURLOPT_POST, 1);
			$request = array();
			foreach($this->variables as $key => $value)
				$request[] = $key.'='.$value;
			$request = implode('&', $request);
			$this->setopt(CURLOPT_POSTFIELDS, $request);
		}
		$this->setopt(CURLOPT_URL, $url);
		$this->setopt(CURLOPT_HEADER, 0);
		$this->setopt(CURLOPT_RETURNTRANSFER, 1);
		$result = $this->exec();
		if(!empty($this->m_status['error'])){
			$this->errors[] = $this->m_status['error'];
			return false;
		}
		return $result;
	}
	
	function clearErrors(){
		$this->errors = array();
	}
	
}

?>