<?php
if(!defined("ROOT_PATH")){
	define("ROOT_PATH",  str_replace("\\", "/", dirname(dirname(__FILE__)))."/");
}
require("function/fun_error.php");
define("SKYVERSION",2.1);
date_default_timezone_set('PRC');  //设置默认时区
if(!defined("LANG")){
	define("LANG",'chinese');	
}

require("function/function.php");//函数库
if(defined("REWRITE_TYPE")  && REWRITE_TYPE=='pathinfo'){
	url_get($_SERVER['REQUEST_URI']);
}
if(is_mobile() or get('iswap') or WAP_DOMAIN==$_SERVER['HTTP_HOST']){
	define("ISWAP",1);
}else{
	define("ISWAP",0);
}
define("B_TIME",microtime(true));//页面开始时间
$_ENV['query_time']=0;//查询时间
/*对非法变量进行转换*/
if (!get_magic_quotes_gpc())
{
    if (!empty($_GET))
    {
        $_GET  = addslashes_deep($_GET);
    }
    if (!empty($_POST))
    {
        $_POST = addslashes_deep($_POST);
    }

    $_COOKIE   = addslashes_deep($_COOKIE);
    $_REQUEST  = addslashes_deep($_REQUEST);
}

//wap模板
define("S_WAP_TEMPLATE_DIR",$wap_template_dir?$wap_template_dir:ROOT_PATH . "themes/wap");
define("S_TEMPLATE_DIR",$template_dir?$template_dir:ROOT_PATH . "themes/index");
define("S_CACHE_DIR",$cache_dir?$cache_dir:ROOT_PATH.'temp/caches');
define("S_HTML_DIR",$html_dir?$html_dir:ROOT_PATH."temp/html");
define("S_COMPILE_DIR",$compile_dir?$compile_dir:ROOT_PATH."temp/compiled");
define("S_REWRITE_ON",$rewrite_on);
$m=isset($_GET['m'])?htmlspecialchars($_GET['m']):"index";
$m=str_replace(array("/","\\"),"",$m);
if(!file_exists(CONTROL_DIR."/$m.ctrl.php"))
{
	$_GET['m']=$m="index";
}

require_once(CONTROL_DIR."/$m.ctrl.php");

$classname = $m.'Control';

$control = new $classname();

if(ISWAP){
	$control->smarty->template_dir   =S_WAP_TEMPLATE_DIR;
}else{
	$control->smarty->template_dir   =S_TEMPLATE_DIR;
}
$control->smarty->cache_dir=S_CACHE_DIR;
$control->smarty->html_dir=S_HTML_DIR;
$control->smarty->compile_dir=S_COMPILE_DIR;
$control->smarty->rewrite_on=S_REWRITE_ON;
$control->smarty->rewriterule=$rewriterule;
if(defined("TESTMODEL") && TESTMODEL==1){
	$control->smarty->direct_output= false;
}else{
	$control->smarty->direct_output= false;
}

$control->smarty->caching=$smarty_caching;
$control->smarty->cache_lifetime=$smarty_cache_lifetime;
$control->smarty->skymvc=$control;
$control->db->skymvc=$control;
$a=get_post('a');
if(empty($a)){
	$_GET['a']=$_POST['a']='default';
}
$method=method_exists($control,'on'.$_GET['a'])? 'on'.$_GET['a']:"onDefault";

$control->$method();


