<?php
GLOBAL $TOOLS_PATH;
include_once($TOOLS_PATH.'/Transfer.class.inc');
include_once($TOOLS_PATH.'/Database.class.inc');
include_once($TOOLS_PATH.'/CheckRemoteServer.class.inc');

class FileDirComparingView extends Slot {

	var $SectionID = 41;
	var $ModuleID = 4;
	var $servers = array();
	var $presets = array();
	var $files = array();
	var $report_type = array();
	var $reports = array();
	var $filepath = '';

	function __construct($pquery) {
		parent::__construct($pquery);
	}

	function init() {
		GLOBAL $ROOT_PATH, $TOOLS_PATH, $CORE_PATH;
		$this->Action->processEvent($this->SectionID, 'select_presets', array(), $this);
		$this->servers = $this->PreparedTemplates;
		$this->Scheme = 'default';
		if(!empty($this->Request)){
			if(empty($this->Request['form']['servers']) && empty($this->Request['form']['groups'])){
				$this->clearAllTemplates();
				header('Location: '.$this->Home.'/Registar/FileDirComparing'.$this->SID);
				return;
			}
			if(empty($this->Request['form']['servers'])) $this->Request['form']['servers'] = array();
			if(empty($this->Request['form']['groups'])) $this->Request['form']['groups'] = array();
			$this->Action->processEvent($this->SectionID, 'select_report_types', array(), $this);
			$this->report_type = $this->PreparedTemplates;
			if(@$this->LocalTarget[0] == 'Engine') $this->Action->processEvent($this->SectionID, 'select_engine_files', array(), $this);
			else $this->Action->processEvent($this->SectionID, 'select_files', array('md5' => true), $this);
			$this->files = $this->PreparedTemplates;
			if(!$this->dumpFileDir()){
				$this->clearAllTemplates();
				header('Location: '.$this->Home.'/Registar/FileDirComparing'.$this->SID);
				return;
			}
			eval(file_get_contents($CORE_PATH.'/signature.inc'));
			foreach($this->Request['form']['servers'] as $value)
				foreach($this->servers['1']['presets'] as $val){
					if ($val['id'] != $value) continue;
					$this->reports[$value] = array('hostid' => $value, 'hostname' => $val['name'], 'datetime' => date('Y-m-d H:i:s', time()), 'report' => array(), 'result' => '', 'successful' => 0);
					$CheckRemoteServer = new CheckRemoteServer($val);
					if($CheckRemoteServer->preActionCheck($signature['type_server'], 10)){ $this->presets[] = $val;}
					else foreach($CheckRemoteServer->errors as $v) $this->addToReport($value, $v, 0);
					break;
				}
			foreach($this->Request['form']['groups'] as $value){
				if(empty($this->servers[$value])) continue;
				$check = true;
				foreach($this->servers[$value]['presets'] as $val){
					$this->reports[$val['id']] = array('hostid' => $val['id'], 'hostname' => $val['name'], 'datetime' => date('Y-m-d H:i:s', time()), 'report' => array(), 'result' => '', 'successful' => 0);
					$CheckRemoteServer = new CheckRemoteServer($val);
					if(!$CheckRemoteServer->preActionCheck($signature['type_server'], 10)){
						$check = false;
						foreach($CheckRemoteServer->errors as $v) $this->addToReport($val['id'], $v, 0);
					}
				}
				if($check) $this->presets = array_merge($this->presets, $this->servers[$value]['presets']);
				else foreach($this->servers[$value]['presets'] as $val)
					if(empty($this->reports[$val['id']]['report'])) $this->addToReport($val['id'], 'Some server from the same PreSet group doesn\'t responding', 0);
			}
			foreach ($this->presets as $key => $value){
				if(!$this->transferFile($value)) continue;
				$this->launchScript($value);
				$this->getReport($value);
				$result = end($this->reports[$value['id']]['report']);
				if($result['type'] == array_search('Good', $this->report_type)) $this->reports[$value['id']]['successful'] = 1;
			}
			unlink($this->filepath);
			$this->Scheme = 'action';
		}
		$this->setSchemeTemplate($this->Scheme);
	}

	function fillElements() {
		switch($this->Scheme) {
			case 'default': $this->fillDefault(); break;
			case 'action': $this->fillAction(); break;
		}
	}

	function fillDefault() {
		if(@$this->LocalTarget[0] == 'Engine'){
			$this->TempFillEls['area'] = $this->LocalTarget[0];
		}
		foreach($this->servers as $value) {
			if($value['id'] == 1){
				foreach($value['presets'] as $v)
					$this->TempFillEls['servers'][] = array(
						'id' => inputCheckbox('form[servers][]', false, 'onClick = "CountCheckedPreset(this)"', $v['id']),
						'type' => '[SINGLE]',
						'name' => $v['name'],
						'list' => '&nbsp;',
					);
			}
			else{
				if (empty($value['presets'])) continue;
				$servers = array();
				$checked = false;
				foreach($value['presets'] as $v) 
					$servers[$v['id']] = $v['name'];
				$this->TempFillEls['servers'][] = array(
					'id' => inputCheckbox('form[groups][]', false, 'onClick = "CountCheckedPreset(this)"', $value['id']),
					'type' => '[GROUP]',
					'name' => $value['name'],
					'list' => '('.implode(', ', $servers).')',
				);
			}
		}
		$this->clearAllTemplates();
	}
	
