<?php
// +----------------------------------------------------------------------
// | Sunnyi 多语商城建站系统 (Build on ThinkPHP)
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://www.sunnyi.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 商易网络(admin@sunnyi.cn)
// +----------------------------------------------------------------------

//基础action
class SunnyiAction extends Action {
	
	public function __construct(){	
		$this->checkInstall();
		parent::__construct();	
		//开始重新处理语言环境  为防止COOKIE丢失，导致多语言无法访问。 将语言存于Session中		
			        $langSet = sunnyiC('DEFAULT_LANG'); //读取默认语言			        
		            if(isset($_REQUEST[C('VAR_LANGUAGE')])){// 检测浏览器支持语言			            	
			                $langItem = D("LangConf")->where("id=".intval($_REQUEST[C('VAR_LANGUAGE')]))->find(); 
							if($langItem)
							{
								$langSet = $langItem['lang_name'];
			                	Session::set("sunnyi_lang",$langSet);	
			                	//定义默认的货币
					        	$currency_item = M("Currency")->getById($langItem['currency']);
					        	Session::set('sunnyi_currency',$currency_item);								
							}			   	                
			            }elseif(Session::get("sunnyi_lang"))// 获取上次用户的选择
			                $langSet = Session::get("sunnyi_lang");
			            else{
			                Session::set("sunnyi_lang",$langSet);
			            }
			        
			        // 定义当前语言	
	 				$langItem = D("LangConf")->where("lang_name='".$langSet."'")->find();
			        if(!$langItem)
			        {
			        	$langItem = D("LangConf")->where("lang_name='".sunnyiC('DEFAULT_LANG')."'")->find();
			        	$langSet = $langItem['lang_name'];
			        	Session::set("sunnyi_lang",$langSet);	
			        }
			        
			        if($_REQUEST['currency'])
			        {
			        	//定义默认的货币
			        	$currency_item = M("Currency")->getById(intval($_REQUEST['currency']));
			        	if(!$currency_item)
			        	{
			        		$currency_item = M("Currency")->getById($langItem['currency']);
			        	}
			        	Session::set('sunnyi_currency',$currency_item);
			        }
			        if(!Session::get('sunnyi_currency'))
			        {
			        	//定义默认的货币
			        	$currency_item = M("Currency")->getById($langItem['currency']);
			        	Session::set('sunnyi_currency',$currency_item);
			        }
			        		        
			        define('FANWE_LANG_SET',strtolower($langSet));			       
			        define('FANWE_LANG_ID',$langItem['id']);
			        $this->assign('FANWE_LANG_ID',FANWE_LANG_ID);
			        $this->assign("TMPL_PATH",TMPL_PATH.$langItem['tmpl']."/");	 //输出当前语言的模板路径		        
			        // 加载框架语言包
			        if(is_file(THINK_PATH.'/Lang/'.$langSet.'.php'))
			            L(include THINK_PATH.'/Lang/'.$langSet.'.php');
			        // 读取项目公共语言包
			        if (is_file(LANG_PATH.$langSet.'/common.php'))
			            L(include LANG_PATH.$langSet.'/common.php');
			            
			        //读取支付语言包
					$files = Dir::getList(getcwd()."/app/Lang/".$langSet."/payment/");
					foreach($files as $file)
					{
						if($file!='.'&&$file!='..')
						{
							 L(include LANG_PATH.$langSet.'/payment/'.$file);
						}
					}
			        $group = '';
			        // 读取当前分组公共语言包
			        if (defined('GROUP_NAME')){
			            $group = GROUP_NAME.C('TMPL_FILE_DEPR');
			            if (is_file(LANG_PATH.$langSet.'/'.$group.'lang.php'))
			                L(include LANG_PATH.$langSet.'/'.$group.'lang.php');
			        }
			        // 读取当前模块语言包
			        if (is_file(LANG_PATH.$langSet.'/'.$group.strtolower(MODULE_NAME).'.php'))
			        L(include LANG_PATH.$langSet.'/'.$group.strtolower(MODULE_NAME).'.php');
		//处理end
		
		//输出可选的货币
		$this->assign("currency_list",M("Currency")->findAll());
		
		$this->assign("Sunnyi",C("FANWE_INFO"));  //输出系统信息	
		if(sunnyiC("SHOP_CLOSED"))
		{
			$this->display("Public:close");
			exit;
		}
		//开始输出相关的全局数据
		$this->initGlobal();	
		
		//输出用于POST提交的表单URL	
		if(sunnyiC("URL_ROUTE")>0)
		$this->assign("POST_URL",__APP__."/");
		else
		$this->assign("POST_URL",__APP__);
	}
	
