<?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');
include_once($TOOLS_PATH.'/EnginePacketDump.class.inc');

class EnginePacketManagerView extends Slot {

	var $SectionID = 33;
	var $ModuleID = 4;
	var $packets = array();
	var $packet = array();
	var $actiontype = array();
	var $actionable = true;
	var $adds = array();
	var $servers = array();
	var $presets = array();
	var $reporttype = array();
	var $prepacket = array();
	var $report_receivers = array();
	var $MailTemplate = array();
	var $search_conditions = array('not_older' => '0', 'packed' => '0', 'unpacked' => '0', 'published' => '0', 'inpublished' => '0', 'contained' => array(),);
	var $founded_packets = array();
	var $search_time_intervals = array('X' => '0', '3 days' => '259200', '1 week' => '604800', '10 days' => '864000', '2 weeks' => '1209600', '3 weeks' => '1814400', '1 month' => '2592000', '2 months' => '5184000', '3 months' => '7776000',);

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

	function init() {
		GLOBAL $ROOT_PATH, $TOOLS_PATH, $CORE_PATH, $COMMON_VARS, $MailBroker;
		$this->packets = $this->Action->Server->getGuide('enginepacket');
		$this->actiontype = $this->Action->Server->getGuide('enginepacketactiontype');
		$this->Action->processEvent($this->SectionID, 'select_report_type', array(), $this);
		$this->reporttype = $this->PreparedTemplates;
		if(!isset($this->LocalTarget[0])) $this->LocalTarget[0] = false;
		if($this->LocalTarget[0] !== false && !is_numeric($this->LocalTarget[0])){
			if((empty($this->LocalTarget[1]) || !isset($this->packets[$this->LocalTarget[1]])) && $this->LocalTarget[0] != 'Add' && $this->LocalTarget[0] != 'AddItem' && $this->LocalTarget[0] != 'ObjectView' && $this->LocalTarget[0] != 'Search') return $this->terminateAction();
		}
		switch($this->LocalTarget[0]) {
			case 'Lock': {
				$this->Action->processEvent($this->SectionID, 'get_access', array('id' => $this->LocalTarget[1]), $this);
				if(empty($this->PreparedTemplates['access_flag'])) $this->Action->processEvent($this->SectionID, 'set_access', array('id' => $this->LocalTarget[1], 'name' => $this->PreparedTemplates['name'], 'access_flag' => $this->Action->Security->currentuser->id), $this);
				return $this->terminateAction();
				break;
			}
			case 'Unlock': {
				$this->Action->processEvent($this->SectionID, 'get_access', array('id' => $this->LocalTarget[1]), $this);
				if($this->PreparedTemplates['access_flag'] == $this->Action->Security->currentuser->id) $this->Action->processEvent($this->SectionID, 'set_access', array('id' => $this->LocalTarget[1], 'name' => $this->PreparedTemplates['name'], 'access_flag' => 0), $this);
				return $this->terminateAction();
				break;
			}
			case 'Update': {
				$this->Scheme = 'action';
				$this->Action->processEvent($this->SectionID, 'get_access', array('id' => $this->LocalTarget[1]), $this);
				if($this->PreparedTemplates['actioned']) return $this->terminateAction();
				else if(empty($this->PreparedTemplates['access_flag'])) $this->Action->processEvent($this->SectionID, 'set_access', array('id' => $this->LocalTarget[1], 'name' => $this->PreparedTemplates['name'], 'access_flag' => $this->Action->Security->currentuser->id), $this);
				else if($this->PreparedTemplates['access_flag'] != $this->Action->Security->currentuser->id) return $this->terminateAction();
				if(empty($this->Request)){
					$this->Action->processEvent($this->SectionID, 'open', array('id' => $this->LocalTarget[1]), $this);
					$this->packet = $this->PreparedTemplates;
					$this->initAdds();
				}
				break;
			}
			case 'Delete': case 'Pack': case 'Unpack': case 'Publish': {
				$this->Scheme = 'action';
				$this->Action->processEvent($this->SectionID, 'get_access', array('id' => $this->LocalTarget[1]), $this);
				if($this->LocalTarget[0] == 'Pack' && $this->PreparedTemplates['actioned']) return $this->terminateAction();
				else if(empty($this->PreparedTemplates['access_flag'])) $this->Action->processEvent($this->SectionID, 'set_access', array('id' => $this->LocalTarget[1], 'name' => $this->PreparedTemplates['name'], 'access_flag' => $this->Action->Security->currentuser->id), $this);
				else if($this->PreparedTemplates['access_flag'] != $this->Action->Security->currentuser->id) return $this->terminateAction();
				$this->Action->processEvent($this->SectionID, 'open', array('id' => $this->LocalTarget[1]), $this);
				$this->packet = $this->PreparedTemplates;
				if($this->LocalTarget[0] == 'Publish'){
					$this->Action->processEvent($this->SectionID, 'select_presets', array(), $this);
					$this->servers = $this->PreparedTemplates;
				}
				break;
			}
			case 'Add': {
				$this->Scheme = 'action';
				if(empty($this->Request)){
					$this->Action->processEvent($this->SectionID, 'open', array(), $this);
					$this->packet = $this->PreparedTemplates;
					$this->initAdds();
				}
				break;
			}
			case 'Duplicate': {
				$this->Scheme = 'action';
				$this->Action->processEvent($this->SectionID, 'open', array('id' => $this->LocalTarget[1], 'action' => $this->LocalTarget[0]), $this);
				$this->packet = $this->PreparedTemplates;
				$this->initAdds();
				break;
			}
			case 'View': {
				$this->Scheme = 'action';
				$this->Action->processEvent($this->SectionID, 'open', array('id' => $this->LocalTarget[1]), $this);
				$this->packet = $this->PreparedTemplates;
				break;
			}
			case 'ObjectView': {
				$this->Scheme = 'objectview';
				$this->Action->processEvent($this->SectionID, 'open_item', array('id' => $this->LocalTarget[1]), $this);
				if(empty($this->Request)) $this->extractObject($this->PreparedTemplates['filename'], $this->PreparedTemplates['object']);
				break;
			}
			case 'AddItem': {
				if(empty($this->Request['sbtAddItem'])){
					if(empty($this->Request['form']['adds'])) return $this->terminateAction();
					$this->Request['form']['adds'] = array_unique($this->Request['form']['adds']);
					$this->Action->processEvent($this->SectionID, 'select', array('all_addable' => true, 'user' => $this->Action->Security->currentuser->id,), $this);
				}
				else if(empty($this->Request['form']['packet'])) return $this->terminateAction();
				else{
					$preparedTemplates = array();
					$count = count($this->Request['form']['packet']);
					for($i = 0; $i < $count; $i++){
						$this->Action->processEvent($this->SectionID, 'get_access', array('id' => $this->Request['form']['packet'][$i]), $this);
						$preparedTemplates[] = $this->PreparedTemplates;
					}
					$this->PreparedTemplates = $preparedTemplates;
					unset($preparedTemplates);
				}
				$this->Scheme = 'add';
				break;
			}
			case 'Search': {
				$this->clearAllTemplates();
				$this->Scheme = 'search';
				break;
			}
			default: {
				$this->Scheme = 'default';
				$request['pageRecordsQty'] = 50;
				$request['curPageNumber'] = intval($this->LocalTarget[0]) + 1;
				$this->Action->processEvent($this->SectionID, 'select', $request, $this);
				break;
			}
		};
		if(empty($this->Request)){
			$this->setSchemeTemplate($this->Scheme);
			return;
		}
		switch($this->LocalTarget[0]) {
			case 'Update': case 'Add': case 'Duplicate': {
				if(!empty($this->Request['form']['adds'])){
					$count = count($this->Request['form']['adds']);
					$count_items = isset($this->Request['form']['items']) ? count($this->Request['form']['items']) : 0;
					for ($i = 0; $i < $count; $i++){
						for ($j = 0; $j < $count_items; $j++)
							if($this->Request['form']['items'][$j]['object'] == $this->Request['form']['adds'][$i]) continue 2;
						$this->Request['form']['items'][]['object'] = $this->Request['form']['adds'][$i];
						$count_items++;
					}
				}
				unset($this->Request['form']['adds']);
				if(!empty($this->Request['form']['compile'])){
					$this->initAdds();
					$this->Action->processEvent($this->SectionID, 'open', $this->Request['form'], $this);
				}
				else if($this->validateForm()){
					if($this->Action->processEvent($this->SectionID, 'save', $this->Request['form'], $this)) return $this->terminateAction();
				}
				else{
					$this->initAdds();
					$this->Action->processEvent($this->SectionID, 'open', array_merge($this->Request['form'], array('compile' => true)), $this);
				}
				$this->packet = $this->PreparedTemplates;
				break;
			}
			case 'Delete': {
				if($this->Action->processEvent($this->SectionID, 'delete', array('id' => $this->LocalTarget[1]), $this)){
					$this->deletePacketFile();
					return $this->terminateAction();
				}
				break;
			}
			case 'AddItem': {
				if(empty($this->Request['sbtAddItem'])) break;
				$packets = $this->PreparedTemplates;
				$count = count($packets);
				$adds_count = count($this->Request['form']['adds']);
				for ($i = 0; $i < $count; $i++){
					if(!empty($packets[$i]['actioned']) || (!empty($packets[$i]['access_flag']) && $packets[$i]['access_flag'] != $this->Action->Security->currentuser->id) || !isset($this->packets[$packets[$i]['id']])) continue;
					$this->Action->processEvent($this->SectionID, 'open', array('id' => $packets[$i]['id'], 'action' => 'AddItem',), $this);
					$packet = $this->PreparedTemplates;
					$items_count = count($packet['items']);
					for ($j = 0; $j < $adds_count; $j++){
						for($k = 0; $k < $items_count; $k++)
							if($packet['items'][$k]['object'] == $this->Request['form']['adds'][$j]) continue 2;
						$this->Action->processEvent($this->SectionID, 'save_item', array('ownerid' => $packet['id'], 'object' => $this->Request['form']['adds'][$j]), $this);
					}
					$this->Db->update('enginepacket', array('date_changed' => 'now'), array('id' => $packet['id']));
					$this->Action->processEvent($this->SectionID, 'log', array('type' => 2, 'entity' => 17, 'event' => 12, 'value' => 'Edit engine packet "'.$packet['name'].'" ['.$packet['id'].']'), $this);
				}
				$this->PreparedTemplates = $packets;
				break;
			}
			case 'Pack': {
				$this->packet['action'][0] = array('date_actioned' => 'now', 'type' => 1, 'userid' => $this->Action->Security->currentuser->id, 'username' => $this->Action->Security->currentuser->username,);
				$this->addToReport($this->packet['action'][0], 'Begin validating', 2);
				if($this->validatePack($this->packet)){
					$this->addToReport($this->packet['action'][0], 'End validating', 3);
					$this->addToReport($this->packet['action'][0], 'Begin packing', 2);
					if($this->dumpPacket($this->packet)){
						$this->addToReport($this->packet['action'][0], 'End packing', 1);
						$this->packet['action'][0]['successful'] = 1;
						$this->packet['date_changed'] = 'now';
						$this->Action->processEvent($this->SectionID, 'save_actioned', $this->packet, $this);
						$this->packet = $this->PreparedTemplates;
						return $this->terminateAction();
					}
					else $this->addToReport($this->packet['action'][0], 'Packing failed', 7);
				}
				else{
					$this->addToReport($this->packet['action'][0], 'Validating failed', 0);
					$this->addToReport($this->packet['action'][0], 'Packing failed', 7);
				}
				break;
			}
			case 'Unpack': {
				$index = count($this->packet['action']);
				$this->packet['action'][$index] = array('ownerid' => $this->packet['id'], 'date_actioned' => 'now', 'type' => 2, 'userid' => $this->Action->Security->currentuser->id, 'username' => $this->Action->Security->currentuser->username,);
				$this->addToReport($this->packet['action'][$index], 'Begin validating', 2);
				if($this->validatePack($this->packet)){
					$this->addToReport($this->packet['action'][$index], 'End validating', 3);
					$this->addToReport($this->packet['action'][$index], 'Begin making prepacket', 2);
					if($this->backupPacket()){
						$this->addToReport($this->packet['action'][$index], 'End making prepacket', 3);
						$this->addToReport($this->packet['action'][$index], 'Begin unpacking', 2);
						if($this->restorePacket($this->packet)){
							$this->addToReport($this->packet['action'][$index], 'End unpacking', 1);
							$this->packet['action'][$index]['successful'] = 1;
						}
					}
					else $this->addToReport($this->packet['action'][$index], 'Making prepacket failed', 0);
				}
				else $this->addToReport($this->packet['action'][$index], 'Validating failed', 0);
				if(empty($this->packet['action'][$index]['successful'])){
					$keys = array_keys($this->errors);
					$count = count($keys);
					for ($i = 0; $i < $count; $i++) $this->addToReport($this->packet['action'][$index], $this->errors[$keys[$i]], 0);
					$this->addToReport($this->packet['action'][$index], 'Unpacking failed', 7);
					$this->Action->processEvent($this->SectionID, 'save_action', $this->packet['action'][$index], $this);
				}
				else{
					$this->Action->processEvent($this->SectionID, 'save_action', $this->packet['action'][$index], $this);
					$this->Action->processEvent($this->SectionID, 'log', array('type' => 2, 'entity' => 17, 'event' => 6, 'value' => 'Unpack engine packet "'.$this->packet['name'].'" ['.$this->packet['id'].']'), $this);
					$this->Action->processEvent($this->SectionID, 'set_access', array('id' => $this->packet['id'], 'name' => $this->packet['name'], 'access_flag' => 0), $this);
					return $this->terminateAction();
				}
				$this->packet['action'][$index] = $this->PreparedTemplates;
				break;
			}
			case 'ObjectView': {
				$this->deleteObjectTempFile();
				return $this->terminateAction($this->Home.'/Registar/EnginePacketManager/View/'.$this->PreparedTemplates['ownerid'].$this->SID);
				break;
			}
			case 'Search': {
				if(!isset($this->Request['form']['contained'])) $this->Request['form']['contained'] = array();
				$this->search_conditions = $this->Request['form'];
				$this->Action->processEvent($this->SectionID, 'search', $this->search_conditions, $this);
				$this->founded_packets = $this->PreparedTemplates;
				break;
			}
			case 'Publish': {
				$this->Scheme = 'publish';
				if(!isset($this->Request['form']['servers'])) $this->Request['form']['servers'] = array();
				if(!isset($this->Request['form']['groups'])) $this->Request['form']['groups'] = array();
				if(empty($this->Request['form']['servers']) && empty($this->Request['form']['groups'])) $this->terminateAction();
				$this->packet['action'] = array();
				if(!$this->packet['actioned']){
					$this->packet['action'][0] = array('date_actioned' => 'now', 'type' => 1, 'userid' => $this->Action->Security->currentuser->id, 'username' => $this->Action->Security->currentuser->username,);
					$this->addToReport($this->packet['action'][0], 'Begin validating', 2);
					if($this->validatePack($this->packet)){
						$this->addToReport($this->packet['action'][0], 'End validating', 3);
						$this->addToReport($this->packet['action'][0], 'Begin packing', 2);
						if($this->dumpPacket($this->packet)){
							$this->addToReport($this->packet['action'][0], 'End packing', 1);
							$this->packet['action'][0]['successful'] = 1;
							$this->packet['date_changed'] = 'now';
							$this->Action->processEvent($this->SectionID, 'save_actioned', $this->packet, $this);
							$this->packet = $this->PreparedTemplates;
						}
						else $this->addToReport($this->packet['action'][0], 'Packing failed', 7);
					}
					else{
						$this->addToReport($this->packet['action'][0], 'Validating failed', 0);
						$this->addToReport($this->packet['action'][0], 'Packing failed', 7);
					}
				}
				if($this->packet['actioned']){
					eval(file_get_contents($CORE_PATH.'/signature.inc'));
					$index = count($this->packet['action']);
					foreach($this->Request['form']['servers'] as $value){
						$this->packet['action'][$index] = array('ownerid' => $this->packet['id'], 'host' => $value, 'date_actioned' => 'now', 'type' => 3, 'userid' => $this->Action->Security->currentuser->id, 'report' => array());
						foreach($this->servers['1']['presets'] as $val){
							if ($val['id'] != $value) continue;
							$CheckRemoteServer = new CheckRemoteServer($val);
							$val['index'] = $index;
							if($CheckRemoteServer->preActionCheck($signature['type_server'], 30)) $this->presets[] = $val;
							else{
								foreach($CheckRemoteServer->errors as $v) $this->addToReport($this->packet['action'][$val['index']], $v, 0);
								$this->Action->processEvent($this->SectionID, 'save_action', $this->packet['action'][$val['index']], $this);
								$this->packet['action'][$val['index']] = $this->PreparedTemplates;
							}
							break;
						}
						$index++;
					}
					foreach($this->Request['form']['groups'] as $value){
						if(empty($this->servers[$value])) continue;
						$check = true;
						foreach($this->servers[$value]['presets'] as $ind => $val){
							$this->servers[$value]['presets'][$ind]['index'] = $index;
							$val['index'] = $index;
							$this->packet['action'][$val['index']] = array('ownerid' => $this->packet['id'], 'host' => $val['id'], 'date_actioned' => 'now', 'type' => 3, 'userid' => $this->Action->Security->currentuser->id, 'report' => array());
							$CheckRemoteServer = new CheckRemoteServer($val);
							if(!$CheckRemoteServer->preActionCheck($signature['type_server'], 30)){
								$check = false;
								foreach($CheckRemoteServer->errors as $v) $this->addToReport($this->packet['action'][$val['index']], $v, 0);
							}
							$index++;
						}
						if($check) $this->presets = array_merge($this->presets, $this->servers[$value]['presets']);
						else foreach($this->servers[$value]['presets'] as $val){
							if(empty($this->packet['action'][$val['index']]['report'])) $this->addToReport($this->packet['action'][$val['index']], 'Some server from the same PreSet group doesn\'t responding', 0);
							$this->Action->processEvent($this->SectionID, 'save_action', $this->packet['action'][$val['index']], $this);
							$this->packet['action'][$val['index']] = $this->PreparedTemplates;
						}
					}
					$count = count($this->presets);
					for ($i = 0; $i < $count; $i++){
						if(empty($this->packet['_error']) && $this->transferPacket($this->presets[$i])){
							$this->launchScript($this->presets[$i]);
							$info = $this->getReport($this->presets[$i]);
							$result = end($this->packet['action'][$this->presets[$i]['index']]['report']);
							if($result['type'] == array_search('Good', $this->reporttype)) $this->packet['action'][$this->presets[$i]['index']]['successful'] = 1;
							else if($result['type'] != array_search('Bad', $this->reporttype)) $this->addToReport($this->packet['action'][$this->presets[$i]['index']], 'Publish engine packet failed', 7);
							$this->putRemoteReport($this->presets[$i], $info);
							$this->Action->processEvent($this->SectionID, 'log', array('type' => 4, 'entity' => 17, 'event' => 14, 'value' => 'Publish engine packet "'.$this->packet['name'].'" ['.$this->packet['id'].'] to "'.$this->presets[$i]['name'].'"'), $this);
						}
						$this->Action->processEvent($this->SectionID, 'save_action', $this->packet['action'][$this->presets[$i]['index']], $this);
						$this->packet['action'][$this->presets[$i]['index']] = $this->PreparedTemplates;
					}
				}
				break;
			}
		}
		$this->setSchemeTemplate($this->Scheme);
	}

