<?php
/**
 *      [XCECP] (C) Colorful Network Inc.
 *      This is NOT a freeware, use is subject to license terms
 */

if(!defined("IN_QKWEB")){exit("Access Denied");}
class Dispatcher
{//类定义开始

    /**
     +----------------------------------------------------------
     * URL映射到控制器
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     */
    static public function dispatch()
    {
        $depr = "/";
        // 分析PATHINFO信息
        self::getPathInfo();

        if(!self::routerCheck()){   // 检测路由规则 如果没有则按默认规则调度URL
            $paths = explode($depr,trim($_SERVER['PATH_INFO'],'/'));
			//print_r($paths);
            $var  =  array();
            $var["m"]  =   array_shift($paths);
            $var["a"]  =   array_shift($paths);
            // 解析剩余的URL参数
			//print_r($paths);
            //$res = preg_replace('@(\w+)'.$depr.'([^'.$depr.'\/]+)@e', '$var[\'\\1\']="\\2";', implode($depr,$paths));
			//echo implode($depr,$paths);
			//$res = preg_replace('@(w+)'.$depr.'([^'.$depr.'\/]+)@e', '$var[\'\\1\']=\'\\2\';', implode($depr,$paths));
			//$res = preg_replace('@(\w+)\/([^,\/]+)@e', '$var[\'\\1\']=strip_tags(\'\\2\');', implode('/',$paths));
			$res = preg_match_all('@(\w+)\/([^,\/]+)@', implode('/',$paths),$matches);
			foreach($matches[1] as $key=>$val){$var[$val]=$matches[2][$key];}
			foreach($paths as $path){
				if(substr($path,0,1)!="m"&&substr($path,0,1)!="a"){
					//$res = preg_replace_callback('@([a-z]+)([0-9]+)@', create_function('$matches','return $var[\'$matches[1]\']=\'$matches[2]\';'), $path);
					//preg_replace('@([a-z]+)([0-9]+)@e', '$var[\'\\1\']=\'\\2\';', $path);
					$res = preg_match_all('@([a-z]+)([0-9]+)@', $path,$matches);
					foreach($matches[1] as $key=>$val){$var[$val]=$matches[2][$key];}
				}
			}
			$i=0;
			//print_r($var);//exit;
			$pathArr = explode($depr,trim($_SERVER['PATH_INFO'],'/'));
			foreach($pathArr as $path){
				$_GET['PATH_INFO'][$i]=$path;
				$i++;
			}
			//print_r($var);
			//print_r($_GET);
			//exit;
            $_GET   =  array_merge($_GET,$var);
			//print_r($_GET);
        }
		$MODEL_NAME=self::getModule("m");
		//echo $MODEL_NAME;
		if(defined('APP_DIR') && APP_DIR){
			$opf = APP_DIR."includes/action/".$MODEL_NAME."Action.class.php";	
		}else{
			$opf = ROOT_PATH."includes/action/".$MODEL_NAME."Action.class.php";
		}
		$model = false;
		if(file_exists($opf)){
		}else{
			if(defined('APP_DIR') && APP_DIR){
				return;//exit($MODEL_NAME.'模块不存在');
			}
			global $baseUrl,$db;
			$url = $_SERVER["PATH_INFO"];

			$preg = "/^".str_replace("/","\/",$baseUrl)."/";
			$seoUrl = preg_replace($preg,"",$url);
			$seoUrl = str_replace("'",'',$seoUrl);
			//echo $seoUrl;
			if(substr($seoUrl,0,1)!="/"){$seoUrl = $baseUrl.$seoUrl;}
			if(substr($seoUrl,-1,1)=="/"){$seoUrl=substr($seoUrl,0,strlen($seoUrl)-1);}
			//echo $seoUrl;
			$sql = "select url from qk_seo_url where seoUrl='$seoUrl' or seoUrl='$seoUrl/'";
			$url = $db->getOne($sql);
			//echo $url;
			if(!$url){//echo $url;
				header("HTTP/1.1 404 Not Found");
				Msg::show("文件不存在");
			}else{
				//unset($_GET);
				//echo $url;
				$_SERVER['PATH_INFO'] = $url;
				//echo MODEL_NAME;
				//unset();
				Dispatcher::dispatch();
			}
			return;
		}
        define('MODEL_NAME',$MODEL_NAME);
		$ACTION_NAME = self::getAction("a");
		if($ACTION_NAME=="list"){
			$ACTION_NAME = 'index';
		}
		//echo MODEL_NAME;exit;
		if(strtolower($MODEL_NAME)!="admin" && strtolower($MODEL_NAME)!="user"){
			require_once($opf);
			$modelName = ucfirst(strtolower(MODEL_NAME)."Action");
			$model = new $modelName;
			$actionName = strtolower($ACTION_NAME);
			if(!method_exists($model,$actionName)){
				global $baseUrl,$db;
				$url = $_SERVER["PATH_INFO"];
				$preg = "/^".str_replace("/","\/",$baseUrl)."/e";
				$seoUrl = preg_replace($preg,"",$url);
						$seoUrl = str_replace("'",'',$seoUrl);
	//echo $seoUrl;
				if(substr($seoUrl,0,1)!="/"){$seoUrl = $baseUrl.$seoUrl;}
				if(substr($seoUrl,-1,1)=="/"){$seoUrl=substr($seoUrl,0,strlen($seoUrl)-1);}
				//echo $seoUrl;
				$sql = "select url from qk_seo_url where seoUrl='$seoUrl' or seoUrl='$seoUrl/'";
				$url = $db->getOne($sql);
				if(!$url){
					header("HTTP/1.1 404 Not Found");
					Msg::show("404 Action Not Found");
				}else{
					//unset($_GET);
					$_SERVER['PATH_INFO'] = $url;
					//echo MODEL_NAME;
					//unset();
					Dispatcher::dispatch();
				}
				return;
			}
		}
		
		/*
		if(!in_array($ACTION_NAME,array("list","index","add","edit","detail","ownerInfo","passwd","search","logout","login","info","check","submit","view","goods","category","post","brand","tuan","register","regsuccess","order","pay","finance","shoppingcart","article","onlinepay","user","password","hotkey","ad","adplace","attachment","variable","articlecat","site","seo","seopage","servicecat","register","address","industry","profile","payreturn","paynotify","result","roleaction","rolepage","role","forget"))){
			$res = preg_replace('@([a-z]+)([0-9]+)@e', '$var[\'\\1\']="\\2";', $ACTION_NAME);
			if(isset($var) && is_array($var)) $_GET   =  array_merge($var,$_GET);
			$ACTION_NAME = 'index';
		}
		*/
        define('ACTION_NAME',$ACTION_NAME);
		$_GET['a']=$ACTION_NAME;
		$_GET['m']=$MODEL_NAME;
        // URL常量
        // 当前页面地址
        //define('__SELF__',$_SERVER['PHP_SELF']);
        define('__SELF__',$_SERVER['REQUEST_URI']);
        define('__INFO__',$_SERVER['PATH_INFO']);
        // 当前模块和分组地址
        $module = defined('P_MODULE_NAME')?P_MODULE_NAME:MODEL_NAME;
        if(defined('GROUP_NAME')) {
            $group   = C('URL_CASE_INSENSITIVE') ?strtolower(GROUP_NAME):GROUP_NAME;
            define('__GROUP__',(!empty($domainGroup) || GROUP_NAME == C('DEFAULT_GROUP') )?__APP__ : __APP__.'/'.$group);
            define('__URL__',!empty($domainModule)?__GROUP__.$depr : __GROUP__.$depr.$module);
        }else{
           // define('__URL__',!empty($domainModule)?'/' : __APP__.'/'.$module);
        }
        // 当前操作地址
       // define('__ACTION__',__URL__.$depr.ACTION_NAME);
        //保证$_REQUEST正常取值
        $_REQUEST = array_merge($_POST,$_GET);
    }

