<?php
/*
 +----------------------------------------------------------------------
 | TEMMOKUMVC [ NO BEST , ONLY BETTER ]
 +----------------------------------------------------------------------
 | Copyright (c) 2018~2019 https://www.temmoku.cn All rights reserved.
 +----------------------------------------------------------------------
 | Author: 张宗强 Email:webmaster@temmoku.cn QQ:158726877 516669373 TEL:17895221001 微信:temmokumvc
 +---------------------------------------------------------------------- 
*/
namespace temmoku;
class route{
	
	function __construct()
    {    		
    	//加载模块配置信息
	   	$route=APP_PATH.'module_route.php';
	    is_file($route) && Load_conf($route);
    	define('NOW_TIME',      $_SERVER['REQUEST_TIME']);
        define('REQUEST_METHOD',$_SERVER['REQUEST_METHOD']);
        self::Route();
   	}
    static public function Route(){
    		if($_GET['temmoku_dirs']){
    			$_SERVER['PATH_INFO']=$_GET['temmoku_dirs'];
    		}
			// 分析PATHINFO信息/不存在执行内部
			if(!isset($_SERVER['PATH_INFO'])) {
				//循环匹配内中的值，如果存在跳出
				$types   =  explode(',','HTTP_X_REWRITE_URL,REDIRECT_PATH_INFO,REDIRECT_URL');
				foreach ($types as $type){
					if(0===strpos($type,':')) {
						$_SERVER['PATH_INFO'] =   call_user_func(substr($type,1));
						break;
					}elseif(!empty($_SERVER[$type])) {
						$_SERVER['PATH_INFO'] = (0 === strpos($_SERVER[$type],$_SERVER['SCRIPT_NAME']))?
						substr($_SERVER[$type], strlen($_SERVER['SCRIPT_NAME']))   :  $_SERVER[$type];
						break;
					}
				}
			}
			if($_SERVER['PATH_INFO']){
				$PATH_INFO=explode("/",$_SERVER['PATH_INFO']);
				foreach($PATH_INFO AS $value){
					if(!$value){
						continue;
					}
					$_PATH_INFO[]=$value;
				}
				if($_PATH_INFO){
					$_SERVER['PATH_INFO']=implode('/',$_PATH_INFO);
				}
			}
       		//先进行域名绑定验证
			if(C('ROUTE') && array_key_exists($_SERVER['HTTP_HOST'],C('ROUTE'))){
				$route=C('ROUTE')[$_SERVER['HTTP_HOST']];
				if(is_array($route)){
					$modular=strtolower($route['dir']);
					if($route['controller']) define('CONTROLLER',$route['controller']); 
					if($route['method']) define('METHOD',$route['method']); 
					if($route['data']){
						foreach ((array)$route['data'] AS $key=>$value){
							if ($route['request_method']) {
								$_POST[$key]=$value;
							}else{
								$_GET[$key]=$value;
							}
						}
					}
				}else{
					$modular=strtolower($route);
				}
				define('MODULE',$modular);
			}

			define('MODULE_PATHINFO_DEPR',  '/');
			//trim 去除字符串首尾处的空白字符（或者其他字符）如/
			if(isset($_SERVER['PATH_INFO'])&& $_SERVER['PATH_INFO']){
				$_SERVER['PATH_INFO'] =   trim($_SERVER['PATH_INFO'],'/');
				//获取网址的后戳
				$EXT=pathinfo($_SERVER['PATH_INFO'],PATHINFO_EXTENSION);
				// 去除URL后缀
				$html =$EXT ? (C('HTML') ? C('HTML') : '.html') : false;
				$_SERVER['PATH_INFO'] = preg_replace( $html ? '/\.('.trim($html ,'.').')$/i' : '/\.'.$EXT.'$/i', '', $_SERVER['PATH_INFO']);
	       	}
			
	       	$lock=APP_PATH.'conf/install.lock';
			if(false===defined('MODULE')){
				if (isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO']){ // 获取先尝试获取模块名
					$paths      =   explode(MODULE_PATHINFO_DEPR,$_SERVER['PATH_INFO'],2);;
					$test_module     =   strtolower(preg_replace('/\.' . $EXT . '$/i', '',$paths[0]));
					//判断是否安装了
					if(!is_file($lock) && $test_module !='install'  && !$_GET['step']){
						self::test_is_mod_rewrite();
					}else{
						//是否存在MODULE_ROTUE
						if(in_array($test_module,C('MODULE_ROTUE'))){
							define('MODULE',strtolower($test_module));
							$_SERVER['PATH_INFO']   =   isset($paths[1])?$paths[1]:'';
						}else{
							//如果上面都是判断下是不是插件
							$plugin_route_file=APP_PATH.'plugin_route.php';
							is_file($plugin_route_file) && extract(include $plugin_route_file);
							if($Plugin_Route && in_array($test_module,$Plugin_Route)){
								define('MODULE',strtolower($test_module));
								$_SERVER['PATH_INFO']   =   isset($paths[1])?$paths[1]:'';
								define('is_plugin',true);
							}
						}
					}
				}else{
					
					if(!is_file($lock) && !defined('MODULE')  && !$_GET['step']){
						self::test_is_mod_rewrite();
					}else{
						if(C('index') && C('index') != 'home'){
							define('MODULE',strtolower(C('index')));
						}
					}
				}
			}
			
			if($test_module && false===defined('MODULE')){
				define('MODULE','home');
			}
			
			
			if(C('webstate')=='0' && 'admin'!==MODULE ){
				(new controller)->err(C('close_why'));
			}
			
			if('1'===C('URL_RULES') || 'admin'!==MODULE){
	    		!empty($_GET['m']) && define('MODULE',strtolower($_GET['m']));
	    		!empty($_GET['c']) && define('CONTROLLER',strtolower($_GET['c'])); 
				!empty($_GET['a']) && define('METHOD',$_GET['a']);
	    	}
	
        	//如果没有匹配到或者没有设置模块
        	C('index') ? defined('MODULE') || define('MODULE',C('index')) : defined('MODULE') || define('MODULE','home');

			if(in_array(strtolower(MODULE),C('MODULE_ROTUE')) && 'admin'===MODULE){
				return self::Admin_Route();
        	}

			//开始加载一些模块需要私有的函数文件，如果存在
			defined('is_plugin') ? $plugin='plugin/' : $plugin="";
			
			$function= APP_PATH.$plugin.MODULE."/function.php";
			if(is_file($function)){
				include_once $function;
			}
			//加载模块Route
			$_rute_file=APP_PATH.$plugin.MODULE."/route.php";
			if(is_file($_rute_file)){//这里需要判断下,因为有的模块可能不存在.比如admin,user
				$_rute=str_replace('/','\\',$plugin.MODULE."\\route");
				(new $_rute)->route();
			}
			
			if(isset($_SERVER['PATH_INFO'])){
				//默认路径解析全网址，标准伪静态网址
				$_paths      =   explode(MODULE_PATHINFO_DEPR,$_SERVER['PATH_INFO']);
				if($_paths){
					!empty($_paths[0]) && (defined('CONTROLLER') or define('CONTROLLER',strtolower($_paths[0]))) && array_shift  ( $_paths  ); 
					!empty($_paths[0]) && (defined('METHOD') or define('METHOD',$_paths[0])) && array_shift  ( $_paths  );
	
					//解析参数
					foreach($_paths AS $_paths_k=>$V){
						if($_paths_k%2==1){
							$_GET[$_paths[$_paths_k-1]]=$_paths[$_paths_k];
						}elseif($_paths[$_paths_k]){
							$_GET[$_paths[$_paths_k]]=$_paths[$_paths_k+1];
						}
					}
				}
			}
			defined('CONTROLLER') or define('CONTROLLER','index'); 
			defined('METHOD') or define('METHOD','index');

    }
    