	function fillElements() {
		switch($this->Scheme) {
			case 'default': $this->fillDefault(); break;
			case 'action': $this->fillAction(); break;
			case 'publish': $this->fillPublish(); break;
			case 'add': $this->fillAddItem(); break;
			case 'search': $this->fillSearch(); break;
			case 'objectview': $this->fillObjectView(); break;
		}
	}
	
	function initAdds() {
		$this->Action->processEvent($this->SectionID, 'select_adds', array(), $this);
		$this->adds = $this->PreparedTemplates;
	}
	
	function validateForm(){
		if (in_array($this->Request['form']['name'], $this->packets) && array_search($this->Request['form']['name'], $this->packets) != $this->Request['form']['id']) $this->errors['other'] = 'Packet with such name and different id already exists';
		if(!is_NumText($this->Request['form']['name'], 1, 128)) $this->errors['name'] = 'Packet Name is not valid';
		if (empty($this->Request['form']['items'])) $this->errors['other'] = 'Packet is empty';
		return $this->hasNoErrors();
	}
	
	function validatePack(&$packet){
		$packettype = $packet['id'] == $this->packet['id'] ? 'Packet' : 'Prepacket';
		if(empty($packet['id'])) $this->errors['other'] = $packettype.' ID is not specified';
		if(empty($packet['name'])) $this->errors['other'] = $packettype.' Name is not specified';
		if(empty($packet['uid'])) $this->errors['other'] = $packettype.' Unique ID is not specified';
		if(empty($packet['items'])) $this->errors['other'] = $packettype.' has no items';
		$count = count($packet['items']);
		for ($i = 0; $i < $count; $i++)
			if(!empty($packet['items'][$i]['_error'])){
				$this->errors['other'] = $packettype.' has item(s) with errors';
				break;
			}
		if(!empty($packet['_error'])) $this->errors['other'] = $packettype.' has errors';
		if(!empty($this->Request['form']['prepacket_name'])){
			if(in_array($this->Request['form']['prepacket_name'], $this->packets)) $this->errors['other'] = 'Packet with prepacket name already exists';
			if(!is_NumText($this->Request['form']['prepacket_name'], 1, 128)) $this->errors['prepacket_name'] = 'Prepacket name is not valid';
		}
		return $this->hasNoErrors();
	}
	
