<?PHP

/**
* this is private for engine
*/
class Request{

	var $requiredType = '';
	var $requiredLength = '';

	//validate functions

	function match($value, $match){

		if(substr($match, 0, 1) != '/'){

			if(preg_match('/'.$match.'/i', $value))
				return false;
		}
		else{

			if(preg_match($match, $value))
				return false;
		}

		return true;
	}

	function is_string($value){

		if(!preg_match('/([0-9_]+)/i', $value))
			return false;

		return true;
	}

	function is_numeric($value){

		if(preg_match('/([a-zA-Z\/\|\&\(\)\!\=\-\<\>\[\]\{\?\'\"\"\:\;\.\,\_\$\+\-[:space:]_]+)/i', $value) || strlen($value) == 0)
			return true;

		return false;
	}

	function is_string_numeric($value){

		if(preg_match('/([a-zA-Z_]+)/i', $value) && preg_match('/([0-9_]+)/i', $value))
			return false;

		return true;
	}

	function email($value){

		if(filter_var($value, FILTER_VALIDATE_EMAIL))
			return false;

		return true;
	}

	function equal_to($value1, $value2){
		
		if($value1 == $value2)
			return false;
		return true;
	}

	function is_set($value){

		if(strlen($value) > 0)
			return false;

		return true;
	}

	function is_true($value1, $value2){

		if($value2 == true)
			return false;
		return true;
	}

	function is_password($value, $width){
		
		if(!$width)
			$width = '5,12';

		return $this->match($value, '/^(?=.*\d)(?=.*[A-Z])[0-9A-Za-z!@#$%]{'.$width.'}$/');
	}

	//validate functions END

	function getValidateValue($name, $data){

		if(preg_match('/\[|\]/i', $name)){

			$eval = 'return $data['.str_replace(strstr($name, '['), '', $name).']'.strstr($name, '[').';';
			return eval($eval);
		}
		return $data[$name];
	}

	function checkRequestAccuracy($type, $validate_data, $data){

		$error = false;
		if(!empty($validate_data)){

			foreach($validate_data as $name => $validate){

				if(is_numeric($name)){

					$name = $validate;
					$validate = '';
				}

				$value = trim($this->getValidateValue($name, $data));
				list($validate_function, $validate_value) = explode('=', $validate);
				if( '"'.str_replace('"', '', $validate_value).'"' == $validate_value )
					$validate_value = str_replace('"', '', $validate_value);
				else
					$validate_value = $data[$validate_value];
				$validate_function = !$validate_function || !method_exists($this, trim($validate_function)) ? 'is_set' : $validate_function;

				$error = $this->$validate_function($value, $validate_value);
				if($error == true){

					$this->activate = false;
					$this->error[$name] = true;
				}
				else{

					$this->error[$name] = false;
				}
			}
		}
	}

	function validate($set_to_validate, $data){

		if($this->query_method == 'POST'){

			if($this->activate == true){

				$this->checkRequestAccuracy('POST', $set_to_validate, $data);
			}
		}
		if($this->query_method == 'GET'){

			if($this->activate == true){

				$this->checkRequestAccuracy('GET', $set_to_validate, $data);
			}
		}
	}

	function split_request($request){

		preg_match('/([a-zA-Z0-9\__]+)\=([a-zA-Z0-9\__]+)/se', $request, $match);
		$name = $match[1];
		$value = $match[2];
		return array($name, $value);
	}

	function POST($name, $validate_data=array(), $by_value=false){

		$this->activate = false;
		list($eq_name, $eq_value) = $this->split_request($name);

		if($eq_name && $eq_value){

			if($_POST[$eq_name] == $eq_value){

				$this->method = $eq_value;
				$this->activate = true;
			}
			return $this;
		}
		else{

			if($_POST[$name]){

				$this->method = $by_value ? $_POST[$name] : $name;
				$this->activate = true;
			}
		}

		$this->req_type = '_POST';
		$this->request = $_POST;
		$this->req_name = $name;
		return $this;
	}

	function GET($name, $validate_data=array(), $by_value=false){

		$this->activate = false;
		list($eq_name, $eq_value) = $this->split_request($name);

		if($eq_name && $eq_value){

			if($_GET[$eq_name] == $eq_value){

				$this->method = $eq_value;
				$this->activate = true;
			}
			return $this;
		}
		else{

			if($_GET[$name]){

				$this->method = $by_value ? $_GET[$name] : $name;
				$this->activate = true;
			}
		}

		$this->req_type = '_GET';
		$this->request = $_GET;
		$this->req_name = $name;
		return $this;
	}