	//输出全局数据
	private function initGlobal()
	{	
		//输出logo
		$this->assign("sunnyi_logo",sunnyiC("SHOP_LOGO"));
		$this->assign("sunnyi_url",sunnyiC("SHOP_URL"));
		
		$this->assign("module_name",MODULE_NAME);
		
		//输出所有语言环境
		$this->assign("langs",D("LangConf")->findAll());
		$this->assign("curr_lang",FANWE_LANG_SET);
		$this->assign("curr_lang_id",FANWE_LANG_ID);
		
		//输出头部菜单
		$this->assign("top_navs",$this->assignNav(1));
		
		//输出主菜单
		$this->assign("main_navs",$this->assignNav(2));
		
		//输出底部菜单
		$this->assign("foot_navs",$this->assignNav(3));
		
		$this->assign("time",gmtTime());// 输出当前时间戳	

		//输出商品分类树
		$this->assign("cate_tree",$this->assignCateTree(false));
		
		//输出帮助中心
		$this->assign("help_center",$this->assignHelp());
		
		//输出友情链接
		$this->assign("links",$this->assignLink());
		
		//输出是否开启库存
		$this->assign('use_stock',sunnyiC("USE_STOCK"));
		
		//输出登录情况
		if($_SESSION['user_id']>0)
			$this->assign("is_login",true);
		else
			$this->assign("is_login",false);
			
		//输出当前操作模块名称
		$this->assign("module_name",$this->getActionName());
		$this->assign("rec_id",intval($_REQUEST['id']));
		
		//初始化购物车
		$this->initCart();  //初始化购物车
		$this->assign("cart_info",D("Cart")->countSubTotal());	

		if(sunnyiC("MESSAGE_USER_ONLY")==1&&intval($_SESSION['user_id'])==0)
		{
			$this->assign("hide_msg_form",1);
		}
		else 
		{
			$this->assign("hide_msg_form",0);
		}
		
		//品牌的调用
		$this->assign("rec_brand_list",D("Brand")->getBrandList('',sunnyiC("BRAND_LIMIT"),'sort desc'));
		//销售排行
		$this->assign("top_sale",D("Goods")->getTopSale());
		
		//关键词
		$this->assign("hot_keywords",D("Keywords")->getTopKeywords());
		
		
		//每页高级搜索数据列表
		//输出分类列表
    	$cate_list = D("GoodsCate")->getGoodsCateList();
    	$cate_list = D("GoodsCate")->toFormatTree($cate_list,array('name_'.FANWE_LANG_ID));
    	$this->assign("cate_list",$cate_list);
    	
    	//输出品牌
    	$brand_list = D("Brand")->getBrandList();
    	$this->assign("brand_list",$brand_list);

		
    	//输出规格列表
    	$spec_list = D("GoodsSpec")->getSpecList();
    	$this->assign("spec_list",$spec_list);
    	
				
	}
	public  function getRealPath()
	{
		return getcwd();
	}		
	
	private function checkInstall()
	{
		if(!file_exists($this->getRealPath()."/Public/install.lock"))
		{
	        Dir::delDir($this->getRealPath()."/admin/Runtime/");        
	        Dir::delDir($this->getRealPath()."/app/Runtime/");	
	        Dir::delDir($this->getRealPath()."/install/Runtime/");
	        @mkdir($this->getRealPath()."/admin/Runtime/",0777);
	        @mkdir($this->getRealPath()."/app/Runtime/",0777);
	        @mkdir($this->getRealPath()."/install/Runtime/",0777);
			header('Location:'.__ROOT__.'/install.php');
			exit;
		}
	}
	