	function hasNoErrors(){
		if(count($this->errors) > 0){
			$this->actionable = false; 
			return false;
		}
		return true;
	}

	function fillDefault() {
		$count = count($this->PreparedTemplates['curPage']);
		for ($i = 0; $i < $count; $i++){
			$this->TempFillEls['packet'][$i] = array(
				'id' => $this->PreparedTemplates['curPage'][$i]['id'],
				'name' => $this->PreparedTemplates['curPage'][$i]['name'],
				'uid' => $this->PreparedTemplates['curPage'][$i]['uid'],
				'filename' => $this->PreparedTemplates['curPage'][$i]['filename'],
				'username' => $this->PreparedTemplates['curPage'][$i]['username'],
				'date_changed' => $this->PreparedTemplates['curPage'][$i]['date_changed'],
				'date_locked' => $this->PreparedTemplates['curPage'][$i]['date_locked'],
				'parent' => empty($this->PreparedTemplates['curPage'][$i]['parent']) ? '' : ($this->PreparedTemplates['curPage'][$i]['parent_exists'] ? '<a href="'.$this->Home.'/Registar/EnginePacketManager/View/'.$this->PreparedTemplates['curPage'][$i]['parent'].'" title="Link to parent view">['.$this->PreparedTemplates['curPage'][$i]['parent'].']</a>' : '['.$this->PreparedTemplates['curPage'][$i]['parent'].']'),
				'actioned' => $this->PreparedTemplates['curPage'][$i]['actioned'] ? 'true' : 'false',
			);
			if(empty($this->PreparedTemplates['curPage'][$i]['access_flag']) || $this->PreparedTemplates['curPage'][$i]['access_flag'] == $this->Action->Security->currentuser->id){
				$this->TempFillEls['packet'][$i]['tdBtn_class'] = 'td_btn';
				$this->TempFillEls['packet'][$i]['tdLocked_class'] = 'td_nolocked';
				$this->TempFillEls['packet'][$i]['msgLocked_disp'] = 'none';
				$this->TempFillEls['packet'][$i]['img_lock_action'] = (!empty($this->PreparedTemplates['curPage'][$i]['access_flag']) ? 'un' : '').'lock';
				$this->TempFillEls['packet'][$i]['lock_action'] = !empty($this->PreparedTemplates['curPage'][$i]['access_flag']) ? 'Unlock' : 'Lock';
				$this->TempFillEls['packet'][$i]['btnLock_disp'] = 'inline';
				$this->TempFillEls['packet'][$i]['btnPublish_disp'] = 'inline';
				$this->TempFillEls['packet'][$i]['btnDuplicate_disp'] = 'inline';
				$this->TempFillEls['packet'][$i]['btnDelete_disp'] = 'inline';
				if(empty($this->PreparedTemplates['curPage'][$i]['actioned'])) {
					$this->TempFillEls['packet'][$i]['imgBullet_adds'] = 'pack1';
					$this->TempFillEls['packet'][$i]['btnUpdate_disp'] = 'inline';
					$this->TempFillEls['packet'][$i]['btnPack_disp'] = 'inline';
					$this->TempFillEls['packet'][$i]['btnUnpack_disp'] = 'none';
				}
				else {
					$this->TempFillEls['packet'][$i]['imgBullet_adds'] = 'pack3';
					$this->TempFillEls['packet'][$i]['btnPack_disp'] = 'none';
					$this->TempFillEls['packet'][$i]['btnUnpack_disp'] = 'inline';
					$this->TempFillEls['packet'][$i]['btnUpdate_disp'] = 'none';
				}
			}
			else{
				$this->TempFillEls['packet'][$i]['tdBtn_class'] = 'td_nobtn';
				$this->TempFillEls['packet'][$i]['tdLocked_class'] = 'td_locked';
				$this->TempFillEls['packet'][$i]['msgLocked_disp'] = 'inline';
				$this->TempFillEls['packet'][$i]['btnLock_disp'] = 'none';
				$this->TempFillEls['packet'][$i]['btnUpdate_disp'] = 'none';
				$this->TempFillEls['packet'][$i]['btnPack_disp'] = 'none';
				$this->TempFillEls['packet'][$i]['btnUnpack_disp'] = 'none';
				$this->TempFillEls['packet'][$i]['btnDelete_disp'] = 'none';
				$this->TempFillEls['packet'][$i]['btnPublish_disp'] = 'none';
				$this->TempFillEls['packet'][$i]['btnDuplicate_disp'] = 'none';
				$this->TempFillEls['packet'][$i]['imgBullet_adds'] = empty($this->PreparedTemplates['curPage'][$i]['actioned']) ? 'pack1' : 'pack3';
			}
			$this->TempFillEls['packet'][$i]['cursor'] = empty($this->PreparedTemplates['curPage'][$i]['action']) ? 'auto' : 'pointer';
			$this->TempFillEls['action'][]['variable'] = 'action['.$this->PreparedTemplates['curPage'][$i]['id'].']=[];';
			$count_action = count($this->PreparedTemplates['curPage'][$i]['action']);
			for ($j = 0; $j < $count_action; $j++){
				$this->TempFillEls['action'][]['variable'] = 'action['.$this->PreparedTemplates['curPage'][$i]['id'].']['.$j.']=[];';
				foreach ($this->PreparedTemplates['curPage'][$i]['action'][$j] as $k => $v)
					$this->TempFillEls['action'][]['variable'] = 'action['.$this->PreparedTemplates['curPage'][$i]['id'].']['.$j.']["'.$k.'"]="'.$v.'";';
			}
		}
		$this->getPageControl($this->Home.'/Registar/EnginePacketManager');
		$this->clearAllTemplates();
	}
	