	function PARAM($param){

		$this->activate = false;

		if($param){

			$this->activate = true;
		}

		$this->req_type = '_NONE';
		$this->request = $param;
		$this->req_name = 'NONE';
		return $this;
	}

	function escape($str){

			$search=array("\\","\0","\n","\r","\x1a","'",'"');
			$replace=array("\\\\","\\0","\\n","\\r","\Z","\'",'\"');
			return str_replace($search,$replace,$str);
	}

	function injectionRestriction(){

		foreach($_GET as $k => $v){

			if(is_array($v)){

				foreach($v as $k1 => $v1){

					//$v[$k1] = mysql_real_escape_string($v1);
					$v[$k1] = $this->escape($v1);
				}
			}
			else{

				if(preg_match('/show tables/i', strtolower($v)) || preg_match('/show columns/i', strtolower($v)) || preg_match('/select(.*?)from/i', strtolower($v))){

					unset($v);
				}

				//$_GET[$k] = mysql_real_escape_string($v);
				$_GET[$k] = $this->escape($v);
			}
		}
		foreach($_POST as $k => $v){

			if($k != 'fckeditor' && $k != 'content' && $k != 'content_source' && $k != 'content_source_result' && $k != 'description_add' && $k != 'description'){

				if(is_array($v)){

					foreach($v as $k1 => $v1){

						if(is_array($v1)){

							foreach($v1 as $k2 => $v2){

								//$v1[$k2] = mysql_real_escape_string($v2);
								$v1[$k2] = $this->escape($v2);
							}
						}
						else{

							//$v[$k1] = mysql_real_escape_string($v1);
							$v[$k1] = $this->escape($v1);
						}
					}
				}
				else{

					if(preg_match('/show tables/i', strtolower($v)) || preg_match('/show columns/i', strtolower($v)) || preg_match('/select(.*?)from/i', strtolower($v))){

						unset($v);
					}

					//$_POST[$k] = mysql_real_escape_string($v);
					$_POST[$k] = $this->escape($v);
				}
			}
		}
		//$_SERVER['REQUEST_URI'] = mysql_real_escape_string($_SERVER['REQUEST_URI']);
		$_SERVER['REQUEST_URI'] = $this->escape($_SERVER['REQUEST_URI']);
	}

