<?php

class RequestBroker extends RootRegistry {

	var $Target = '';
	var $Request = array();
	var $RequestMethod = '';
//	var $allow_urls = array('OrderAdmin','Admin','TemplateItem','RSS','receiver.php','smb','ringme','sitemapxml_translator.php','robotstxt_translator.php','sitemapxml2_translator.php');
	var $allow_urls = array('OrderRegistar','Registar','TemplateItem','RSS','sitemapxml_translator.php','robotstxt_translator.php','sitemapxml2_translator.php');
//	var $deny_urls = array('www1','webtest','prod1','prod2','prod3','devorigin1','devorigin2','devorigin','origin','www','devorigin3','production1','production2','production3','staging','staging3','staging2','staging1','stage3','stage2','stage1');
	var $deny_urls = array('www1','prod1','devorigin','origin','www','production1','staging','staging1','stage1');
//	var $external_url = 'http://www.liburdi.com';
	var $external_url = 'http://www.liburdi.com';

	function __construct($name = 'RequestBroker') { 
		global $REGISTRY, $DatabaseBroker, $signature;
		$URL = @parse_url(getenv('REQUEST_URI'));
		$urls = explode('/',$URL['path']);
		$if_allow = @$urls[1];
		$VST = &$REGISTRY['VirtualSlotTarget'];
		$REGISTRY['default_layout'] = $VST[''][''];
		$REGISTRY['Page'] = array();
		if(!empty($REGISTRY['HomeTarget']) && is_numeric($REGISTRY['HomeTarget']) && $REGISTRY['HomeTarget'] != '1'){
			$path = false;
			foreach($VST['main'] as $key => $value)
				if($value == 'DescribeView:object?id='.$REGISTRY['HomeTarget']){
					$path = $key;
					break;
				}
			if($path === false) $REGISTRY['HomeTarget'] = '1';
			else if(!empty($path) && isset($VST[''][$path])){
				$VST[''][''] = $VST['']['/'] = $VST[''][$path];
				$VST['main'][''] = $VST['main']['/'] = 'DescribeView:object?id='.$REGISTRY['HomeTarget'];
			}
		}
//		$this->RootRegistry($name);
		parent::__construct($name);
		$request = array();
		$str_query = array();
		$this->RequestMethod = getenv('REQUEST_METHOD');
		$this->Request = array_merge($_REQUEST,$_FILES);
		$this->Request = $this->deAlias();
		if($REGISTRY['Core']['TargetThruQuery']) $rawTarget = $this->Request['target'];
		else {
			$rawTarget = (isset($_SERVER['REQUEST_URI']) and $_SERVER['REQUEST_URI'] != '/')? (in_array($if_allow,$this->allow_urls)? $URL['path'] : strtolower($URL['path'])) : '';
			if(validate(getenv('QUERY_STRING'))) parse_str(getenv('QUERY_STRING'),$str_query);
			else parse_str(getenv('REDIRECT_QUERY_STRING'),$str_query);
		} 
		$target = explode('/',preg_replace("/\/$/",'',$rawTarget));
		$this->Target = $this->Path($target);
		$localtarget = array_slice($target,count($this->Target));
		$REGISTRY['Request'] = array(
			'Target' => $target,
			'Search' => $str_query,
			'RawTarget' => implode('/',$target),
			'LocalTarget' => $localtarget,
			'Query' => $this->Request,
			'Method' => $this->RequestMethod,
			'Broker' => $this,
			'404' => false,
		);
		$REGISTRY['Globals']['this_target'] = $REGISTRY['Request']['RawTarget'];
		$REGISTRY['Core']['TemplatesDir'] = $REGISTRY['Core']['TemplatesDirDefault'];
		$urls = explode('/',strtolower($URL['path']));

		if(getenv('REDIRECT_STATUS')=='404') {
			$urls = $this->getSD($URL,$urls);
			$this->error = 1;
			while(count($urls) and $this->error == 1) {
				$URL['path'] = implode('/',$urls);
				foreach($VST['main'] as $path => $handler) {
					if($path==strtolower($URL['path'])) {
						$this->error = 0;
						header("HTTP/1.0 200 OK");
						$VST[''][$REGISTRY['Request']['RawTarget']] = $VST[''][$URL['path']=='' || (!empty($REGISTRY['subdomain']) && $URL['path']=='/subdomains/'.$REGISTRY['subdomain'] && !empty($REGISTRY['Request']['RawTarget']))?  $this->setErrorInDB() : $this->setPath($URL['path'])];
						$VST['main'][$REGISTRY['Request']['RawTarget']] = $VST['main'][$URL['path']=='' || (!empty($REGISTRY['subdomain']) && $URL['path']=='/subdomains/'.$REGISTRY['subdomain'] && !empty($REGISTRY['Request']['RawTarget']))? $this->setErrorInDB() : $URL['path']];
						//$REGISTRY['Request']['Target'] = explode('/',$URL['path']);
					}
				}
				$entry = array_pop($urls);
			}
			if(in_array($if_allow,$this->allow_urls)) $this->error = 0;
			if($this->error==1) { 
				$VST[''][$REGISTRY['Request']['RawTarget']] = $VST[''][$this->setErrorInDB()];
				$VST['main'][$REGISTRY['Request']['RawTarget']] = $VST['main'][$this->setErrorInDB()];
				//$REGISTRY['Request']['Target'] = array('');
			}
		}
		else if(!in_array($if_allow,$this->allow_urls)) {
			$urls = $this->getSD($URL,$urls);
			$this->error = 1;
			while(count($urls) and $this->error == 1) {
				$URL['path'] = implode('/',$urls);
				if(!in_array(strtolower($URL['path']),array_keys($VST['main']))) {
					$entry = array_pop($urls);
				}
				else {  
					$this->error = 0; 
					$VST[''][@$REGISTRY['Request']['RawTarget']] = $VST[''][$URL['path']=='' || (!empty($REGISTRY['subdomain']) && $URL['path']=='/subdomains/'.$REGISTRY['subdomain'] && !empty($REGISTRY['Request']['RawTarget']))? $this->setErrorInDB() : $this->setPath($URL['path'])];
					$VST['main'][@$REGISTRY['Request']['RawTarget']] = $VST['main'][$URL['path']=='' || (!empty($REGISTRY['subdomain']) && $URL['path']=='/subdomains/'.$REGISTRY['subdomain'] && !empty($REGISTRY['Request']['RawTarget']))? $this->setErrorInDB() : $URL['path']];
					//$REGISTRY['Request']['Target'] = explode('/',$URL['path']);
				}
			}
//printArray( $REGISTRY['VirtualSlotTarget']['main']);		exit;			
			if($this->error == 1) {
				$VST[''][$REGISTRY['Request']['RawTarget']] = $VST[''][$this->setErrorInDB()];
				$VST['main'][$REGISTRY['Request']['RawTarget']] = $VST['main'][$this->setErrorInDB()];
				//$REGISTRY['Request']['Target'] = array('');
			}
		}
		if(!in_array($if_allow,$this->allow_urls)) {
			$this->getPageId($REGISTRY['Request']['RawTarget']);
		}
//printArray($REGISTRY['Page']); exit;
	}