	function fillAction() {
		if(!empty($this->packet['_error'])){
			$this->actionable = false;
			$this->TempFillEls['other_error'] = $this->printError($this->packet['_error']);
		}
		$this->TempFillEls['objectview_path'] = $this->Home.'/Registar/EnginePacketManager/ObjectView/';
		$this->TempFillEls['action'] = $this->LocalTarget[0];
		$this->TempFillEls['id'] = $this->packet['id'];
		$this->TempFillEls['uid'] = $this->packet['uid'];
		$this->TempFillEls['form_id'] = inputHidden('form[id]', $this->packet['id']);
		$this->TempFillEls['name'] = (empty($this->packet['name']) ? '' : '"'.$this->packet['name'].'"').(empty($this->packet['id']) ? '' : ' ['.$this->packet['id'].']');
		$this->TempFillEls['actioned'] = empty($this->packet['action']) ? 'NO' : 'YES';
		$this->TempFillEls['form_id'] = inputHidden('form[id]', $this->packet['id']);
		$notchanged = true;
		$count = count($this->packet['items']);
		for ($i = 0; $i < $count; $i++){
			if(empty($this->packet['items'][$i]['parent'])){
				$this->TempFillEls['objects'][$this->packet['items'][$i]['id']] = array();
				$link = &$this->TempFillEls['objects'][$this->packet['items'][$i]['id']];
				$link['tblObjInc_disp'] = 'none';
				$link['imgDeleteItem_vis'] = $this->LocalTarget[0] == 'Update' || $this->LocalTarget[0] == 'Add' || $this->LocalTarget[0] == 'Duplicate' ? 'visible' : 'hidden';
				$link['form_item_object'] = inputHidden('form[items][][object]', $this->packet['items'][$i]['object']);
			}
			else{
				$this->TempFillEls['objects'][$this->packet['items'][$i]['parent']]['includes'][$this->packet['items'][$i]['id']] = array();
				$link = &$this->TempFillEls['objects'][$this->packet['items'][$i]['parent']]['includes'][$this->packet['items'][$i]['id']];
				$this->TempFillEls['objects'][$this->packet['items'][$i]['parent']]['tblObjInc_disp'] = '';
			}
			if(!empty($value['message'])) $notchanged = false;
			foreach($this->packet['items'][$i] as $key => $value) $link[$key] = $value;
			if(!empty($this->packet['items'][$i]['_error'])){
				$this->actionable = false;
				$link['imgReady'] = 'cross_red';
				$link['reason'] = $this->packet['items'][$i]['_error'];
				if(!empty($link['parent'])){
					$this->TempFillEls['objects'][$link['parent']]['imgReady'] = 'cross_red';
					$this->TempFillEls['objects'][$link['parent']]['reason'] = 'Included Objects problem';
				}
			}
			else{
				if($this->LocalTarget[0] == 'View' && $this->packet['actioned'] && empty($this->packet['_error']) && !empty($this->packet['items'][$i]['hash'])) $link['object_view'] = 'setObjectViewButton("'.$this->packet['items'][$i]['id'].'");';
				if(!empty($this->packet['items'][$i]['message'])){
					$link['reason'] = $this->packet['items'][$i]['message'];
					$link['imgReady'] = 'attention';
					if(!empty($link['parent'])){
						$this->TempFillEls['objects'][$link['parent']]['imgReady'] = 'attention';
						$this->TempFillEls['objects'][$link['parent']]['reason'] = 'Included Objects mismatches';
					}
				}
				else $link['imgReady'] = 'tick1';
			}
		}
		$this->TempFillEls['notchanged'] = $notchanged ? 'true' : 'false';
		$this->TempFillEls['alternative_disp'] = ($this->LocalTarget[0] == 'Add' || $this->LocalTarget[0] == 'Duplicate') ? 'none' : 'inline';
		$this->TempFillEls['compile_disp'] = ($this->LocalTarget[0] == 'Update' || $this->LocalTarget[0] == 'Add' || $this->LocalTarget[0] == 'Duplicate') ? 'inline' : 'none';
		if($this->LocalTarget[0] == 'Unpack'){
			$this->TempFillEls['form_prepacket_name'] = inputText('form[prepacket_name]', '', '60');
			$this->TempFillEls['prepacket_name_disp'] = '';
		}
		else $this->TempFillEls['prepacket_name_disp'] = 'none';
		$actions = array('Pack', 'Unpack', 'Publish');
		if(($this->LocalTarget[0] == 'View' && !empty($this->packet['actioned'])) || (in_array($this->LocalTarget[0], $actions) && !empty($this->Request))) $this->fillPublish(false);
		else $this->TempFillEls['report_disp'] = 'none';
		switch($this->LocalTarget[0]){
			case 'View': case 'Delete': case 'Pack': case 'Unpack':  case 'Publish': {
				$this->TempFillEls['form_name'] = inputText('form[name]', $this->packet['name'], '60', 'readonly');
				$this->TempFillEls['adds_disp'] = 'none';
				if($this->LocalTarget[0] == 'Publish'){
					$this->TempFillEls['servers_disp'] = 'inline';
					$this->tempFillServersEls();
				}
				else $this->TempFillEls['servers_disp'] = 'none';
				break;
			}
			case 'Update': case 'Add': case 'Duplicate': {
				$this->TempFillEls['form_name'] = inputText('form[name]', $this->packet['name'], '60');
				$this->TempFillEls['adds'] = '(<span id="adds_count">0</span> selected)<br>'.inputSelect('form[adds][]', $this->adds, $selected = '', $event = 'size=20 style="width: 880px;" multiple="multiple" id="adds" onClick="changeSelectedCount(this.id);" onDblClick="setNotSelected(this);"');
				$this->TempFillEls['servers_disp'] = 'none';
				//if($this->LocalTarget[0] != 'Update') $this->actionable = false;
				break;
			}
		}
		if($this->actionable){
			$this->TempFillEls['publishable'] = 'true';
			$this->TempFillEls['imgActionable'] = 'tick1';
		}
		else{
			$this->TempFillEls['publishable'] = 'false';
			$this->TempFillEls['imgActionable'] = 'cross_red';
		}
		foreach ($this->errors as $k => $v) $this->TempFillEls[$k.'_error'] = $this->printError($v);
		$this->clearAllTemplates();
	}
	