	public function verify()
	{
		$type	 =	 isset($_GET['type'])?$_GET['type']:'gif';
        import("@.ORG.Image");
        Image::buildImageVerify(4,1,$type);
	}

	/**
	 * 用于自动模板识别
	 */
	protected function display($templateFile='',$charset='',$contentType='text/html')
    {
    	if(sunnyiC('GZIP_ON'))
    		ob_start('ob_gzip');
    	$lang_item = D("LangConf")->where("lang_name='".FANWE_LANG_SET."'")->find();  //查询出当前语言环境值    	
    	$this->view->display($lang_item['tmpl']."@".$templateFile,$charset,$contentType);
    	if(sunnyiC('GZIP_ON'))
    		ob_end_flush();
    }

    /**
     * 以下用于输出页面模块的一些可供调用的函数
     * 
     */
    
    //输出格式化产品分类树
    protected  function assignCateTree($format = true, $pid)
    {
    	//输出全局产品分类列表
    	if($pid)
		$cate_tree = D("GoodsCate")->getGoodsCateList("status=1 and pid=".$pid,'sort desc');
		else 
		$cate_tree = D("GoodsCate")->getGoodsCateList("status=1",'sort desc');
		if($format)
			$disp_name = "name_".D("LangConf")->where("lang_name='".FANWE_LANG_SET."'")->getField("id");
		$cate_tree = D("GoodsCate")->toFormatTree($cate_tree,array($disp_name));
		//判断当前目录
		$cate_id = 0;
		if(strtolower($this->getActionName())=="goods")
		{
			if(strtolower($_REQUEST[C("VAR_ACTION")])=="index"||strtolower($_REQUEST[C("VAR_ACTION")])=="_index")
			{
				//商品分类列表
				$cate_id = intval($_REQUEST['id']);
			}
			if(strtolower($_REQUEST[C("VAR_ACTION")])=="show")
			{
				//商品展示页
				$goods_id = intval($_REQUEST['id']);
				$cate_id = D("Goods")->where("id=".$goods_id)->getField("cate_id");
			}
		}
		foreach($cate_tree as $k=>$v)
		{
			if($cate_id == $v['id'])
			{
				$cate_tree[$k]['act'] = 1;
			}
			else 
			{
				$cate_tree[$k]['act'] = 0;
			}
		}				
		return $cate_tree;
    }
    //输出菜单列表(type1头部2主菜单3底部)
    protected function assignNav($type=1)
    {
		$curr_module = $_REQUEST[C("VAR_MODULE")];
		$curr_action = $_REQUEST[C("VAR_ACTION")];
		$curr_id = intval($_REQUEST['id']);
      	$navs = D("Nav")->where("type=".$type." and status=1")->order("sort desc")->findAll();
    	//开始判断菜单的状态
    	foreach($navs as $k=>$v)
    	{
    		if($v['url']=='')
    		{
    			$navs[$k]['target'] = '';
    			if($v['rec_module']==""&&$v['rec_action']=="")
    			{
    				$navs[$k]['url'] = __ROOT__."/";
    			}
    			else 
    			{
	    			$arr  = array();
	    			if($v['rec_id']!=0)$arr = array('id'=>$v['rec_id']);
	    			//开始重写模块的定义
	    			if(sunnyiC("URL_ROUTE")==2)
	    			{
		    			if($v['rec_module']=="Goods")
		    			{
		    				if($v['rec_action']=="index")
		    				{
		    					if(intval($v['rec_id'])>0)
		    						$navs[$k]['url'] = U("cate/".$v['rec_id']);
		    					else 
		    						$navs[$k]['url'] = "cate".C("URL_HTML_SUFFIX");
		    				}
		    				elseif($v['rec_action']=="show")
		    				{
			    				$navs[$k]['url'] = U("goods/".$v['rec_id']);
		    				}
		    				else 
		    				{
		    					$navs[$k]['url'] = U($v['rec_module']."/".$v['rec_action'],$arr);
		    				}
		    			}
	    				elseif($v['rec_module']=="Article")
		    			{
		    				if($v['rec_action']=="index")
		    				{
		    					if(intval($v['rec_id'])>0)
		    						$navs[$k]['url'] = U("articlecate/".$v['rec_id']);
		    					else 
		    						$navs[$k]['url'] = "articlecate".C("URL_HTML_SUFFIX");
		    				}
		    				elseif($v['rec_action']=="show")
		    				{
			    				$navs[$k]['url'] = U("article/".$v['rec_id']);
		    				}
		    				else 
		    				{
		    					$navs[$k]['url'] = U($v['rec_module']."/".$v['rec_action'],$arr);
		    				}
		    			}
		    			else
		    			$navs[$k]['url'] = U($v['rec_module']."/".$v['rec_action'],$arr);
	    			}
	    			else 
	    			$navs[$k]['url'] = U($v['rec_module']."/".$v['rec_action'],$arr);
    			}
    		}
    		else 
    		{
    			$navs[$k]['target'] = '_blank';
    		}
    		if($v['rec_module']==$curr_module&&$v['rec_action']==$curr_action&&$v['rec_id']==$curr_id)
    		{
    			$navs[$k]['act'] = 1;
       		}
    		else 
    		{
    			$navs[$k]['act'] = 0;
    		}
    	}
    	return $navs;
    }
     