	function getPageId($URL) {  
		global $REGISTRY, $DatabaseBroker;
		if(empty($REGISTRY['VirtualSlotTarget']['main'][$URL])) {
			if($this->parseURLOnCompare($URL)) {
				$REGISTRY['VirtualSlotTarget'][''][$REGISTRY['Request']['RawTarget']] = $REGISTRY['VirtualSlotTarget']['']['#'];
				$REGISTRY['VirtualSlotTarget']['main'][$REGISTRY['Request']['RawTarget']] = $REGISTRY['VirtualSlotTarget']['main']['#'];
			}
			else { 
				header("HTTP/1.0 404 Not Found");
				$REGISTRY['VirtualSlotTarget'][''][$REGISTRY['Request']['RawTarget']] = $REGISTRY['VirtualSlotTarget']['']['?'];
				$REGISTRY['VirtualSlotTarget']['main'][$REGISTRY['Request']['RawTarget']] = $REGISTRY['VirtualSlotTarget']['main']['?'];
			}
		}
		else {
			$query = explode('?',$REGISTRY['VirtualSlotTarget']['main'][$URL]);
			$target = explode(':',array_shift($query));
			switch($target[0]) {
				case 'StoreView': case 'StoreRSSView': $REGISTRY['Page']['entity'] = 'category'; break;
				case 'ProductView': case 'ProductRSSView': $REGISTRY['Page']['entity'] = 'product'; break;
				default: $REGISTRY['Page']['entity'] = 'module'; break;
			}
			$properties = array_shift($query);
			$pair = explode('=',$properties);
			if(!empty($pair[1])) {
				$REGISTRY['Page']['id'] = $pair[1];
				if($REGISTRY['Page']['entity']!='module') {
					$color = $DatabaseBroker->SelectGuide(array($REGISTRY['Page']['entity'].' e','color g'),array('e.id','g.value as name'),array('e.color' => 'g.id', 'e.id' => $REGISTRY['Page']['id']));
					$REGISTRY['Page']['color'] = $color[$REGISTRY['Page']['id']];
				}
			}
		}
	}