	function fillPublish($main_fill_func = true) {
		if(!$main_fill_func) $this->packet['action'] = array_reverse($this->packet['action']);
		$count = count($this->packet['action']);
		for ($i = 0; $i < $count; $i++){
			$this->TempFillEls['actions'][$i] = array(
				'id' => $this->packet['action'][$i]['id'],
				'type' => $this->actiontype[$this->packet['action'][$i]['type']],
				'date' => $this->packet['action'][$i]['date_actioned'],
				'username' => $this->packet['action'][$i]['username'],
				'userid' => $this->packet['action'][$i]['userid'],
				'script_result' => @$this->packet['action'][$i]['result'],
			);
			switch($this->packet['action'][$i]['type']){
				case 1: case 2: $this->TempFillEls['actions'][$i]['hostpath'] = 'on current server'; break;
				case 3: $this->TempFillEls['actions'][$i]['hostpath'] = 'to "'.$this->packet['action'][$i]['hostpath'].'"'; $this->TempFillEls['actions'][$i]['hostid'] = '['.$this->packet['action'][$i]['host'].']'; break;
				case 4: $this->TempFillEls['actions'][$i]['hostpath'] = 'from "'.$this->packet['action'][$i]['hostpath'].'"'; $this->TempFillEls['actions'][$i]['hostid'] = '['.$this->packet['action'][$i]['host'].']'; break;
			}
			$c = count($this->packet['action'][$i]['report']);
			for ($j = 0; $j < $c; $j++){
				$this->TempFillEls['actions'][$i]['reports'][] = array(
					'time' => $this->packet['action'][$i]['report'][$j]['datetime'],
					'message' => $this->packet['action'][$i]['report'][$j]['message'],
					'type' => strtolower($this->reporttype[$this->packet['action'][$i]['report'][$j]['type']]),
				);
			}
			$this->TempFillEls['actions'][$i]['script_result_disp'] = empty($this->packet['action'][$i]['result']) ? 'none' : 'inline';
		}
		if($main_fill_func){
			$this->TempFillEls['id'] = $this->packet['id'];
			$this->TempFillEls['name'] = $this->packet['name'];
			foreach ($this->errors as $k => $v) $this->TempFillEls[$k.'_error'] = $this->printError($v);
			$this->clearAllTemplates();
		}
	}
	
