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

class DeletedObjectsProcessingView extends Slot {

	var $SectionID = 42;
	var $ModuleID = 4;
	var $servers = array();
	var $presets = array();
	var $publish_type = array();
	var $report_type = array();
	var $reports = array();
	var $report_receivers = array();
	var $deleted = array();
	var $check = true;
	var $referer = '';

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

	function init() {
		GLOBAL $ROOT_PATH, $TOOLS_PATH, $CORE_PATH, $COMMON_VARS, $MailBroker, $REGISTRY;
		if(!empty($this->Request['form']['referer'])) $this->referer = $this->Request['form']['referer'];
		else{
			$this->referer = parse_url(getenv('HTTP_REFERER'));
			$this->referer = $this->referer['path'];
		}
		if(empty($this->referer) || strpos($this->referer, '/Registar/DeletedObjectsProcessing') === 0) $this->referer = '/Registar/DeletedObjectsProcessing';
		switch(@$this->LocalTarget[0]) {
			case 'Process': {
				if(empty($this->Request)){
					header('Location: '.$this->Home.'/Registar/DeletedObjectsProcessing'.$this->SID);
					return;
				}
				$this->Action->processEvent($this->SectionID, 'select_publish_types', array(), $this);
				$this->publish_type = $this->PreparedTemplates;
				$this->Action->processEvent($this->SectionID, 'select_report_types', array(), $this);
				$this->report_type = $this->PreparedTemplates;
				$this->Action->processEvent($this->SectionID, 'select_presets', array(), $this);
				$this->servers = $this->PreparedTemplates;
				$this->Action->processEvent($this->SectionID, 'select_report_receivers', array(), $this);
				$this->report_receivers = $this->PreparedTemplates;
				$this->clearAllTemplates();
				$this->Scheme = 'default';
				break;
			}
			default: {
				$this->Action->processEvent($this->SectionID, 'select_presets', array('changed_urls_check' => true), $this);
				$this->servers = $this->PreparedTemplates;
				$this->clearAllTemplates();
				$this->Scheme = 'default';
				break;
			}
		}
		if(empty($this->Request)){
			$this->setSchemeTemplate($this->Scheme);
			return;
		}
		switch(@$this->LocalTarget[0]) {
			case 'Process': {
				if(empty($this->Request['form']['servers']) && empty($this->Request['form']['groups'])) break;
				if(empty($this->Request['form']['servers'])) $this->Request['form']['servers'] = array();
				if(empty($this->Request['form']['groups'])) $this->Request['form']['groups'] = array();
				if(isset($this->Request['form']['check'])) $this->check = $this->Request['form']['check'];
				$MailTemplate = array();
				$preurl = 'http://'.$_SERVER['HTTP_HOST'].'/Registar/DeletedObjectsProcessingReport/View/';
				eval(file_get_contents($CORE_PATH.'\signature.inc'));
				foreach($this->Request['form']['servers'] as $value){
					$this->reports[$value] = array('host' => $value, 'date_processed' => 'now', 'userid' => $this->Action->Security->currentuser->id, 'type' => 1, 'report' => array(),);
					foreach($this->servers['1']['presets'] as $val){
						if ($val['id'] != $value) continue;
						$CheckRemoteServer = new CheckRemoteServer($val);
						if($CheckRemoteServer->preActionCheck($signature['type_server'], 30))
							$this->presets[] = $val;
						else{
							foreach($CheckRemoteServer->errors as $v)
								$this->toReport($this->reports[$val['id']], $v, 0);
							$this->Action->processEvent($this->SectionID, 'save_processing', $this->reports[$value], $this);
							$MailTemplate['presets'][] = array('host' => $_SERVER['SERVER_NAME'], 'user' => $this->Action->Security->currentuser->username, 'datetime' => date('Y-m-d H:i:s', time()), 'hostname' => $val['name'], 'hostpath' => $val['path'], 'result' => 'Failed', 'url' => $preurl.$this->PreparedTemplates['id'],);
							$this->reports[$value] = $this->PreparedTemplates;
						}
						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('host' => $val['id'], 'date_processed' => 'now', 'userid' => $this->Action->Security->currentuser->id, 'type' => 1, 'report' => array(),);
						$CheckRemoteServer = new CheckRemoteServer($val);
						if(!$CheckRemoteServer->preActionCheck($signature['type_server'], 30)){
							$check = false;
							foreach($CheckRemoteServer->errors as $v)
								$this->toReport($this->reports[$val['id']], $v, 0);
							$this->Action->processEvent($this->SectionID, 'save_processing', $this->reports[$val['id']], $this);
							$MailTemplate['presets'][] = array('host' => $_SERVER['SERVER_NAME'], 'user' => $this->Action->Security->currentuser->username,'datetime' => date('Y-m-d H:i:s', time()), 'hostname' => $val['name'], 'hostpath' => $val['path'], 'result' => 'Failed', 'url' => $preurl.$this->PreparedTemplates['id'],);
							$this->reports[$val['id']] = $this->PreparedTemplates;
						}
					}
					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->toReport($this->reports[$val['id']], 'Some server from the same PreSet group doesn\'t responding', 0);
							$this->Action->processEvent($this->SectionID, 'save_processing', $this->reports[$val['id']], $this);
							$MailTemplate['presets'][] = array('host' => $_SERVER['SERVER_NAME'], 'user' => $this->Action->Security->currentuser->username, 'datetime' => date('Y-m-d H:i:s', time()), 'hostname' => $val['name'], 'hostpath' => $val['path'], 'result' => 'Failed', 'url' => $preurl.$this->PreparedTemplates['id'],);
							$this->reports[$val['id']] = $this->PreparedTemplates;
						}
					}
				}
				foreach ($this->presets as $key => $value){
					$this->Action->processEvent($this->SectionID, 'get_deleted', array('id' => $value['id']), $this);
					$this->deleted[$value['id']] = $this->PreparedTemplates;
					if(empty($this->deleted[$value['id']])){
						$this->toReport($this->reports[$value['id']], 'There are no deleted objects to process', 5);
						$this->toReport($this->reports[$value['id']], 'Deleted objects processing successful', 1);
						$this->reports[$value['id']]['successful'] = 1;
						$this->Action->processEvent($this->SectionID, 'save_processing', $this->reports[$value['id']], $this);
						$MailTemplate['presets'][] = array('host' => $_SERVER['SERVER_NAME'], 'user' => $this->Action->Security->currentuser->username, 'datetime' => date('Y-m-d H:i:s', time()), 'hostname' => $value['name'], 'hostpath' => $value['path'], 'result' => 'Successful', 'url' => $preurl.$this->PreparedTemplates['id'],);
						$this->reports[$value['id']] = $this->PreparedTemplates;
						continue;
					}
					if(($filepath = $this->dumpDeletedObjectsArray($this->deleted[$value['id']])) === false){
						$this->toReport($this->reports[$value['id']], 'Can not make deleted objects array file', 0);
						$this->toReport($this->reports[$value['id']], 'Deleted objects processing failed', 7);
						$this->Action->processEvent($this->SectionID, 'save_processing', $this->reports[$value['id']], $this);
						$MailTemplate['presets'][] = array( 'host' => $_SERVER['SERVER_NAME'], 'user' => $this->Action->Security->currentuser->username, 'datetime' => date('Y-m-d H:i:s', time()), 'hostname' => $value['name'], 'hostpath' => $value['path'], 'result' => 'Failed', 'url' => $preurl.$this->PreparedTemplates['id'],);
						$this->reports[$value['id']] = $this->PreparedTemplates;
						continue;
					}
					if($this->transferFile($value, $filepath, true)){
						$this->launchScript($value, basename($filepath));
						$not_deleted = $this->getReport($value, $processingid);
						$result = end($this->reports[$value['id']]['report']);
						if(!empty($processingid)) $this->putRemoteReport($value, $processingid);
						if($result['type'] == array_search('Good', $this->report_type)){
							$this->reports[$value['id']]['successful'] = 1;
							$request = array('id' => $value['id'], 'exception' => $not_deleted);
							$this->Action->processEvent($this->SectionID, 'clean_deleted', $request, $this);
							if(!empty($this->PreparedTemplates['_error'])) $this->toReport($this->reports[$value['id']], $this->PreparedTemplates['_error'], 6);
						}
					}
					$this->Action->processEvent($this->SectionID, 'save_processing', $this->reports[$value['id']], $this);
					$MailTemplate['presets'][] = array('host' => $_SERVER['SERVER_NAME'], 'user' => $this->Action->Security->currentuser->username, 'datetime' => $result['datetime'], 'hostname' => $value['name'], 'hostpath' => $value['path'], 'result' => @$this->reports[$value['id']]['successful'] == 1 ? 'Successful' : 'Failed', 'url' => $preurl.$this->PreparedTemplates['id'],);
					$this->reports[$value['id']] = $this->PreparedTemplates;
				}
				$MailBroker->sendMail('deletedobjects', $this->report_receivers, $MailTemplate);
				break;
			}
		}
		$this->setSchemeTemplate($this->Scheme);
	}

	function fillElements() {
		switch($this->Scheme) {
			case 'default': $this->fillDefault(); break;
		}
	}
	
	function fillDefault() {
		$this->TempFillEls['form_referer'] = inputHidden('form[referer]', $this->referer);
		$this->TempFillEls['referer'] = $this->referer;
		switch(@$this->LocalTarget[0]) {
			case 'Process': {
				$this->TempFillEls['servers_display'] = 'none';
				$this->TempFillEls['btnProcess_disp'] = 'none';
				foreach($this->reports as $key => $value){
					$this->TempFillEls['processing'][$key] = array(
						'id' => $value['id'],
						'hostpath' => $value['hostpath'],
						'hostid' => $value['host'],
						'username' => $value['username'],
						'userid' => $value['userid'],
						'date_processed' => $value['date_processed'],
					);
					foreach($value['report'] as $ind => $val){
						$this->TempFillEls['processing'][$key]['report'][$ind] = array(
							'datetime' => $val['datetime'],
							'message' => $val['message'],
							'type' => strtolower($this->report_type[$val['type']]),
						);
					}
					if (empty($value['result'])) $this->TempFillEls['processing'][$key]['script_result_disp'] = 'none';
					$this->TempFillEls['processing'][$key]['script_result'] = $value['result'];
				}
				break;
			}
			default: {
				$this->TempFillEls['reports_disp'] = 'none';
				$this->TempFillEls['form_check'] = inputHidden('form[check]', '0').inputCheckbox('form[check]', true, '', '1');
				$this->tempFillServersEls();
				break;
			}
		}
		$this->clearAllTemplates();
	}
	
	function tempFillServersEls(){
		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).')',
				);
			}
		}
	}
	
	function toReport(&$array, $message, $type){
		$array['report'][] = array(
			'datetime' => date('Y-m-d H:i:s', time()),
			'message' => $message,
			'type' => $type,
		);
	}
	
	function dumpDeletedObjectsArray($array){
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$filepath = $ROOT_PATH.'/'.$COMMON_VARS['temp_dir'].'/'.$array[0]['preset'].'_'.getUnique32().'.inc';
		if(($file = @fopen($filepath, "w")) === false) return false;
		$string = '<?php'."\r\n".'$DeletedObjects = '.var_export($array, true).';'."\r\n".'?>';
		if(fwrite($file, $string) === false) return false;
		include_once($filepath);
		if(!isset($DeletedObjects) || !is_array($DeletedObjects)) return false;
		return $filepath;
	}
	
	function transferFile($preset, $filepath, $delete = false){
		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($filepath).'/';
		$Transfer->file = basename($filepath);
		if($delete) $Transfer->delete = true;
		$Transfer->sendFile();
		$Transfer->close();
		if(!empty($Transfer->errors)){
			foreach($Transfer->errors as $value) $this->toReport($this->reports[$preset['id']], $value, 0);
			return false;
		}
		return true;
	}
	
	function launchScript($preset, $filename){
		$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' => 'deleted',
			'username' => $this->Action->Security->currentuser->username,
			'hostpath' => $_SERVER['HTTP_HOST'],
			'filename' => $filename,
			'check' => $this->check,
		);
		$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->toReport($this->reports[$preset['id']], $value, 0);
			return false;
		}
		return true;
	}
	
	function getReport($preset, &$processingid){
		$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->toReport($this->reports[$preset['id']], 'No publish report was retrieved from remote server', 0);
		if (!empty($Transfer->errors)){
			foreach($Transfer->errors as $value) $this->toReport($this->reports[$preset['id']], $value, 0);
			return false;
		}
		$not_deleted = array();
		foreach($this->reports[$preset['id']]['report'] as $value){
			switch($value['type']){
				case 5: case 6: {
					preg_match('/\(uid = "[[:alnum:]]{32,32}"/', $value['message'], $matches);
					preg_match('/[[:alnum:]]{32,32}/', $matches[0], $uid);
					$not_deleted[] = $uid[0];
					break;
				}
				case 9: {
					if(preg_match('/Processing remote ID \[[0-9]+\]/i', $value['message'])){
						preg_match('/[0-9]+/', $value['message'], $matches);
						$processingid = $matches[0];
					}
					break;
				}
			}
		}
		return $not_deleted;
	}
	
	function putRemoteReport($preset, $processingid){
		if(empty($processingid)) return false;
		$Database = new Database($preset['db_host'], $preset['db_name'], $preset['db_user'], $preset['db_password'], $preset['db_port']);
		if($Database->connect()){
			if(!$Database->update('deletedprocessing', array('result' => $this->reports[$preset['id']]['result']), array('id' => $processingid)))
				$this->reports[$preset['id']]['report'][] = array('datetime' => date('Y-m-d H:i:s', time()), 'message' => 'Couldn\'t put deleted objects processing debug result to remote database', 'type' => 6);
			$Database->close();
			return true;
		}
		return false;
	}
	
	function clearAllTemplates(){
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select_publish_types');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select_report_types');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select_presets');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select_report_receivers');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'save_processing');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'get_deleted');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'clean_deleted');
	}
}
?>