<?php

class Server extends RootRegistry{

	var $Model = array();
	var $Control = array();

	var $Guides = array();

	var $UserAgent = array();

	var $LM;

	var $settings = array(
		'LanguageSearch' => array(),
	);
	var $error = 0;

	function __construct($name='Server',$type=3) {
		//$this->RootRegistry($name,$type);
		parent::__construct($name,$type);
		$this->setUserAgent();
		$this->LM = $_SESSION['LanguageManager'];
	}

	function setActivity() { 
		$handler = $this->getHandler(3);
		$handler->changeDateLastActivity();
	}

	function saveRegistry() {
		global $REGISTRY, $CORE_PATH;
		$filename = $CORE_PATH.'\Registry2.inc';
		$handle = fopen($filename,"w");
		flock($handle, LOCK_EX);
		fwrite($handle,"<?php\r\n");
		// Changes cause of Home Target //
		$REGISTRY['VirtualSlotTarget'][''][''] = $REGISTRY['default_layout'];
		$REGISTRY['VirtualSlotTarget']['']['/'] = $REGISTRY['default_layout'];
		$REGISTRY['VirtualSlotTarget']['main'][''] = 'DescribeView:object?id=1';
		$REGISTRY['VirtualSlotTarget']['main']['/'] = 'DescribeView:object?id=1';
		ksort($REGISTRY['VirtualSlotTarget']['']);
		ksort($REGISTRY['VirtualSlotTarget']['main']);
		$registryadd = fopen($CORE_PATH.'\RegistryAdd.inc', "w");
		flock($registryadd, LOCK_EX);
		fwrite($registryadd,"<?php\r\n");
		fwrite($registryadd, '// REGISTRY/_HomeTarget'."\r\n");
		fwrite($registryadd, '$REGISTRY[\'HomeTarget\'] = '."'".(empty($REGISTRY['HomeTarget']) || !is_numeric($REGISTRY['HomeTarget']) ? 1 : $REGISTRY['HomeTarget'])."';\r\n");
		fwrite($registryadd, "?>");
		flock($registryadd, LOCK_UN);
		fclose($registryadd);
		@chmod($CORE_PATH.'\RegistryAdd.inc', 0664);
		/////////////////////////////////
		fwrite($handle,'// REGISTRY/_VirtualSlotTarget'."\r\n");
		fwrite($handle,'$REGISTRY[\'VirtualSlotTarget\'] = array('."\r\n");
		foreach($REGISTRY['VirtualSlotTarget'] as $key => $value) {
			fwrite($handle,"\t'".$key."' => array("."\r\n");
			foreach($value as $k1 => $v1) {
				if(is_array($v1)) {
					fwrite($handle,"\t\t'".$k1."' => array("."\r\n");
					foreach($v1 as $k2 => $v2) {
						if($k2=='Locate') fwrite($handle,"\t\t\t'".$k2."' => ".(int)$v2.",\r\n");
						else fwrite($handle,"\t\t\t'".$k2."' => '".$v2."',\r\n");
					}
					fwrite($handle,"\t\t),\r\n");
				}
				else fwrite($handle,"\t\t'".$k1."' => '".$v1."',"."\r\n");
			}
			fwrite($handle,"\t),\r\n");
		}
		fwrite($handle,");\r\n");
		fwrite($handle,'// ~REGISTRY/_VirtualSlotTarget'."\r\n");
		fwrite($handle,"?>");
		flock($handle,LOCK_UN);
		fclose($handle);
		@chmod($filename,0664);
		$handle = fopen($CORE_PATH.'\Registry.inc',"w");
		flock($handle,LOCK_EX);
		//copy($filename,$CORE_PATH.'\Registry.inc');
		$data = file_get_contents($filename);
		fwrite($handle, $data);
		flock($handle,LOCK_UN);
		fclose($handle);
		include_once($CORE_PATH.'\Registry.inc');
	}

	function getAction($sectionid = 1) {
		if(isset($this->Control[$sectionid])) return $this->Control[$sectionid];
		else {
			$key = $this->findAction($sectionid);
			if(!empty($key)) return $this->Control[$key];
			else {
				$this->setAction($sectionid);
				return $this->Control[$sectionid];
			}
		}
	}

	function setAction($sectionid = 1) {
		if(!empty($this->Properties['Sections'][$sectionid])) {
			if(isset($this->Properties['Sections'][$sectionid]['a'])) {
				$action = $this->Properties['Sections'][$sectionid]['a'].'Action';
				if(class_exists($action)) {
					$this->Control[$sectionid] = new $action();
					if(!empty($this->Properties['Sections'][$sectionid]['m'])) {
						$this->Control[$sectionid]->ModuleID = $this->Properties['Sections'][$sectionid]['m'];
						$this->Control[$sectionid]->Handler = $this->getHandler($sectionid); 
						//$this->Control[$sectionid]->Security = $_SESSION['SecurityHandler'];
						$this->Control[$sectionid]->Security = isset($_SESSION['SecurityHandler'])?$_SESSION['SecurityHandler']:NULL;
						$this->Control[$sectionid]->Server = $this;
					}
					else debug('<b>Error:</b> Section "'.$sectionid.'": Module ID does not exist!<br>');
				}
				else debug('<b>Error:</b> Section "'.$sectionid.'": Action "'.$action.'" does not exist!<br>');
			}
			else debug('<b>Error:</b> Section "'.$sectionid.'": Action Name does not exist!<br>');
		}
		else debug('<b>Error:</b> Section "'.$sectionid.'": Section does not exist!<br>');
	}