	function convertRequest(){

		if($_GET['request']){

			$this->Sql->table = 'redirect_link';
			$request = $_SERVER['REQUEST_URI'];
			$request = $this->escape($request);
			$request = str_replace('%C3%B5', 'õ', $request);
			$request = str_replace('%C3%A4', 'ä', $request);
			$request = str_replace('%C3%B6', 'ö', $request);
			$request = str_replace('%C3%BC', 'ü', $request);
			$request = str_replace('%C3%95', 'Õ', $request);
			$request = str_replace('%C3%84', 'Ä', $request);
			$request = str_replace('%C3%96', 'Ö', $request);
			$request = str_replace('%C3%9C', 'Ü', $request);
			if(preg_match('/\+/i', $request)){

				$requestTmp = $request;
				$request = '';

				foreach(explode('+', $requestTmp) as $v){

					$request .= $request ? '+'.urldecode($v) : urldecode($v);
				}
			}
			else{

				$request = urldecode($request);
			}
			$_GET['request'] = $request;
			if(substr($_GET['request'], 0, 1) == '/')
				$_GET['request'] = substr($_GET['request'], 1);
			$retUrl = $_GET['request'];
			list($retUrl, $retUrlAppend) = explode('?', $retUrl);

			$row = $this->Sql->Query("SELECT SQL_CACHE * FROM redirect_link USE INDEX(redirect_url) WHERE redirect_url = '".addslashes($retUrl)."' LIMIT 1 ", true);
			if($this->Sql->Numrows == 0 && substr($retUrl, -1) != '/')
				$row = $this->Sql->Query("SELECT SQL_CACHE * FROM redirect_link USE INDEX(redirect_url) WHERE redirect_url = '".addslashes($retUrl.'/')."' LIMIT 1 ", true);

			//file_put_contents(_RootFolder.'/tmp/requests.txt', "SELECT SQL_CACHE * FROM redirect_link USE INDEX(redirect_url) WHERE redirect_url = '".addslashes($retUrl)."' LIMIT 1 ");
			//echo "<span style=\"display:none;\">SELECT SQL_CACHE * FROM redirect_link USE INDEX(redirect_url) WHERE redirect_url = '".addslashes($retUrl)."' LIMIT 1 </span>";
			if($row[0]['canonical_url']){

				$canonical_url = $row[0]['canonical_url'];
				$dead_url = false;
				$redirect_id = 0;

				foreach($row as $v){

					if($v['is_deleted'] == 0){

						$canonical_url = $v['canonical_url'];
					}
					if($v['is_deleted'] == 1){

						$dead_url = true;
						$redirect_id = $v['redirect_id'];
					}
				}
				if($dead_url == true){

					$Location = _RootUrl;

					if($redirect_id > 0){

						$row = $this->Sql->Query("SELECT SQL_CACHE * FROM redirect_link USE INDEX(redirect_url) WHERE id = ".$redirect_id, true);
						if($row[0]['canonical_url']){

							$Location = _RootUrl.'/'.$row[0]['redirect_url'];
						}
					}

					die(header('Location: '.$Location, true, 301));
				}

				//preg_match_all('//se', $canonical_url, $matches);

				foreach(explode('&', $canonical_url) as $v){

					$v = str_replace('?', '', $v);
					list($key, $value) = explode('=', $v);

					if($key && $value){

						$value = str_replace('-', ' ', $value);
						$_GET[$key] = $value;
						$prev_key = $key;
					}
					else{

						$key = str_replace('-', ' ', $key);
						$value = str_replace('-', ' ', $value);
						$_GET[$prev_key] .= '&'.$key.$value;
					}
				}
				if($retUrlAppend){

					$canonical_url .= '&'.str_replace('/?', '', $retUrlAppend);

					foreach(explode('&', str_replace('/?', '', $retUrlAppend)) as $v){

						$v = str_replace('?', '', $v);
						list($key, $value) = explode('=', $v);

						if($key && $value){

							$value = str_replace('-', ' ', $value);
							$_GET[$key] = $value;
							$prev_key = $key;
						}
						else{

							if($prev_key){

								$key = str_replace('-', ' ', $key);
								$value = str_replace('-', ' ', $value);
								$_GET[$prev_key] .= '&'.$key.$value;
							}
						}
					}
				}

				$canonical_url = str_replace('&', '&amp;', $canonical_url);
				$canonical_url = str_replace("'", '&apos;', $canonical_url);
				$canonical_url = str_replace('"', '&quot;', $canonical_url);
				$canonical_url = str_replace('<', '&lt;', $canonical_url);
				$canonical_url = str_replace('>', '&gt;', $canonical_url);
				define ('_FULL_URL', $canonical_url);
			}
			else{

				$exp = explode('/', $_GET['request']);
				$request = $exp[count($exp)-1];
				foreach(explode('&', str_replace('/?', '', $request)) as $v){

					$v = str_replace('?', '', $v);
					list($key, $value) = explode('=', $v);

					if($key && $value){

						$_GET[$key] = $value;
						$prev_key = $key;
					}
					else{

						if($prev_key)
							$_GET[$prev_key] .= '&'.$key.$value;
					}
				}
				$_GET['request'] = str_replace('&', '&amp;', $_GET['request']);
				$_GET['request'] = str_replace("'", '&apos;', $_GET['request']);
				$_GET['request'] = str_replace('"', '&quot;', $_GET['request']);
				$_GET['request'] = str_replace('<', '&lt;', $_GET['request']);
				$_GET['request'] = str_replace('>', '&gt;', $_GET['request']);
				define ('_FULL_URL', str_replace('/?', '', $_GET['request']));
			}
			/*print '<pre>';
			print_R ($_GET);*/
			//echo "SELECT SQL_CACHE * FROM redirect_link WHERE redirect_url = '".addslashes($retUrl)."'<br>";
		}
		//file_put_contents(_RootFolder.'/tmp/requests.txt', "SELECT SQL_CACHE * FROM redirect_link USE INDEX(redirect_url) WHERE redirect_url = '".addslashes($retUrl)."' LIMIT 1 ".json_encode($_GET));
		if(!defined('_FULL_URL')){

			$window_location_href = '';
			if(is_array($_GET)){

				foreach($_GET as $name => $val){

					$window_location_href .= $window_location_href ? '&'.$name.'='.$val : '?'.$name.'='.$val;
				}
			}
			define ('_FULL_URL', $window_location_href);
		}
		if($_SESSION['UserData']['user_id'])
			$this->Sql->Query("INSERT INTO logs_get (`get`, `post`, `created_by`, `created_by_id`, `created_at`) VALUES ('".addslashes(json_encode($_GET))."', '".addslashes(json_encode($_POST))."', '".$_SESSION['UserData']['name']."', '".$_SESSION['UserData']['user_id']."', NOW()) ");
	}
}