class skymvc
{
	public $db,$smarty,$cache,$config_data=array(),$lang=array(),$rewriterule=array();
	public $version='2.0';
	public $skysqlrun="";//记录数据库执行的总数
	public $skysqlnum=0;
	function __construct($config=array())
	{
		$this->initLang();
		$this->initmysql();
		
		$this->initsession();
		$this->initsmarty();
		$this->smarty->assign("lang",$this->lang);
		$this->initCache();
		$this->db->setCache();
		$this->userinit_model();
		
		if(defined("HOOK_AUTO") && HOOK_AUTO){
			!isset($config['hook']) && $this->hook_auto();
		}
		$this->userinit();
	}
	/*用户自定义初始化*/
	public function userinit(){
		if(function_exists("userinit"))
		{
			userinit($this);		
		}
	}
	/*用户自定义初始化model*/
	public function userinit_model(){
		if(function_exists("userinit_model")){
			userinit_model($this);
		}
	}
	
	
	//初始化语言包
	public function initLang(){
		if(file_exists(ROOT_PATH."lang/".LANG)){
			$dir=ROOT_PATH."lang/".LANG;
			$d=opendir($dir);
			while(false !==($f=readdir($d))){				
				if($f!="." && $f!=".." ){
					if(strtolower(trim(substr(strrchr($f, '.'), 1)))=="php"){
						@include_once($dir."/".$f);
					}
				}
			}
			closedir($d);
			$this->lang=$lang;
		}
		//加载模块语言包
		
	}
	//初始化session
	public function initsession()
	{
		if(defined("SESSIONDB") )
		{
			if(SESSIONDB)
			{
				require_once("class/cls_session.php");
				$session= new session($this->db,60);
			}else
			{
				session_start();
			}
		}else
		{
			session_start();
		}
		
	}
	//初始化版本
	public function version()
	{
		$this->version;
	}
	
	 
	
	public function initmysql()
	{
		require_once("class/cls_mysql.php");//引入数据库文件
		$this->db=$this->loadMysql($_ENV['database']);
		$this->db->base=$this;		
		@require_once("class/cls_model.php");
		@require_once("class/cls_model_more.php");
	}
	
	public function loadMysql($config){
		$db=new mysql();
		$db->charset=MYSQL_CHARSET;
		$db->dbconfig=$config; 
		$db->connect();
		return $db;
	}
	
	public function initsmarty()
	{
		if(defined("ISSAE") && ISSAE==1){
			require_once("class/cls_smarty_sae.php");//引入模板文件
		}else{
			require_once("class/cls_smarty.php");//引入模板文件
		}
		$this->smarty=new Smarty();
		if(ISWAP){
			$this->smarty->template_dir   =S_WAP_TEMPLATE_DIR;
		}else{
			$this->smarty->template_dir   =S_TEMPLATE_DIR;
		}
		$this->smarty->cache_dir=S_CACHE_DIR;
		$this->smarty->html_dir=S_HTML_DIR;
		$this->smarty->compile_dir=S_COMPILE_DIR;
		$this->smarty->rewrite_on=S_REWRITE_ON;
		$this->smarty->rewriterule=$this->rewriterule;
		$this->smarty->skymvc=$this;
		if(defined("REWRITE_ON"))
		{
			if(REWRITE_ON)
			{
				$this->smarty->rewrite=true;
			}
		}
	}
 	
	public function initCache(){
		require_once("class/cls_cache.php");
		$this->cache=new cache();
		$this->loadconfig("cache");
		$config=$this->config_data['cache'];
		$this->cache->cache_type=$config['cache_type'];
		$this->cache->cache_dir=ROOT_PATH.$config['cache_dir'];
		(isset($config['memcache']) && !empty($config['memcache'])) && $this->cache->mem_connect($config['memcache']['host'],$config['memcache']['port']);
		(isset($config['mysql']) && !empty($config['mysql'])) && $this->cache->mysql($config['mysql']);
		
	}
	
	public function assignlist($table,$pagesize=10,$w="",$ord='',$url='')
	{
		$pagesize=$pagesize;
		$page=max(1,intval($_GET['page']));
		$start=($page-1)*$pagesize;
		$rscount=true;
		$list=$this->db->select($table,array("where"=>$w,"order"=>$ord,"start"=>$start,"limit"=>$pagesize),$rscount); 
		$pagelist=$this->multipage($rscount,$pagesize,$page,$url);
		$this->smarty->assign("rscount",$rscount);
		$this->smarty->assign("list",$list);
		$this->smarty->assign("pagelist",$pagelist);
	}
	
