<?php
require 'xingcai_lib/core/DBAccess.class';
require 'xingcai_lib/core/Object.class';
require 'xingcai_back/WebBase.class.php';
require 'xingcai_back/WebLoginBase.class.php';

require 'xingcai_config.php';

function notfound($message){
	header('content-Type: text/plain; charset=utf8');
	header('HTTP/1.1 404 Not Found');
	die($message);
}

if (!function_exists('jms_emit_json_payload')) {
	function jms_emit_json_payload($payload, $jsonFlags) {
		if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
			$js = json_encode($payload, $jsonFlags);
			if ($js === false && $jsonFlags) {
				$fb = defined('JSON_UNESCAPED_UNICODE') ? JSON_UNESCAPED_UNICODE : 0;
				$js = json_encode($payload, $fb);
			}
		} else {
			$js = json_encode($payload);
		}
		echo ($js !== false) ? $js : '{"ok":false,"error":"json_encode_failed"}';
	}
}

function is_mobile(){
 
	     //正则表达式,批配不同手机浏览器UA关键词。
 
	     $regex_match="/(nokia|iphone|android|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|";
 
	     $regex_match.="htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|";
 
	     $regex_match.="blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|";
 
	     $regex_match.="symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|";
 
	     $regex_match.="jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320x320|240x320|176x220";
 
	     $regex_match.=")/i";
 
	    
 
	     return isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE']) or preg_match($regex_match, strtolower($_SERVER['HTTP_USER_AGENT'])); //如果UA中存在上面的关键词则返回真。
 
	}
 

$para=array();

$__routePath = '';
if (isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] !== '') {
	$__routePath = $_SERVER['PATH_INFO'];
} elseif (isset($_GET['s']) && $_GET['s'] !== '') {
	$__routePath = '/' . ltrim((string) $_GET['s'], '/');
} elseif (!empty($_SERVER['REQUEST_URI'])) {
	$__reqUri = $_SERVER['REQUEST_URI'];
	$__qpos = strpos($__reqUri, '?');
	if ($__qpos !== false) {
		$__reqUri = substr($__reqUri, 0, $__qpos);
	}
	if (preg_match('#/index\.php(/[^/].*)$#', $__reqUri, $__m)) {
		$__routePath = $__m[1];
	}
	unset($__reqUri, $__qpos, $__m);
}

if ($__routePath !== '') {
	$para=explode('/', substr($__routePath, 1));
	if($control=array_shift($para)){
		if(count($para)){
			$action=array_shift($para);
		}else{
			$action=$control;
			$control='index';
		}
	}else{
		$control='index';
		$action='main';
	}
} else {
	$control='index';
	$action='main';
}
unset($__routePath);
$control=ucfirst($control);

if(strpos($action,'-')!==false){
	list($action, $page)=explode('-',$action);
}

$file=$conf['action']['modals'].$control.'.class.php';

if(!is_file($file)) notfound('找不到控制器');
try{
	require $file;
}catch(Exception $e){
	print_r($e);
	exit;
}

if(!class_exists($control)) notfound('找不到控制器1');
$jms=new $control($conf['db']['dsn'], $conf['db']['user'], $conf['db']['password']);
$jms->debugLevel=$conf['debug']['level'];

if(!method_exists($jms, $action)) notfound('方法不存在');
   
$reflection=new ReflectionMethod($jms, $action);

if($reflection->isStatic()) notfound('不允许调用Static修饰的方法');
if(!$reflection->isFinal()) notfound('只能调用final修饰的方法');

$jms->controller=$control;

$jms->action=$action;

$jms->charset=$conf['db']['charset'];
$jms->cacheDir=$conf['cache']['dir'];
$jms->setCacheDir($conf['cache']['dir']);
$jms->actionTemplate=$conf['action']['template'];
$jms->prename=$conf['db']['prename'];
$jms->title=$conf['web']['title'];
if(method_exists($jms, 'getSystemSettings')) $jms->getSystemSettings();

if($jms->settings['switchWeb']=='0'){

	$jms->display('close-service.php');
	exit;
}

if(isset($page)) $jms->page=$page;
 
if ($q = $_SERVER['QUERY_STRING']) {
	if (!isset($_GET['s'])) {
		$para = array_merge($para, explode('/', $q));
	}
}
if($para==null) $para=array();

//2019-04-09修改
if (!function_exists('getallheaders'))
{
    function getallheaders()
    {
       foreach ($_SERVER as $name => $value)
       {
           if (substr($name, 0, 5) == 'HTTP_')
           {
               $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
           }
       }
       return $headers;
    }
}
$jms->headers=getallheaders();





if(isset($jms->headers['x-call'])){
   
	// 函数调用
	header('content-Type: application/json');
	try{
		ob_start();
		echo json_encode($reflection->invokeArgs($jms, $_POST));
		ob_flush();
	}catch(Exception $e){
		$msg = trim($e->getMessage());
		if ($msg === '' || preg_match('/^0+$/', $msg) || preg_match('/^(00000|success|ok|error)$/i', $msg)) {
			$msg = '登录失败，请稍后重试';
		}
		$jms->error($msg, true);
	}
}elseif(isset($jms->headers['x-form-call'])){

	// 表单调用
	$accept=strpos($jms->headers['Accept'], 'application/json')===0;
	if($accept) header('content-Type: application/json');
	try{
		ob_start();
		echo json_encode($reflection->invokeArgs($jms, $_POST));
		ob_flush();
	}catch(Exception $e){
		$msg = trim($e->getMessage());
		if ($msg === '' || preg_match('/^0+$/', $msg) || preg_match('/^(00000|success|ok|error)$/i', $msg)) {
			$msg = '登录失败，请稍后重试';
		}
		$jms->error($msg, true);
	}
}elseif(!empty($jms->headers['Accept']) && strpos($jms->headers['Accept'], 'application/json')!==false){
	// AJAX调用（Accept 含 application/json 即可，避免部分客户端首段非 JSON 子类型）
	header('content-Type: application/json; charset=utf-8');
	$jsonFlags = defined('JSON_UNESCAPED_UNICODE') ? JSON_UNESCAPED_UNICODE : 0;
	if (defined('JSON_INVALID_UTF8_SUBSTITUTE')) {
		$jsonFlags |= JSON_INVALID_UTF8_SUBSTITUTE;
	}
	try {
		ob_start();
		$p = call_user_func_array(array($jms, $action), $para);
		$jsonBuffer = ob_get_clean();
		if ($jsonBuffer !== '') {
			echo $jsonBuffer;
		} elseif ($p !== null) {
			jms_emit_json_payload($p, $jsonFlags);
		}
	} catch (Exception $e) {
		jms_emit_json_payload(array(
			'ok' => false,
			'ts' => time(),
			'error' => $e->getMessage(),
			'source_note' => '接口异常，已返回占位结构。',
			'items' => array(),
			'stale' => false,
			'table_rows' => array(),
		), $jsonFlags);
	}
}else{

	// 普通请求
	header('content-Type: text/html;charset=utf-8');
	call_user_func_array(array($jms, $action), $para);
}
$jms=null;