	function parseURLOnCompare($URL) {
		global $REGISTRY, $DatabaseBroker;
		if(!isset($REGISTRY['Request']['Compare'])) {
			$REGISTRY['Request']['Compare'] = array();
//print "////////////////////".$URL;			
			$URL = explode('/',$URL);
			if(count($URL) > 2) return false;
			else {
				$colors = $DatabaseBroker->SelectAny('select *, lower(replace(label,\' \',\'-\')) as label from color');
				$color = strstrb($URL[1],'_');
				$color_num = arr_search($colors,"label=='".$color."'");
				if(!validate($color_num)) return false;
				else {
					$query = explode('_compare_',str_replace($color.'_','',$URL[1]));
					if(!in_array(count($query),array(2,3))) return false;
					else {
						$items = array();
						$names = array();
						$products = $DatabaseBroker->SelectAny('select p.id, p.path, p.color, p.name, p.nav_name from product p, parentitem i where i.id = p.item and i.itemtype = 1');
//printArray($query);printArray($products);						
						foreach($products as $value) {
							if(in_array($value['path'],$query) && $value['color']==$color_num[0]['id']) {
								$items[$value['id']] = $value['path'];
								$names[$value['id']] = !empty($value['nav_name'])? $value['nav_name'] : $value['name'];
							}
						}
//printArray($_SESSION);print '...'.count($items).'------'; exit;						
						if(!in_array(count($items),array(2,3))) return false;
						else {
							ksort($items);
							$url = $color.'_'.implode('_compare_',$items);
							if($url==$URL[1]) {
								$REGISTRY['Request']['Compare'] = array(
									'items' => $items,
									'names' => $names,
									'count' => count($items),
									'color' => $color_num[0],
								);
								return true;
							}
							else $this->setLocation($url);
						}
					}
				}
			}
		}
		else if(empty($REGISTRY['Request']['Compare'])) return false;
		return true;
	}

	function setLocation($url) {
		header("HTTP/1.1 301 Moved Permanently");
		header("Location: ".$url);
		exit();
	}

	function getSD($URL,$urls) {
		global $REGISTRY, $DatabaseBroker, $signature;
		$VST = &$REGISTRY['VirtualSlotTarget'];
		$host = getenv('HTTP_HOST');
		foreach($signature['domain'] as $value) $host = preg_replace('/('.$value.')/i','', $host);

		if(preg_match('/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/',$host)) $host = '';
		if(!empty($host)) {
			$domains = explode('.',$host);
			foreach($domains as $key => $value) if(empty($value)) unset($domains[$key]);
			$subdomain = $domains[count($domains)-1];
			$typedomain = $domains[0];
			if(!in_array($subdomain, $this->deny_urls)) {
				$selected = $DatabaseBroker->SelectList('domain','subdomain',array('domain'));
				if(in_array($subdomain,$selected)) {
					$URL['path'] = '/subdomains/'.$subdomain.$URL['path'];
					$urls = explode('/',strtolower($URL['path']));
					$VST['main'][''] = $VST['main']['/'] = isset($VST['main']['/subdomains/'.$subdomain])? $VST['main']['/subdomains/'.$subdomain] : $VST['main'][$this->setErrorInDB()];
					$REGISTRY['subdomain'] = $subdomain;
					if($typedomain!=$subdomain && in_array($typedomain,$this->deny_urls)) $REGISTRY['typedomain'] = $typedomain;
				}
				else { 
//printArray($domains);printArray($selected);exit;
					foreach($VST['main'] as $key => $value) if(preg_match("/^(\/subdomains)/i", $key)) unset($VST['main'][$key]);
					$VST['main'][''] = $VST['main']['/'] = $VST['main'][$this->setErrorInDB()];
					$urls = array('');
				}
			}
			else foreach($VST['main'] as $key => $value) if(preg_match("/^(\/subdomains)/i", $key)) unset($VST['main'][$key]);
		}
		else foreach($VST['main'] as $key => $value) if(preg_match("/^(\/subdomains)/i", $key)) unset($VST['main'][$key]);
		return $urls;
	}