	function fillAction(){
		if(@$this->LocalTarget[0] == 'Engine'){
			$this->TempFillEls['area'] = $this->LocalTarget[0];
			$checkbox_name = 'form[adds][]';
			$this->TempFillEls['entity'] = 'EnginePacket';
		}
		else {
			$checkbox_name = 'form[adds][5][]';
			$this->TempFillEls['entity'] = 'Package';
		}
		foreach($this->reports as $key => $value){
			$this->TempFillEls['presets'][$key] = array(
				'hostpath' => $value['hostname'],
				'hostid' => $value['hostid'],
				'datetime' => $value['datetime'],
			);
			foreach($value['report'] as $val){
				$checkbox = '&nbsp;';
				if($val['type'] == 4 && $value['successful']){
					preg_match('/^"[[:alnum:]-_\/\.]+"/', $val['message'], $matches);
					if(!empty($matches[0])) $checkbox = inputCheckbox($checkbox_name, false, 'onClick="CountChecked(this);"', str_replace('"', '', $matches[0]));
				}
				$this->TempFillEls['presets'][$key]['report'][] = array(
					'time' => $val['datetime'],
					'message' => $val['message'],
					'checkbox' => $checkbox,
					'type' => strtolower($this->report_type[$val['type']]),
				);
			}
			$this->TempFillEls['presets'][$key]['script_result'] = $value['result'];
			if(empty($value['result'])) $this->TempFillEls['presets'][$key]['script_result_display'] = 'none';
		}
		$this->clearAllTemplates();
	}
	
	function dumpFileDir(){
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$this->filepath = $ROOT_PATH.'/'.$COMMON_VARS['temp_dir'].'/filedir_'.md5(microtime()).'.inc';
		if(($file = @fopen($this->filepath, "w")) === false) return false;
		if(fwrite($file, '<?php'."\r\n".'$FileDir = '.var_export($this->files, true).';'."\r\n".'?>') === false) return false;
		include($this->filepath);
		if(!isset($FileDir) || !is_array($FileDir)) return false;
		return true;
	}
	
	function transferFile($preset){
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$Transfer = new Transfer();
		$Transfer->setopt(CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)');
		$Transfer->min_speed = 3600;
		$Transfer->dest_path = 'ftp://'.$preset['ftp_user'].':'.$preset['ftp_password'].'@'.$preset['ftp_host'].'/%2f'.$preset['ftp_folder'].$COMMON_VARS['upload_dir'].'/';
		$Transfer->src_path = dirname($this->filepath).'/';
		$Transfer->file = basename($this->filepath);
		$Transfer->sendFile();
		$Transfer->close();
		if(!empty($Transfer->errors)){
			foreach($Transfer->errors as $value) $this->addToReport($preset['id'], $value, 0);
			return false;
		}
		return true;
	}
	
	function launchScript($preset){
		$Transfer = new Transfer();
		$Transfer->setopt(CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)');
		$Transfer->dest_path = $preset['path'];
		$Transfer->file = 'receiver.php';
		$Transfer->variables = array(
			'type' => 'filedir_comparing',
			'filename' => basename($this->filepath),
			'username' => $this->Action->Security->currentuser->username,
			'hostpath' => $_SERVER['HTTP_HOST'],
		);
		$this->reports[$preset['id']]['result'] = $Transfer->launchScript();
		if(empty($this->reports[$preset['id']]['result'])) $this->reports[$preset['id']]['result'] = 'No debug result was retrieved from remote server';
		$Transfer->close();
		if (!empty($Transfer->errors)){
			foreach($Transfer->errors as $value) $this->addToReport($preset['id'], $value, 0);
			return false;
		}
		return true;
	}
	
	function getReport($preset){
		$Transfer = new Transfer();
		$Transfer->setopt(CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)');
		$Transfer->dest_path = $preset['path'];
		$SID = strtok($this->reports[$preset['id']]['result'], "\r\n");
		$SID = explode('=', $SID);
		$Transfer->file = 'get_session.php';
		$Transfer->variables = array($SID[0] => $SID[1],);
		$report = $Transfer->launchScript();
		$Transfer->close();
		if(@eval('$this->reports[$preset[\'id\']][\'report\'] = '.$report.';') === false)
			$this->addToReport($preset['id'], 'No report was retrieved from remote server', 0);
		if (!empty($Transfer->errors)){
			foreach($Transfer->errors as $value) $this->addToReport($preset['id'], $value, 0);
			return false;
		}
		return true;
	}
	
	function addToReport($id, $message, $type){
		$this->reports[$id]['report'][] = array(
			'datetime' => date('Y-m-d H:i:s', time()),
			'message' => $message,
			'type' => $type,
		);
	}
	
	function clearAllTemplates(){
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select_report_types');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select_files');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select_presets');
	}
}
?>