	public function loadModuleModel($module,$model,$base= NULL){
		$base=$base?$base:$this;
		if(is_array($model)){
			foreach($model as $m){			
				require_once   ROOT_PATH."module/".$module."/source/model/{$m}.model.php";
				
				if(!isset($_ENV[$m.'Model'])){
					eval('$_ENV[$m.\'Model\'] =new '.$m.'Model($base);');
				}
				//controler  model调用
				$_model="{$m}Model";
				$base->$m=new $_model($base);				
			}
		}else{			
			require_once    ROOT_PATH."module/".$module."/source/model/$model.model.php";
			if(!isset($_ENV[$model.'Model']))
			{
				//全局调用
				eval('$_ENV[$model.\'Model\'] =new '.$model.'Model($base);');				
			}
			//controler  model调用
			$_model="{$model}Model";				
			$base->$model=new $_model($base);		
		}
	}
	
	/*相同APP_DIR的model载入*/
    public function loadModel($model,$base= NULL )
	{
		$base=$base?$base:$this;
		if(is_array($model)){
			foreach($model as $m){			
				require_once   MODEL_DIR."/{$m}.model.php";
				
				if(!isset($_ENV[$m.'Model'])){
					eval('$_ENV[$m.\'Model\'] =new '.$m.'Model($base);');
				}
				//controler  model调用
				$_model="{$m}Model";
				$base->$m=new $_model($base);				
			}
		}else{			
			require_once   MODEL_DIR."/$model.model.php";
			if(!isset($_ENV[$model.'Model']))
			{
				//全局调用
				eval('$_ENV[$model.\'Model\'] =new '.$model.'Model($base);');				
			}
			//controler  model调用
			$_model="{$model}Model";				
			$base->$model=new $_model($base);		
		}
	}
	 
	public function loadControl($ctrl,$dir=false,$base= NULL){
		$base=$base?$base:$this;
		$dir=$dir?$dir:CONTROL_DIR;
		if(file_exists($dir."/$ctrl.ctrl.php")){
			require_once($dir."/$ctrl.ctrl.php");
			$ctrl="{$ctrl}Control";
			$base->$ctrl=new $ctrl();
			$base->$ctrl->smarty=$this->smarty;
			if(!isset($_ENV[$ctrl]))
			{
				//全局调用
				$_ENV[$ctrl]=$base->$ctrl;			
			}
			
		}
	}
	
	public function loadModuleControl($module,$ctrl,$dir="index",$base= NULL){
		$base=$base?$base:$this;
		$dir=$dir?$dir:CONTROL_DIR;
		$file=ROOT_PATH."module/".$module."/source/$dir/$ctrl.ctrl.php";
		if(file_exists($file)){
			require_once($file);
			$ctrl="{$ctrl}Control";
			$base->$ctrl=new $ctrl();
			$base->$ctrl->smarty=$this->smarty;
			if(!isset($_ENV[$ctrl]))
			{
				//全局调用
				$_ENV[$ctrl]=$base->$ctrl;				
			}
		}
	}
	
	/*引入类*/
	public function loadClass($cls,$dir=false,$isnew=true)
	{
		$dir=$dir?$dir:"library";
		if(in_array($cls,array("cache","image","upload"))){
			if(defined("ISSAE") && ISSAE==1){
				include_once($dir."/cls_{$cls}_sae.php");//引入模板文件
			}else{
				@include_once("{$dir}/cls_{$cls}.php");
			}
		}else{
			@include_once("{$dir}/cls_{$cls}.php");
		}
		if($isnew==true){
			$this->$cls = new $cls();
		}
	}
	/*引入func*/
	public function loadfun($fun,$dir=false)
	{
		$dir=$dir?$dir:"function";
		@include_once("{$dir}/fun_{$fun}.php");
	}
	/*引入配置文件*/
	public function loadconfig($file,$base=NULL){
		if(file_exists(ROOT_PATH."config/{$file}.php")){
			@include(ROOT_PATH."config/{$file}.php");
			$base=$base?$base:$this;
			if(isset($config)){
				$base->config_data=$config;
			}
		}
	}
	/*获取配置信息*/
	public function config_item($k="",$base=NULL){
		$base=$base?$base:$this;
		if(empty($k)){
			return $base->config_data; 
		}else{
			if(is_array($k)){
				$ct=count($k);
				$d=isset($base->config_data[$k[0]])?$base->config_data[$k[0]]:false;
				if($d){
					for($i=1;$i<$ct;$i++){
						if(isset($d[$k[$i]])){
							$d=$d[$k[$i]];
						}else{
							return false;
						}
					}
					return $d;
				}else{
					return false;
				}
			}else{
				return isset($base->config_data[$k])?$base->config_data[$k]:false;
			}
		}
	}
	