	function fillObjectView(){
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$this->TempFillEls = $this->PreparedTemplates;
		$filepath = $COMMON_VARS['enginepacket_dir_temp'].'/'.$this->PreparedTemplates['packetuid'].'/ObjectView'.$this->PreparedTemplates['object'];
		$mime = mime_content_type($ROOT_PATH.'/'.$filepath);
		$type = explode('/', $mime);
		$type = $type[0];
		switch($type){
			case 'text': {
				$this->TempFillEls['imagetype_disp'] = 'none';
				$this->TempFillEls['texttype_disp'] = '';
				$this->TempFillEls['othertype_disp'] = 'none';
				$textfile = file($ROOT_PATH.'/'.$filepath);
				$this->TempFillEls['textarea'] = inputTextArea('textfile', implode("\r\n", $textfile), '', 35, 'style="width: 870px;" readonly');
				break;
			}
			case 'image': {
				$this->TempFillEls['imagetype_disp'] = '';
				$this->TempFillEls['texttype_disp'] = 'none';
				$this->TempFillEls['othertype_disp'] = 'none';
				$this->TempFillEls['image'] = 'http://'.getenv('HTTP_HOST').'/'.$filepath;
				break;
			}
			default: {
				$this->TempFillEls['imagetype_disp'] = 'none';
				$this->TempFillEls['texttype_disp'] = 'none';
				$this->TempFillEls['othertype_disp'] = '';
				$this->TempFillEls['other'] = 'http://'.getenv('HTTP_HOST').'/'.$filepath;
				break;
			}
		}
		$this->clearAllTemplates();
	}
	
	function fillAddItem(){
		GLOBAL $COMMON_VARS, $REGISTRY, $ROOT_PATH;
		if(!empty($this->Request['sbtAddItem'])) $this->TempFillEls['sbtAddItemToNew_disabled'] = 'disabled';
		$this->TempFillEls['objects_count'] = count($this->Request['form']['adds']);
		$count = count($this->Request['form']['adds']);
		for ($i = 0; $i < $count; $i++){
			$this->TempFillEls['object'][$i] = array(
				'form_object' => inputCheckbox('form[adds][]', true, 'onClick="setSubmitAbility(\'object\', this);" '.(empty($this->Request['sbtAddItem']) ? '' : 'disabled'), $this->Request['form']['adds'][$i]),
				'path' => $this->Request['form']['adds'][$i],
			);
		}
		$count = count($this->PreparedTemplates);
		for ($i = 0; $i < $count; $i++){
			$this->TempFillEls['packet'][] = array(
				'form_packet' => inputCheckbox('form[packet][]', (empty($this->Request['sbtAddItem']) ? false : true), 'onClick="setSubmitAbility(\'packet\', this);" '.(empty($this->Request['sbtAddItem']) ? '' : 'disabled'), $this->PreparedTemplates[$i]['id']),
				'id' => $this->PreparedTemplates[$i]['id'],
				'name' => $this->PreparedTemplates[$i]['name'],
				'message' => empty($this->Request['sbtAddItem']) ? '' : (empty($this->PreparedTemplates[$i]['actioned']) ? (empty($this->PreparedTemplates[$i]['access_flag']) || $this->PreparedTemplates[$i]['access_flag'] == $this->Action->Security->currentuser->id ? (isset($this->packets[$this->PreparedTemplates[$i]['id']]) ? 'OK' : 'Packet doesn\'t exist') : 'Locked by '.$this->PreparedTemplates[$i]['username'].' ['.$this->PreparedTemplates[$i]['date_locked'].']') : 'Packet was actioned'),
				'type' => empty($this->Request['sbtAddItem']) ? '1' : ((empty($this->PreparedTemplates[$i]['access_flag']) || $this->PreparedTemplates[$i]['access_flag'] == $this->Action->Security->currentuser->id) && empty($this->PreparedTemplates[$i]['actioned']) && isset($this->packets[$this->PreparedTemplates[$i]['id']]) ? 'end' : 'error'),
			);
		}
		$this->clearAllTemplates();
	}
	