    static private function Admin_Route(){
    	$_REDIRECT_URL[1] =$_REDIRECT_URL[0] = 'index';
		
		if($_SERVER['PATH_INFO']){
			$_REDIRECT_URL=explode("/",$_SERVER['PATH_INFO']);
			$__REDIRECT_URL=$_REDIRECT_URL;
			unset($_REDIRECT_URL);
			foreach($__REDIRECT_URL as $v){
				if(!$v){
					continue;
				}
				$_REDIRECT_URL[]=$v;
			}
			if('modular'==$_REDIRECT_URL[1]){
				isset($_REDIRECT_URL[2]) && define('M_MODULE',strtolower($_REDIRECT_URL[2])); 
				define('M_CONTROLLER',strtolower($_REDIRECT_URL[3]) ? strtolower($_REDIRECT_URL[3]) : 'index'); 
				define('M_METHOD',$_REDIRECT_URL[4] ? $_REDIRECT_URL[4] : 'index'); 
			}elseif('plugin'==$_REDIRECT_URL[1]){
				isset($_REDIRECT_URL[2]) && define('P_MODULE',strtolower($_REDIRECT_URL[2])); 
				define('P_CONTROLLER',strtolower($_REDIRECT_URL[3]) ? strtolower($_REDIRECT_URL[3]) : 'index'); 
				define('P_METHOD',$_REDIRECT_URL[4] ? $_REDIRECT_URL[4] : 'index'); 
			}
			//打印自定义常量
			foreach($_REDIRECT_URL AS $KEY=>$VAL){
				//其它参数使用下划线分割
				@list($_key,$_value)=explode("_",$VAL);
				if(!$_value && $_value !='0' ){
					continue;
				}
				//---要替换成反斜杠
				$_value=str_replace("---","/",$_value); 
				$_key=str_replace("---","/",$_key); 
				//+++要替换成下划线
				$_key=str_replace("+++","_",$_key); 
				$_value=str_replace("+++","_",$_value); 
				$_GET[$_key]=$_value;
			}
		}
		define('CONTROLLER',strtolower($_REDIRECT_URL[0]) ? strtolower($_REDIRECT_URL[0]) : 'index'); 
		define('METHOD',$_REDIRECT_URL[1] ? $_REDIRECT_URL[1] : 'index');
    }

