<?php
set_time_limit(1000);
$sessionHandling = 1;

include_once ("_dirinfo.php");
include_once (PATH_TO_ROOT."init.php");

include_once (PATH_TO_ROOT."_liveUpdate/class.capiMachine.php");


$capiMachine = new capiMachine($db);
$capiMachine->SetCapiServerOptions(configLoader::loadConfig('capi-server'));
//$capiMachine->SetCapiServerOptions(configLoader::loadConfig('capi-server'));

$capiMachine->GetMachine($_POST['client-machine-id']);

file_put_contents("/tmp/ifes-capi-server.txt","************* UPLOAD ******************\n\r",FILE_APPEND);
file_put_contents("/tmp/ifes-capi-server.txt","Macine ID - [".$_POST['client-machine-id']."] is active: ".$capiMachine->isActive()." and allow to upload data: ".$capiMachine->GetMachineInfo('allow_upload')."\n\r",FILE_APPEND);


 if ($capiMachine->isActive() && intval($capiMachine->GetMachineInfo('allow_upload')) == 1) {

		$upload_file = "capi-data-".date("mdY-his")."-".time().".xml";
		$fp = fopen(WARPIT_LIVEUPDATE_ZIPVERSION."/upload/".$upload_file, "w");
		fwrite($fp,$_POST['PostData']);
		fclose($fp);
		echo "1";
		
		//echo $_POST['PostData']."<br>";
		
		
		$oXML = new SimpleXMLElement("<xml>".$_POST['PostData']."</xml>");
		    
		//$oXML = new SimpleXMLElement("<xml>".file_get_contents("capi-data-08032012-022805-1343996885.xml")."</xml>");
		
		$UploadedProjects = array();
		
		foreach ($oXML->record as $rec) {
			$sqlf = array();
			//echo $rec->database."<br>";
			
			if ($rec->id_project) $UploadedProjects[intval($rec->id_project)] = intval($rec->id_project);
			
			if ($rec->table == "_capi_interviewer_visits") $rec->table = "_Capi_interviewer_visits";
			foreach (explode(",",$rec->listFields) as $f) {
				if ($f == 'id')  $id = $rec->fields->$f;
				elseif ($f == 'id_clien') $sqlf[] = $f." = '".$id."'";		
				else $sqlf[] = $f." = '".addslashes(strval(htmlspecialchars_decode($rec->fields->$f)))."'";
				
				
			}
			
			$sql =  "INSERT IGNORE INTO ".$dbConfig[strval($rec->database)].".".$rec->table."  SET ".implode(",",$sqlf);
			//echo $sql."<br>";
			$db->SQLexecute($sql);
		}
		
		$monitor = $oXML->updateMonitor;
		if ($monitor->project->statusesUser) 
			foreach ($monitor->project->statusesUser as $obj) if ($obj->status == 1) $goodIntOnServer += $obj->count;
		
		if ($monitor->project->statusesOtherUser) 
			foreach ($monitor->project->statusesOtherUser as $obj) if ($obj->status == 1)  $goodOtherIntOnServer += $obj->count;
		
		$sql = "INSERT INTO ".DB_WARPIT_LIVEUPDATE."._LiveUpdateLog SET
					dateDone 		= NOW(),
					project_id 		= '".$monitor->project->id."',
					user_id 		= '".$monitor->user_id."',
					browser			= '".addslashes($monitor->browser)."',
					version_start	= '".$monitor->versions->start."',
					version_stop	= '".$monitor->versions->stop."',
					tableCheckType	= '".addslashes($monitor->project->tableCheck->Msg_type)."',
					tableCheckText	= '".addslashes($monitor->project->tableCheck->Msg_text)."',
					uploadNumberRecords = '".$monitor->project->uploadNumberRecords."',
					capi_ok_records = '".$goodIntOnServer."'";
		
		$db->SQLexecute($sql);
		
		//echo $oXML->asXML();
		
		$sql = "INSERT INTO ".DB_WARPIT_LIVEUPDATE."._LiveUpdateLogRaw SET id = ".$db->GetLastInsertId().", fileData = '".addslashes($oXML->asXML())."'";
		$db->SQLexecute($sql);
		
		// Update quotas
		
		if ( $UploadedProjects ) { 
			
			$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			foreach ($UploadedProjects as $idProject) {
				//$idProject = 3;
				$sql = " SELECT proj_name FROM _Projects WHERE id = ".$idProject;
				$res = $db->SQLexecute($sql);
				$zad = $db->fetchAssoc($res);
				$projectName = $zad['proj_name'];
				
				$sql = "SHOW TABLES LIKE '".$projectName."___quotaCalc'";
				$res = $db->SQLexecute($sql);
				if ($db->NumRows($res)) {
					$sql = "DESCRIBE ".$projectName."___quotaCalc ";
					$res = $db->SQLexecute($sql);
					
					$fields_quota = array();
					$fields_structure = array();
					// getting structure of Quota table to know what to read from structure
					while ($zad = $db->fetchAssoc($res)) {
						
						// we need to make 2 arrays because some of field are different named in structure as in quota table
						// so we have 2 arrays, One to read from structure table $fields_structure and one for inserting into quota table $fields_quota
						$fields_quota[$zad['Field']] = $zad['Field'];
						if ($zad['Field'] == "QT_user_id") $zad['Field'] = "user_id";
						if ($zad['Field'] == "QT_user_type") $zad['Field'] = "user_type";				
						$fields_structure[$zad['Field']] = $zad['Field'];
					}
					
					$sql = "INSERT IGNORE INTO ".$projectName."___quotaCalc (".implode(",",$fields_quota).") 
								SELECT ".implode(",",$fields_structure)." FROM ".$projectName."_structure  
										WHERE user_id = '".$monitor->user_id."' AND status = 1 AND status_rec = 1 ";
					//echo $sql;
					$res = $db->SQLexecute($sql);
					
				}
			}
		
		}
		file_put_contents("/tmp/ifes-capi-server.txt","Upload done. \n\r",FILE_APPEND);
} else {
	echo "0";
	file_put_contents("/tmp/ifes-capi-server.txt","NO UPLOAD because of restrictions.\n\r",FILE_APPEND);
}

file_put_contents("/tmp/ifes-capi-server.txt","************* END UPLOAD ******************\n\r",FILE_APPEND);
?>