    /**
    +----------------------------------------------------------
    * 获得服务器的PATH_INFO信息
    +----------------------------------------------------------
    * @access public
    +----------------------------------------------------------
    * @return void
    +----------------------------------------------------------
    */
    public static function getPathInfo()
    {
        if(!empty($_SERVER['PATH_INFO'])){
            $pathInfo = $_SERVER['PATH_INFO'];
            if(0 === strpos($pathInfo,$_SERVER['SCRIPT_NAME']))
                $path = substr($pathInfo, strlen($_SERVER['SCRIPT_NAME']));
            else
                $path = $pathInfo;
        }elseif(!empty($_SERVER['ORIG_PATH_INFO'])) {
            $pathInfo = $_SERVER['ORIG_PATH_INFO'];
            if(0 === strpos($pathInfo, $_SERVER['SCRIPT_NAME']))
                $path = substr($pathInfo, strlen($_SERVER['SCRIPT_NAME']));
            else
                $path = $pathInfo;
        }elseif (!empty($_SERVER['REDIRECT_PATH_INFO'])){
            $path = $_SERVER['REDIRECT_PATH_INFO'];
        }elseif(!empty($_SERVER["REDIRECT_Url"])){
            $path = $_SERVER["REDIRECT_Url"];
            if(empty($_SERVER['QUERY_STRING']) || $_SERVER['QUERY_STRING'] == $_SERVER["REDIRECT_QUERY_STRING"])
            {
                $parsedUrl = parse_url($_SERVER["REQUEST_URI"]);
                if(!empty($parsedUrl['query'])) {
                    $_SERVER['QUERY_STRING'] = $parsedUrl['query'];
                    parse_str($parsedUrl['query'], $GET);
                    $_GET = array_merge($_GET, $GET);
                    reset($_GET);
                }else {
                    unset($_SERVER['QUERY_STRING']);
                }
                reset($_SERVER);
            }
        }
        if(defined('URL_HTML_SUFFIX') && !empty($path)) {
            $path = preg_replace('/\.'.trim(URL_HTML_SUFFIX,'.').'$/', '', $path);
        }
        $_SERVER['PATH_INFO'] = empty($path) ? '/' : $path;
    }