	function setPath($path) {
		global $REGISTRY;
		$VST = &$REGISTRY['VirtualSlotTarget'];
		$query = explode('?',$VST['main'][$path]);
		if(!empty($query[2])) {
			$pair = explode('=',$query[1]);
			$array = getValuesToKeys($VST['main']);
			foreach($array as $key => $value) {
				if($key=='DescribeView:object?id='.$pair[1] ||
					$key=='ProductView:object?id='.$pair[1] ||
					$key=='StoreView:object?id='.$pair[1])
					return $value;
			}
		}
		return $path;
	}

	function setErrorInDB($URL='') {
		global $DatabaseBroker, $REGISTRY;
//print $REGISTRY['Request']['RawTarget'];exit;
		$curl_info = array();
		$URL = @parse_url(getenv('REQUEST_URI'));
		if($this->parseURLOnCompare($URL['path'])) return '#';
		else {  //print "<!-- ".printArray($URL)." -->";exit;
			$REGISTRY['Request']['404'] = true;
			$curl_info['http_code'] = '404';
			/*if(!validate(getenv('HTTPS'))) {
				/*$curl = curl_init();
				curl_setopt($curl, CURLOPT_URL, $this->external_url.$URL['path']);
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); 
				$output = curl_exec($curl);
				$curl_info = curl_getinfo($curl);
				curl_close($curl);
				exit();
			}else $curl_info['http_code'] = '404';*/
			if(!empty($curl_info['http_code']) && $curl_info['http_code']=='200') {
				$output = eregi_replace('src="/','src="'.$this->external_url.'/',$output);
				$output = eregi_replace('background="/','background="'.$this->external_url.'/',$output);
				$output = eregi_replace('href="/','href="'.$this->external_url.'/',$output);
				header("HTTP/1.0 200 OK");
				print $output;
				exit();
			}
			else {
				/*$selected = $DatabaseBroker->SelectAny('select * from error where path=\''.getenv('REQUEST_URI').'\'');
				if(!empty($selected)) {
					$hits = $selected[0]['hits']+1;
					$DatabaseBroker->update('error',array('hits' => $hits,'date' => 'now'),array('id' => $selected[0]['id']));
				}
				else $DatabaseBroker->insert('error',array('hits' => 1,'path' => getenv('REQUEST_URI'),'date' => 'now'));*/
				header("HTTP/1.0 404 Not Found");
				return '?';
			}
		}
	}

	function getTarget() { return $this->Target; }

	function getPath() {
		$path = implode('/',$this->Target);
		if(empty($path)) $path = '/'.$path;
		return $path;
	}

	function deAlias() {
		global $REGISTRY;
		$request = array();
		foreach($this->Request as $key => $value)
			$request[isset($REGISTRY['RequestSettings']['Parameters'][$key])?
				$REGISTRY['RequestSettings']['Parameters'][$key] : $key] = $value;
//printArray($this->Request);printArray($request);
		return $request;
	}

	function getRequestFor($name) {
		if(isset($this->Request['object']) && $this->Request['object'] == $name) return $this->Request;
		else return array();
	}

	function Path($path) {
		return $this->validatePath($path,array());
	}

	function validatePath($path,$subtree) {
		$checked = array();
		if(count($path)) {
			$node = array_shift($path);
			if(isset($subtree[$node])) {
				if(is_array($subtree[$node])) $checked = $this->validatePath($path,$subtree[$node]);
				array_unshift($checked,$node);
			}
		}
		return $checked;
	}
}
?>