    //输出帮助中心
    protected function assignHelp($limit = 5)
    {
    	$condition['type'] = 2;  //分类条件为帮助类型
    	$condition['status'] = 1;
    	$help_cates = D("ArticleCate")->getArticleCateList($condition,4,'sort desc');
    	foreach($help_cates as $k=>$v)
    	{
    		$article_condition['status'] = 1;
    		$article_condition['type'] = 2;
    		$childIds = D("ArticleCate")->getChildIds($v['id']);
    		$childIds[] = $v['id'];
    		$article_condition['cate_id'] = array('in',$childIds);
    		$help_cates[$k]['list'] = D("Article")->getArticleList($article_condition,$limit,'sort desc');
    	}
    	return $help_cates;
    }
    
    //输出友情链接
    protected function assignLink($limit = 10)
    {
    	$list = D("Link")->where("status=1")->order('sort desc')->limit($limit)->findAll();
    	foreach($list as $k=>$v)
    	{
    		if($v['type']!=0)
    		$res['img'][] = $v;
    		else 
    		$res['txt'][]=$v;
    	}
    	return $res;
    }
    
    
    /**
     * 输出导航（SEO，页头等相关信息）
     *
     * @param array $data
     * 结构：$data = array(
     * 			'navs' =>  array(
     * 				array('name'=>'name','url'=>'url'),.....     * 						
     * 				),
     * 			'keyword'	=>	'...',
     * 			'content'	=>	'...'
     * )
     */
    protected function assignSeo($data)
    {
    	$current_lang = D("LangConf")->getById(FANWE_LANG_ID);
    	$shop_name = $current_lang['shop_name'];
    	$shop_keyword = $current_lang['seokeyword'];
    	$shop_description = $current_lang['seocontent'];
    	$shop_title = $current_lang['shop_title'];
    	
    	$shop_url = __APP__;
    	
    	$title_str = "";
    	$nav_str = "<a href='".$shop_url."'>".$shop_name."</a>"; 
    	foreach($data['navs'] as $k=>$item)
    	{
    		if(strtolower($this->getActionName())!="index")  //非前页标题添加导航
    		$title_str.= $data['navs'][count($data['navs'])-$k-1]['name']." - ";
    		$nav_str.= " - <a href='".$item['url']."'>".$item['name']."</a>";
    	}
    	$title_str.=$shop_title;
    	$rs['title'] = $title_str;
    	$rs['navs'] = $nav_str;
    	
    	if($data['keyword']!="")
    	$rs['keyword'] = $data['keyword'];
    	else 
    	$rs['keyword'] = $shop_keyword;
    	
    	if($data['content']!='')
    	$rs['content'] = $data['content'];
    	else 
    	$rs['content'] = $shop_description;
    	
    	$this->assign('site_info',$rs);
    }
    