	/*hook插件机制*/
	public function hook($param=array()){
		$m=get('m','h');
		$a=get('a','h');
		$m=$m?$m:"index";
		$a=$a?$a:"default";
		$this->loadconfig("hook");
		$hook=$this->config_item("hook");
		$data=$hook[$m."_".$a];
		  
		if($data){
			foreach($data as $k=>$v){
				if(file_exists(HOOK_DIR."/".$v[0].".hook.php")){
					require_once(HOOK_DIR."/".$v[0].".hook.php");
					$class=$v[0]."hook";
					$h=new $class(array("hook"=>1));
					$h->$v[1]($param);
				}
			}
		}
	}
	/*全局hook*/
	public function hook_auto(){
		$this->loadconfig("hook");
		$hook=$this->config_item("hook");
		$data=$hook['hook_auto'];
		if($data){
			foreach($data as $k=>$v){
				if(file_exists(HOOK_DIR."/".$v[0].".hook.php")){
					require_once(HOOK_DIR."/".$v[0].".hook.php");
					$class=$v[0]."hook";
					$h=new $class(array("hook"=>1));
					$h->$v[1]($param);
				}
			}
		}
	}
	
	/*分页函数*/
	function pagelist($rscount,$pagesize,$url,$num=0){
		if(!defined("ISWAP")){
			define("ISWAP",false);
		}
		if(!$num){
			$num=ISWAP?6:10;	
		}
		$url .= strpos($url, '?')!==false ? '&' : '?';
		$per_page=get_post('per_page','i');
		$page=ceil($per_page/$pagesize);
		$pagenum=ceil($rscount/$pagesize);
		if($pagenum<2) return false;
		$pagestart=0;
		//中间页面
		$middle=ceil(($num-2)/2);
		if($per_page>=$pagenum) $pageend=$page;
		$prevlot=$lastlot="";
		if(($per_page-$pagesize*$num/2)>0){
			$prevlot='<a href="'.R($url.'per_page='.min($per_page-$pagesize*$num/2,$rscount)).'">....</a>';
		}
		if($rscount-$per_page-$pagesize*$num/2>0){
			$lastlot='<a href="'.R($url.'per_page='.min($per_page+$pagesize*$num/2,$rscount)).'">....</a>';
		}
		$min=intval(max(0,($per_page-$pagesize*$middle))/$pagesize);
		$pagelist='<div class="pages">';
		if($per_page==0){
			$pagelist.='<strong>首页</strong>';
		}else{
			$pagelist.='<a href="'.R($url).'" class="first">首页</a>';
		}
		
		$pagelist.=$prevlot;
		$max=min($min+$num,$pagenum);
		if($max-$min<$num){
			$min=max(1,$max-$num);
		}
		for($i=$min;$i<$max;$i++){
			if($i==0) continue;
			if($i>=$pagenum-1) continue;
			if($i==$page){
				$pagelist.='<strong>'.$i.'</strong>';
			}else{
				$pagelist.='<a href="'.R($url.'per_page='.min($i*$pagesize,$rscount)).'">'.$i.'</a>';
			}
		}
		$pagelist.=$lastlot;
		if($per_page>=$rscount-$pagesize){ 
			$pagelist.='<strong>尾页</strong>';
		}else{
			$pagelist.='<a href="'.R($url.'per_page='.($pagenum-1)*$pagesize).'" class="last">尾页</a>';
		}
		$pagelist.='</div>';
		return $pagelist;
	}
	/*旧版分页 即将取消*/
	function multipage($num, $perpage, $curpage, $mpurl,$page=10) {
		$shownum = $showkbd = FALSE;
		$multipage = '';
		$mpurl .= strpos($mpurl, '?') ? '&' : '?';
		$page=10;
		if(!defined("ISWAP")){
			define("ISWAP",false);
		}
		if(ISWAP)
		{
			if($num>=$perpage*($curpage+1))
			{
				return "<div class='pages'> <a href='".R($mpurl."page=1")."'><strong>首页</strong></a>  <a href='".R("{$mpurl}page=".($curpage-1))."'><strong>上一页</strong></a> <a href='{$mpurl}page=".($curpage+1)."'><strong>下一页</strong></a></div>";
			}else
			{
				
				return false;
			}
		}
		$realpages = 1;
		if($num > $perpage) {
			$offset = 2;
	
			$realpages = @ceil($num / $perpage);
			$realpages=min(1000,$realpages);
			$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;
	
			if($page > $pages) {
				$from = 1;
				$to = $pages;
			} else {
				$from = $curpage - $offset;
				$to = $from + $page - 1;
				if($from < 1) {
					$to = $curpage + 1 - $from;
					$from = 1;
					if($to - $from < $page) {
						$to = $page;
					}
				} elseif($to > $pages) {
					$from = $pages - $page + 1;
					$to = $pages;
				}
			}
	
			$multipage = ($curpage > 1 && !$simple ? '<a href="'.R($mpurl.'page='.($curpage - 1)).'" class="prev" > 首页</a>' : '').
				($curpage - $offset > 1 && $pages > $page ? '<a href="'.R($mpurl.'page=1').'" class="first" >1 ...</a>' : '');
			for($i = $from; $i <= $to; $i++) {
				$multipage .= $i == $curpage ? '<strong>'.$i.'</strong>' :
				'<a href="'.R($mpurl.'page='.$i).'">'.$i.'</a>';
			}
	
			$multipage .= ($to < $pages ? '<a href="'.R($mpurl.'page='.$pages).'" class="last" >... '.$realpages.'</a>' : '').
			($curpage < $pages && !$simple ? '<a href="'.R($mpurl.'page='.($curpage + 1)).'" class="next" >下一页</a>' : '');
	
			$multipage = $multipage ? '<div class="pages">'.($shownum && !$simple ? '<em>&nbsp;'.$num.'&nbsp;</em>' : '').$multipage.'</div>' : '';
		}
		$maxpage = $realpages;
		return $multipage;
	}
	//信息提示跳转
	public function gomsg($str='',$url='',$tpl='')	
	{	
	 	if(!$str){
			$this->gourl($url);
		}else{
			 
			$this->smarty->assign("message",$str);
			$this->smarty->assign("url",$url?$url:$_SERVER['HTTP_REFERER']);
			if($tpl){
				$this->smarty->template_dir=$tpl;
			}
			$this->smarty->display("gomsg.html");
			exit;
		}
		
	}
	
	/*
	地址直接跳转
	*/
	public function gourl($url=''){
		if(empty($url))
		{
			echo "<script>location.href='".$_SERVER['HTTP_REFERER']."';</script>";
		}else
		{	
			echo "<script>location.href='".$url."';</script>";
		}
		exit();
	}
	
	/*MD5加密*/	
	public function umd5($string){
		return md5(md5(md5($string)));
	}
	
	
	/*验证权限*/
	function checkpermission($permission,$m='',$a=''){
		$m=strtolower($m?$m:get('m','h'));
		$a=strtolower($a?$a:get('a','h'));
		$a=$a?$a:"default";
		if(!isset($permission[$m])) return false;
		$p=$permission[$m];
		$arr=array();
		if($p){
			foreach($p as $v){
				$arr=array_merge($arr,explode(",",$v)); 
			}
		}
		if(!in_array($a,$arr)){
				return false;
		}
		return true;	
	}
	
	
	
}