	function fillSearch(){
		foreach($this->search_time_intervals as $key => $value){
			$this->TempFillEls['not_older'][]['radio'] = '<nobr>'.inputRadio('form[not_older]', $value, ($this->search_conditions['not_older'] == $value ? true : false)).'&nbsp;'.$key.'&nbsp;</nobr>';
			$this->TempFillEls['packed'][]['radio'] = '<nobr>'.inputRadio('form[packed]', $value, ($this->search_conditions['packed'] == $value ? true : false)).'&nbsp;'.$key.'&nbsp;</nobr>';
			$this->TempFillEls['unpacked'][]['radio'] = '<nobr>'.inputRadio('form[unpacked]', $value, ($this->search_conditions['unpacked'] == $value ? true : false)).'&nbsp;'.$key.'&nbsp;</nobr>';
			$this->TempFillEls['published'][]['radio'] = '<nobr>'.inputRadio('form[published]', $value, ($this->search_conditions['published'] == $value ? true : false)).'&nbsp;'.$key.'&nbsp;</nobr>';
			$this->TempFillEls['inpublished'][]['radio'] = '<nobr>'.inputRadio('form[inpublished]', $value, ($this->search_conditions['inpublished'] == $value ? true : false)).'&nbsp;'.$key.'&nbsp;</nobr>';
		}
		$count = count($this->search_conditions['contained']);
		for ($i = 0; $i < $count; $i++) $this->TempFillEls['contained'][] = array('object' => $this->search_conditions['contained'][$i],);
		if(empty($this->Request['form'])) $this->TempFillEls['founded_packets_disp'] = 'none';
		else{
			if(empty($this->founded_packets)){
				$this->TempFillEls['message'] = 'No engine packets founded that match search conditions';
				$this->TempFillEls['colnames_disp'] = 'none';
			}
			else $this->TempFillEls['packets'] = $this->founded_packets;
		}
		$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 extractObject($filename, $object){
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		if(!empty($this->PreparedTemplates['_error'])) return false;
		$temp_dir_path = $ROOT_PATH.'/'.$COMMON_VARS['enginepacket_dir_temp'].'/'.$this->PreparedTemplates['packetuid'];
		if(!file_exists($temp_dir_path) && !mkdir($temp_dir_path)) return false;
		$object_view_path = $temp_dir_path.'/ObjectView';
		if(!file_exists($object_view_path) && !mkdir($object_view_path)) return false;
		$Archive = new Archive($ROOT_PATH.'/'.$COMMON_VARS['enginepacket_dir'].'/', $object_view_path, $filename, true);
		$Archive->setExtractFiles(array(substr($this->PreparedTemplates['object'], 1)));
		$Archive->setTarPath($COMMON_VARS['tar_dir']);
		$Archive->extractArchive();
		if(empty($Archive->errors)) return true;
		else return false;
	}
	
	function deleteObjectTempFile(){
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		if(!empty($this->PreparedTemplates['_error'])) return false;
		$temp_dir_path = $ROOT_PATH.'/'.$COMMON_VARS['enginepacket_dir_temp'].'/'.$this->PreparedTemplates['packetuid'];
		$temp_file_path = $temp_dir_path.'/ObjectView'.$this->PreparedTemplates['object'];
		unlink($temp_file_path);
		//mysystem('rm -rf '.$temp_dir_path);
	}
	
	function dumpPacket(&$packet){
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$Dump = new EnginePacketDump($packet, $ROOT_PATH.'/'.$COMMON_VARS['enginepacket_dir']);
		$Dump->dumpEnginePacket();
		if(!empty($Dump->errors)){
			$this->errors['other'] = 'Packet Dump Error:<br>'.$Dump->errors[0];
			return false;
		}
		return true;
	}
	
	function deletePacketFile(){
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		unlink($ROOT_PATH.'/'.$COMMON_VARS['enginepacket_dir'].'/'.$this->packet['filename']);
		mysystem('rm -rf '.$ROOT_PATH.'/'.$COMMON_VARS['enginepacket_dir_temp'].'/'.$this->packet['uid']);
	}
	
	function backupPacket(){
		GLOBAL $ROOT_PATH;
		$success = false;
		$keys = array_keys($this->packet);
		$count = count($keys);
		for ($i = 0; $i < $count; $i++){
			if(is_array($this->packet[$keys[$i]])) $this->prepacket[$keys[$i]] = array();
			else $this->prepacket[$keys[$i]] = $this->packet[$keys[$i]];
		}
		$count = count($this->packet['items']);
		for ($i = 0; $i < $count; $i++){
			if(empty($this->packet['items'][$i]['parent']) && file_exists($ROOT_PATH.$this->packet['items'][$i]['object'])) $this->prepacket['items'][] = $this->packet['items'][$i];
		}
		if(empty($this->prepacket['items'])){
			$index = count($this->packet['action']) - 1;
			$this->addToReport($this->packet['action'][$index], 'There is nothing to prepack', 3);
			return true;
		}
		$this->prepacket['id'] = '';
		$this->prepacket['actioned'] = '0';
		$this->prepacket['parent'] = $this->packet['id'];
		if(empty($this->Request['form']['prepacket_name'])){
			$selected = $this->Db->SelectAny('SELECT count(id) AS count FROM enginepacket WHERE parent = '.$this->packet['id']);
			$this->prepacket['name'] = $this->packet['name'].' (#'.(empty($selected) ? 1 : ($selected[0]['count'] + 1)).')';
		}
		else $this->prepacket['name'] = $this->Request['form']['prepacket_name'];
		$this->Action->processEvent($this->SectionID, 'save', $this->prepacket, $this);
		$this->Action->processEvent($this->SectionID, 'open', array('id' => $this->PreparedTemplates['id']), $this);
		$this->prepacket = $this->PreparedTemplates;
		$this->prepacket['action'][0] = array('date_actioned' => 'now', 'type' => 1, 'userid' => $this->Action->Security->currentuser->id, 'username' => $this->Action->Security->currentuser->username,);
		$this->addToReport($this->prepacket['action'][0], 'Begin validating prepacket', 2);
		if($this->validatePack($this->prepacket)){
			$this->addToReport($this->prepacket['action'][0], 'End validating prepacket', 3);
			$this->addToReport($this->prepacket['action'][0], 'Begin packing prepacket', 2);
			if($this->dumpPacket($this->prepacket)){
				$this->prepacket['action'][0]['successful'] = 1;
				$this->addToReport($this->prepacket['action'][0], 'End packing prepacket', 1);
				$this->prepacket['date_changed'] = 'now';
				$this->Action->processEvent($this->SectionID, 'save_actioned', $this->prepacket, $this);
				$this->prepacket = $this->PreparedTemplates;
				$success = true;
			}
			else $this->addToReport($this->prepacket['action'][0], 'Packing prepacket failed', 0);
		}
		else $this->addToReport($this->prepacket['action'][0], 'Validating prepacket failed', 0);
		$index = count($this->packet['action']) - 1;
		$this->packet['action'][$index]['report'] = array_merge($this->packet['action'][$index]['report'], $this->prepacket['action'][0]['report']);
		$last_rep_index = count($this->packet['action'][$index]['report']) - 1;
		if($this->packet['action'][$index]['report'][$last_rep_index]['type'] == 1) $this->packet['action'][$index]['report'][$last_rep_index]['type'] = 3;
		return $success;
	}
	
	function restorePacket(&$packet){
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$Dump = new EnginePacketDump($packet, $ROOT_PATH.'/'.$COMMON_VARS['enginepacket_dir']);
		$Dump->restoreEnginePacket();
		mysystem('rm -rf '.$ROOT_PATH.'/'.$COMMON_VARS['enginepacket_dir_temp'].'/'.$packet['uid']);
		if(!empty($Dump->errors)){
			$this->errors['other'] = 'Packet Dump Error:<br>'.$Dump->errors[0];
			return false;
		}
		return true;
	}
	
	function addToReport(&$action, $message, $type, $datetime = false){
		if($datetime === false) $datetime = date('Y-m-d H:i:s', time());
		$action['report'][] = array(
			'datetime' => $datetime,
			'message' => $message,
			'type' => $type,
		);
	}
	
	function transferPacket($preset, $delete = false){
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$this->addToReport($this->packet['action'][$preset['index']], 'Transfer engine packet', 2);
		$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 = $ROOT_PATH.'/'.$COMMON_VARS['enginepacket_dir'].'/';
		$Transfer->file = $this->packet['filename'];
		if($delete) $Transfer->delete = true;
		$Transfer->sendFile();
		$Transfer->close();
		if(!empty($Transfer->errors)){
			$this->addToReport($this->packet['action'][$preset['index']], 'Transfer engine packet failed', 0);
			foreach($Transfer->errors as $value) $this->addToReport($this->packet['action'][$preset['index']], $value, 0);
			return false;
		}
		$this->addToReport($this->packet['action'][$preset['index']], 'Transfer engine packet', 3);
		return true;
	}
	
	function launchScript($preset){
		$this->addToReport($this->packet['action'][$preset['index']], 'Launch remote script', 2);
		$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' => 'enginepacket',
			'uid' => $this->packet['uid'],
			'filename' => $this->packet['filename'],
			'username' => $this->Action->Security->currentuser->username,
			'hostpath' => $_SERVER['HTTP_HOST'],
		);
		$this->packet['action'][$preset['index']]['result'] = $Transfer->launchScript();
		if(empty($this->packet['action'][$preset['index']]['result'])) $this->packet['action'][$preset['index']]['result'] = 'No debug result was retrieved from remote server';
		$Transfer->close();
		if (!empty($Transfer->errors)){
			$this->addToReport($this->packet['action'][$preset['index']], 'Launch Script failed', 0);
			foreach($Transfer->errors as $value) $this->addToReport($this->packet['action'][$preset['index']], $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->packet['action'][$preset['index']]['result'], "\r\n");
		$SID = explode('=', $SID);
		$Transfer->file = 'get_session.php';
		if(empty($SID[0]) || empty($SID[1])) {
			$this->addToReport($this->packet['action'][$preset['index']], 'No remote Session ID was retrieved from remote server', 0);
			return false;
		}
		$Transfer->variables = array($SID[0] => $SID[1],);
		$report = $Transfer->launchScript();
		$Transfer->close();
		if (!empty($Transfer->errors)){
			$this->addToReport($this->packet['action'][$preset['index']], 'Getting remote server report failed', 0);
			foreach($Transfer->errors as $value) $this->addToReport($this->packet['action'][$preset['index']], $value, 0);
			return false;
		}
		$packetid = 0;
		$actionid = 0;
		if(@eval('$report = '.$report.';') === false) $this->addToReport($this->packet['action'][$preset['index']], 'No publish report was retrieved from remote server', 0);
		else{
			$count = count($report);
			for($i = 0; $i < $count; $i++){
				if($report['message_'.$i]['type'] == 4){
					if(preg_match('/Engine packet ID \[[0-9]+\]/i', $report['message_'.$i]['message'])){
						preg_match('/[0-9]+/', $report['message_'.$i]['message'], $matches);
						$packetid = $matches[0];
					}
					else if(preg_match('/Engine packet action ID \[[0-9]+\]/i', $report['message_'.$i]['message'])){
						preg_match('/[0-9]+/', $report['message_'.$i]['message'], $matches);
						$actionid = $matches[0];
					}
				}
				$this->packet['action'][$preset['index']]['report'][] = $report['message_'.$i];
			}
		}
		return array('packetid' => $packetid, 'actionid' => $actionid,);
	}
	
	function putRemoteReport($preset, $info){
		if(empty($info['actionid'])) 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('enginepacketaction', array('result' => $this->packet['action'][$preset['index']]['result']), array('id' => $info['actionid']))) $this->addToReport($this->packet['action'][$preset['index']], 'Couldn\'t put publish debug result to remote database', 6);
			$Database->close();
		}
		else return false;
	}
	
	function terminateAction($location = ''){
		if(empty($location)) $location = $this->Home.'/Registar/EnginePacketManager'.$this->SID;
		$this->clearAllTemplates();
		header('Location: '.$location);
		return true;
	}
	
	function clearAllTemplates(){
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select_report_type');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'open');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select_adds');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'get_access');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'set_access');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'save');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'save_actioned');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'save_action');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'delete');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select_item');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'save_item');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'search');
	}
}
?>