    static public function filtering()
    { 
		$_GET = filtering($_GET );
		$_POST = filtering($_POST );
		$_COOKIE = filtering($_COOKIE);
		$_SESSION = filtering($_SESSION);
		$_SERVER = filtering($_SERVER);
    }
    // 检测自定义全局变量（register globals）并移除
    static public function un_reg_ister_Globals()
    {
        if (ini_get('register_globals')) {
            $array = ['_SESSION', '_POST', '_GET', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES'];
           	foreach ($array as $value) {
                foreach ($GLOBALS[$value] as $key => $var) {
                    if ($var === $GLOBALS[$key]) {
                        unset($GLOBALS[$key]);
                    }
                }
            }
        }
    }
    
	static public function test_is_mod_rewrite(){
		//检测是否支持伪静态
		$paths      =   explode(MODULE_PATHINFO_DEPR,$_SERVER['PATH_INFO'],1);
		if($paths['0']=='test_is_mod_rewrite'){
			exit('1');
		}
		$data=http_request(get_url().'/test_is_mod_rewrite/');
		if($data=='1'){
			header('Location:/install/index/index');
			exit;
		}else{
			exit('你的空间不支持伪静态，访问网址<a HREF="http://bbs.temmoku.cn/category/2/articles_1.shtml">http://bbs.temmoku.cn/category/2/articles_1.shtml</A>修改');
		}
	}
    /**
     * 析构方法
     */
    public function __destruct() {
       self::filtering();
       self::un_reg_ister_Globals();
    }
}
?>