	function findAction($sectionid = 1) {
		$action = strtolower($this->Properties['Sections'][$sectionid]['a'].'Action');
		foreach($this->Control as $key => $value) if(strtolower(get_class($value)) == $action) return $key;
		return 0;
	}

	function getHandler($sectionid = 1) {
		if(isset($this->Model[$sectionid])) return $this->Model[$sectionid];
		else {
			$key = $this->findHandler($sectionid);
			if(!empty($key)) return $this->Model[$key];
			else {
				$this->setHandler($sectionid);
				return $this->Model[$sectionid];
			}
		}
	}

	function setHandler($sectionid = 1) {
		if(!empty($this->Properties['Sections'][$sectionid])) {
			if(isset($this->Properties['Sections'][$sectionid]['h'])) {
				$handler = $this->Properties['Sections'][$sectionid]['h'].'Handler';
				if(class_exists($handler)) {
					if(strtolower($handler) == 'securityhandler')
						$this->Model[$sectionid] = $_SESSION['SecurityHandler'];
					elseif(strtolower($handler) == 'orderhandler')
						$this->Model[$sectionid] = $_SESSION['OrderHandler'];
					else $this->Model[$sectionid] = new $handler();
				}
				else debug('<b>Error:</b> Section "'.$sectionid.'": Handler "'.$handler.'" does not exist!<br>');
			}
			else debug('<b>Error:</b> Section "'.$sectionid.'": Handler Name does not exist!<br>');
		}
		else debug('<b>Error:</b> Section "'.$sectionid.'": Section does not exist!<br>');
	}

	function findHandler($sectionid = 1) {
		$handler = strtolower($this->Properties['Sections'][$sectionid]['h'].'Handler');
		foreach($this->Model as $key => $value) if(strtolower(get_class($value)) == $handler) return $key;
		return 0;
	}

	function clearAll() {
		foreach($this->Model as $key => $value) {
			if(strtolower(get_class($value)) != 'securityhandler' && strtolower(get_class($value)) != 'orderhandler') unset($this->Model[$key]);
			else {
				$_SESSION['SecurityHandler'] = new SecurityHandler();
				//$_SESSION['SecurityHandler']->init();
				$_SESSION['OrderHandler'] = new OrderHandler();
				//$_SESSION['OrderHandler']->init();
			}
		}
		foreach($this->Control as $key => $value) unset($this->Control[$key]);
	}

	function getUserAgent() {
		return $this->UserAgent;
	}

	function setUserAgent() {
		$UserAgent = new Sniff();
		$this->UserAgent = array(
			'browser' => $UserAgent->_browser_info['browser']=='ns' && !empty($UserAgent->_browser_info['gecko'])? 'gs' : ($UserAgent->_browser_info['browser']=='mz' && empty($UserAgent->_browser_info['gecko'])? 'ie' :$UserAgent->_browser_info['browser']),
			'IP' => $UserAgent->_browser_info['ip'],
			'OS' => $UserAgent->_browser_info['platform'].' '.$UserAgent->_browser_info['os'],
		);
		$this->UserAgent['ua'] = array(
			'name' => $UserAgent->_browser_info['browser']=='ns' && !empty($UserAgent->_browser_info['gecko'])? 'gecko' : ($UserAgent->_browser_info['browser']=='mz' && empty($UserAgent->_browser_info['gecko'])? 'msie' : $UserAgent->_browser_info['long_name']),
			'version' => $this->UserAgent['browser']=='ie' || $this->UserAgent['browser']=='ns'? $UserAgent->_browser_info['version'] : '',
		);
	}

	function getLM() {
		return $this->LM;
	}

	function setLM($langs = array()) {
		$this->LM = new LanguageManager($langs);
		$this->Guides = array();
	}

	function &getGuide($key,$short = false) {
		//unset($this->Guides);
		$array = array();
		$conditions = array();
		$sort = 'id';
		$value = !empty($this->Properties['Guides'][$key])? $this->Properties['Guides'][$key] : '';
		if(!empty($value)) {
			if(!isset($this->Guides[$key])) {
				if(!empty($this->Properties['Guides'][$key]['columns'])) $conditions = $this->Properties['Guides'][$key]['columns'];
				if(!empty($this->Properties['Guides'][$key]['sort'])) $sort = $this->Properties['Guides'][$key]['sort'];
				$this->Guides[($short? 'short_' : '').$key] = $this->LM->DB->SelectGuide($value['table'].' g',array('id','name'),$conditions,false,$sort);
			}
			return $this->Guides[($short? 'short_' : '').$key];
		}
		return $array;
	}
	
	function allocateMemoryIfNeeded($increment = 30) {
		$increment = intval($increment);
		if($increment < 10 || $increment > 512) $increment = 30;
		$current_limit = intval(ini_get('memory_limit'));
		$current_usage = intval(mem_convert(memory_get_usage(true)));
		$diff = $current_limit - $current_usage;
		if($diff < 20 || $diff < $increment) {
			$new_limit = $current_limit + $increment;
			if($new_limit <= self::memory_usage_limit) ini_set('memory_limit', $new_limit.'M');
		}
	}
	
	
}
?>