<?php 

class liveupdateWarpit {

	public $client_project;
	private $serverAddress;
	private $versionsToDownload = array();	
	private $clientVersion;
	private $zipFilesPath;
	private $localContainer;
	private $dbConfig;
	private $newLine = "\r\n";
	
	
	public function __construct($db) {
		$this->db = $db;
		// default setup, which table records should be transfered from client to server
	
	}
	
	/**
	 * Define server address
	 *
	 * @param string $aPath
	 */
	public function SetServerAddress($aPath) { $this->serverAddress = $aPath; }
	
	public function SetDatabaseConfig($aConfig) { $this->dbConfig = $aConfig; }

	/**
	 * define version of program and database on client side
	 *
	 * @param string $a
	 */
	public function SetClientVersion($a) { $this->clientVersion = $a; }
	public function GetClientVersion() { return $this->clientVersion; }
	
	public function SaveClientVersion() {
		$sql = "UPDATE ".DB_WARPIT_MAIN."._WarpitConfig  SET cValue = '".$this->clientVersion."' WHERE cName = 'warpit_version'";
		$this->db->SQLexecute($sql);
	}
	
	/**
	 * define http remote path where we can find update files
	 *
	 * @param string $a
	 */
	public function SetZipFilesPath($a) { $this->zipFilesPath = $a; }
	
	/**
	 * absolute path to local container, where I will save updates
	 *
	 * @param string $a
	 */
	public function SetLocalFileContainer($a) { $this->localContainer = $a; }
	
	
	/**
	 * all informations from user needed to make complete live update
	 *
	 * @param unknown_type $ar
	 */
	public function SetUserParameter($ar = array()) {
		foreach ($ar as $key=>$val) $this->UserParams[$key] = $val;
	}
	
		
	/**
	 * Check for new versions on server and manage them
	 * Function returns array with all version numbers which are missing on client side
	 *
	 * @return unknown
	 */
	public function curl_getVersionControl($aCurrentPropreties) {
		
		$this->SetClientVersion($aCurrentPropreties['warpit_version']);
		
		$ch = curl_init(); 
	    curl_setopt($ch, CURLOPT_URL,$this->serverAddress."Warpit-Updater/Warpit-Version-Control.php?client_app_key=".$aCurrentPropreties['warpit_license_key']."&client_version=".$this->GetClientVersion()); 
//echo $this->serverAddress."Warpit-Updater/Warpit-Version-Control.php?client_app_key=".$aCurrentPropreties['warpit_license_key']."&client_version=".$this->GetClientVersion();

	    curl_setopt($ch, CURLOPT_FAILONERROR,1); 
	    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); 
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
	    curl_setopt($ch, CURLOPT_TIMEOUT, 15); 
	    $xmlValue = curl_exec($ch);                       
		if (!$xmlValue) {
			echo curl_error($ch);
			exit;
		}
	    
	    curl_close($ch); 
	   
	    if ($xmlValue[0] == "0") echo $xmlValue;
	    else {
	   
	        $oXML = new SimpleXMLElement($xmlValue); 
			foreach ($oXML->version as $ver) {
				unset($tmp);
				$tmp['label'] = $ver->version_label;
				$tmp['id'] = $ver->id;
				$tmp['version_file'] = $ver->version_file;
				$this->versionsToDownload[] = $tmp;
			}
			return $this->versionsToDownload;
	    }
			
	}
	
	
	function doVersionUpdate() {
		
		// we don't have nothing to do
		if (!$this->versionsToDownload) exit;
		
		// now go step by step and do next action
		// 1. download oldest update
		// 2. unpack it
		// 3. update programs
		// 4. update webprojects directory
		// 5. update sql
		// 6. define new client version
		
		foreach ($this->versionsToDownload as $ver) {
			
			// 1. download update
				if ($this->curl_getFromServer($ver['version_file'])) {
					
					$zip = new ZipArchive();					
					$zip->open("../../_backup/_downloadFiles/".$ver['version_file']);
					// 2. unpack it
					$zip->extractTo("../../_backup/_downloadFiles/".$ver['id']."/"); 
					$zip->close(); 
					
					$oXML = new SimpleXMLElement(file_get_contents("../../_backup/_downloadFiles/".$ver['id']."/file-action.xml")); 
					foreach ($oXML->file as $file) {
						if ($file->action == 'copy') {
							// 3. update programs 
							if ($file->directory) @mkdir(WARPIT_ABSOLUTE.$file->directory);
							copy("../../_backup/_downloadFiles/".$ver['id']."/files/".$file->directory.$file->filename, WARPIT_ABSOLUTE.$file->directory.$file->filename);						
						} 
					}
						echo "<p>Upgrade to version <b>".$ver['label']."</b> finished</p>";
					// 6. define new client version
						$this->SetClientVersion($ver['label']);
						$this->SaveClientVersion();
				}
			
		}
		
	}
	
	public function curl_getFromServer($aFile) {
			
			$ch = curl_init();
			$fp = fopen("../../_backup/_downloadFiles/".$aFile, "w"); 
			
			curl_setopt($ch, CURLOPT_USERAGENT, "'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20120427 Firefox/15.0a1'");
			
			curl_setopt($ch, CURLOPT_URL,$this->serverAddress."Warpit-Updater/_files/".$aFile);
			//echo $this->serverAddress."Warpit-Updater/_files/".$aFile;
			curl_setopt($ch, CURLOPT_FAILONERROR, true);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
			curl_setopt($ch, CURLOPT_AUTOREFERER, true);
			curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
			curl_setopt($ch, CURLOPT_TIMEOUT, 1000);
			curl_setopt($ch, CURLOPT_FILE, $fp);
			$status = curl_exec($ch);
			curl_close($ch);
			
			return $status;
	}	
	
}

?>