    /**
     +----------------------------------------------------------
     * 路由检测
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     */
    static public function routerCheck() {
        $regx = trim($_SERVER['PATH_INFO'],'/');
        if(empty($regx)) return true;
        // 是否开启路由使用
        if(!defined('URL_ROUTER_ON') || !URL_ROUTER_ON) return false;
        // 路由定义文件优先于config中的配置定义
        $routes = "/";
        // 路由处理
        if(!empty($routes))
        {
            $depr = "/";
            foreach ($routes as $key=>$route){
                if(0 === stripos($regx.$depr,$route[0].$depr)) {
                    // 简单路由定义：array('路由定义','分组/模块/操作名', '路由对应变量','额外参数'),
                    $var  =  self::parseUrl($route[1]);
                    //  获取当前路由参数对应的变量
                    $paths = explode($depr,trim(str_ireplace($route[0].$depr,$depr,$regx),$depr));
                    $vars    =   explode(',',$route[2]);
                    for($i=0;$i<count($vars);$i++)
                        $var[$vars[$i]]     =   array_shift($paths);
                    // 解析剩余的URL参数
                    $res = preg_replace('@(\w+)\/([^,\/]+)@e', '$var[\'\\1\']="\\2";', implode('/',$paths));
                    $_GET   =  array_merge($var,$_GET);
                    if(isset($route[3])) {
                        parse_str($route[3],$params);
                        $_GET   =   array_merge($_GET,$params);
                    }
                    return true;
                }elseif(1 < substr_count($route[0],'/') && preg_match($route[0],$regx,$matches)) {
                    // 路由定义规则：array('正则定义','分组/模块/操作名', '路由对应变量','额外参数'),
                    $var  =  self::parseUrl($route[1]);
                    //  获取当前路由参数对应的变量
                    $vars    =   explode(',',$route[2]);
                    for($i=0;$i<count($vars);$i++)
                        $var[$vars[$i]]     =   $matches[$i+1];
                    // 解析剩余的URL参数
                    $res = preg_replace('@(\w+)\/([^,\/]+)@e', '$var[\'\\1\']="\\2";', str_replace($matches[0],'',$regx));
                    $_GET   =  array_merge($var,$_GET);
                    if(isset($route[3])) {
                        parse_str($route[3],$params);
                        $_GET   =   array_merge($_GET,$params);
                    }
                    return true;
                }
            }
        }
        return false;
    }

    static private function parseUrl($route) {
        $array   =  explode('/',$route);
        $var  =  array();
        $var[C('VAR_ACTION')] = array_pop($array);
        $var[C('VAR_MODULE')] = array_pop($array);
        if(!empty($array)) $var[C('VAR_GROUP')]  = array_pop($array);
        return $var;
    }

    /**
     +----------------------------------------------------------
     * 获得实际的模块名称
     +----------------------------------------------------------
     * @access private
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static private function getModule($var)
    {
		
        $module = (!empty($_GET[$var])? $_GET[$var]:"Index");
        if(defined("URL_CASE_INSENSITIVE")) {
            // URL地址不区分大小写

            $P_MODULE_NAME = strtolower($module);
			
            // 智能识别方式 index.php/user_type/index/ 识别到 UserTypeAction 模块
            $module = ucfirst(parse_name($P_MODULE_NAME,1));
        }
        
        return ucfirst($module);
    }

    /**
     +----------------------------------------------------------
     * 获得实际的操作名称
     +----------------------------------------------------------
     * @access private
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static private function getAction($var)
    {
        $action   = !empty($_POST[$var]) ?
            $_POST[$var] :
            (!empty($_GET[$var])?$_GET[$var]:"index");
        unset($_POST[$var],$_GET[$var]);
        return defined('URL_CASE_INSENSITIVE')?strtolower($action):$action;
    }

    /**
     +----------------------------------------------------------
     * 获得实际的分组名称
     +----------------------------------------------------------
     * @access private
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static private function getGroup($var)
    {
        $group   = (!empty($_GET[$var])?$_GET[$var]:C('DEFAULT_GROUP'));
        unset($_GET[$var]);
        return ucfirst(strtolower($group));
    }
}//类定义结束
?>