    /**
     * 用于检测当前用户IP的可操作性,time_span为验证的时间间隔 秒
     *
     * @param string $ip_str  IP地址
     * @param string $module  操作的模块     * 
     * @param integer $time_span 间隔
     * @param integer $id   操作的数据
     * 
     * @return boolean
     */
    public function check_ip_operation($ip_str,$module,$time_span=0,$id=0)
    {
    	if(empty($_SESSION[$module."_".$id."_ip"]))
    	{
    		$check['ip']	=	 get_client_ip();
    		$check['time']	=	gmtTime();
    		Session::set($module."_".$id."_ip",$check);
    		
    		return true;  //不存在session时验证通过
    	}
    	else 
    	{   
    		$check['ip']	=	 get_client_ip();
    		$check['time']	=	gmtTime();    
    		$origin	=	$_SESSION[$module."_".$id."_ip"];
    		
    		if($check['ip']==$origin['ip'])
    		{
    			if($check['time'] - $origin['time'] < $time_span)
    			{
    				return false;
    			}
    			else 
    			{
    				Session::set($module."_".$id."_ip",$check);
    				return true;  //不存在session时验证通过    				
    			}
    		}
    		else 
    		{
    			Session::set($module."_".$id."_ip",$check);
    			return true;  //不存在session时验证通过
    		}
    	}
    }
    
    //用于获取相应模块下的留言列表及回复
    protected function getMessageList()
    {
    	$rec_module = $this->getActionName();
    	$rec_id	=	intval($_REQUEST['id']);
    }
    
    public function _empty()
    {
    	$this->error(L("EMPTY_ACTION"));
    }
    
    //处理购物车  暂时实现商品购买
    protected function initCart()
    {
    	$max_time = sunnyiC('CART_MAX_TIME');  //购物车保留的最长时效
    	$now = gmtTime();
    	D("Cart")->where($now." - update_time > ".$max_time)->delete();  //删除超时的购物车商品
    	M("CartCard")->where($now." - update_time > ".$max_time)->delete();
    	
    	$session_id = Session::id();
    	$user_id = intval($_SESSION['user_id']);
    	
    	//删除非会员状态下时的积分商品与赠品
    	if($user_id==0)
    	{
    		D("Cart")->where("session_id='".$session_id."' and (rec_module='PromoteGoods' or rec_module='ScoreGoods')")->delete();
    		M("CartCard")->where("session_id='".$session_id."'")->delete();
    	}
    	
    	//清空购物车时清空促销券
    	if(D("Cart")->where("session_id='".$session_id."'")->count()==0)
    	{
    		M("CartCard")->where("session_id='".$session_id."'")->delete();
    	}    	
    	
    	if(sunnyiC("USER_CART"))  //仅会员购买时删除非会员的购物车商品
    	{
    		D("Cart")->where("user_id=0")->delete();
    	}    	
    	D("Cart")->where("session_id='".$session_id."'")->setField("user_id",$user_id);  //将所有当前session的列表改变会员状态    	
    	D("Cart")->countCart();  //计算非促销的购物车数据
    	D("Cart")->countPromoteCart();  //计算促销购物车数据   	
    }
    

    
    public function getHotItemDetail()
    {
    	$goods_id = intval($_REQUEST['id']);    	
    	$goods_info = D("Goods")->getGoodsItem("id=".$goods_id);    	
    	$goods_info['name'] = $goods_info['name_'.FANWE_LANG_ID];  
    	$goods_info['brief'] = $goods_info['brief_'.FANWE_LANG_ID];    	
    	echo json_encode($goods_info);exit;
    }
    
    protected function success($message,$ajax=false)
    {
    	//输出当前页seo内容
    	$navs = array('name'=>$message,'url'=>__ROOT__);
    	$data = array(
    		'navs' => array(
    			$navs,
    		),    		
    		'keyword'=>	'',
    		'content'=>	'',
    	);
    	$this->assignSeo($data); 
    	$this->assign("waitSecond",3);
    	parent::success($message,$ajax);
    }
    
    protected function error($message,$ajax=false)
    {
    	//输出当前页seo内容
    	$navs = array('name'=>$message,'url'=>__ROOT__);
    	$data = array(
    		'navs' => array(
    			$navs,
    		),    		
    		'keyword'=>	'',
    		'content'=>	'',
    	);
    	$this->assignSeo($data); 
    	parent::error($message,$ajax);
    }
    
	
}
?>