<?php
/** App base控制器
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaoq <xiaoq@570035208.com>
 */

/** 注意事项
 * 1.注意客户端与服务端控制器与方法名称的大小写（控制器首字母大写）记录在method_array方法中
 * 2.返回值统一放在$return['data']中,报错信息放在$return['msg']中
 * 3.返回值$return['status']中 1代表正常数据 2代表获取的数据为空 3代表登录信息错误 4代表没有权限
 * 4.需要登录验证的方法和控制器统一用$this->checkuserauth()验证，验证成功则返回用户数据
 */
namespace Pad\Controller;
use Common\Controller\HanchaoController;
class BaseController extends HanchaoController {
	public function _initialize(){
		parent::_initialize ();
		$this->pagesize = C('WEB_DEFAULT_PAGE') > 0 ? C('WEB_DEFAULT_PAGE') :10;//网站默认分页
        if(I('pagesize'))$this->pagesize=I('pagesize');
        $this->notallowmod = array('admin','config','oauth_member');//不允许操作的模块
        $this->ControllerName = CONTROLLER_NAME; //控制器			
		$this->ActionName = ACTION_NAME; //方法
        $this->AC_ID=$_SERVER['HTTP_X_APICLOUD_APPID']; 
		$this->AppKey=$_SERVER['HTTP_X_APICLOUD_APPKEY'];
        $this->check();
    }
    //
    //允许执行的控制器与方法
    private function method_array($key=''){
        $method_array = array(
            //添加控制器和方法
            'InvoicingOrder'=>array('get_order_list','get_stock_list','get_order_info','get_freight_management','cancel_order','add_goods_list','search_goods_list','get_select_list','stocktaking_list','stocktaking_info','stocktaking_add_before','stocktaking_goods','stocktaking_add','get_suppliers','sub_order_stock','get_category','confirm_goods','bad_list','bad_info','bad_add','transfer_add_before','transfer_add','other_goods','get_print_info','bad_print_info','confirm_prepare_goods','warning','stock_confirm_order','get_allcategory','get_return_order','get_return_goods','add_order','get_shopmoney','save_pay_img','check_paysuccess'),
			'Member'=>array('member_list','member_infor','checkmobile','member_add','daogou_info','get_memberinfo','get_member','calculation','get_recharge','package_list','get_package','get_memberattr','get_memberattrinfo','add_member_attribute','save_labels',"add_label","get_memberattr_new",'member_bind','member_bind_add'),
			'Ajax'=>array('upload','shops','linkage','add_card','is_upd_card','particulars','add_coupon','list_coupon','update_coupon_data','update_card','create','share_url','save_wx','update_config_data','card_update','config_guan','wx_keyword','del_wx_keyword','url_navtype','wx_keyword_add','select_keyword','wx_keyword_upd','wx_menu_list','wx_menu_add','select_menu','wx_menu_upd','wx_menu_del','updatemenu','coupon_issue','coupon_if','logo'),
            'Cashier'=>array('index','member_discount','guadan','del_guadan','tidan','get_siteinfo','shop_list_arr','shops_change','member_infor','check_code','add_order','get_sales','get_order_list','get_order_info','order_manage','order_take','get_order_status','deliver_goods','statistics','get_message_list','get_message_count','exchange_print_info','return_goods','add_turnover','turn_over_list','turn_over_content','get_print_info','check_paysuccess','record_list','message_read','print_recharge_info','get_active','get_peisong','count_shipping_fee','tui_goods','submit_service','return_goods_print','xstui_goods'),
            'CashierSet'=>array('moling_before','update_moling','tone_before','update_tone','cash_before','update_cash','tpl_before','update_tpl','set_shop_prints','update_scale_sn','set_jizhong_config'),
            'ShopLog'=>array('bill','money_list'),
			'Shops'=>array('index','get_pid','save_shops','shops_list','check','shops_change','get_root_data','get_chinaums_img'),//门店
			'Goods'=>array('goods_list','get_cate','goods_info','save_goods','delete_goods','category_lists','unit_lists','delete_category','category_info','save_category','attr_lists','attr_info','save_attr','save_attr_options','set_all_options','package_add','package_list','get_package','package_send','get_member_package','get_package_service','sub_hx_package','select_hx','service_hx','select_thm','check_goods','select_gift','check_gift','service_jilu','thm_jilu','gift_jilu','service_jilu_cont','thm_jilu_cont','gift_jilu_cont'),//商品
			'UCenter'=>array('index','set_password'),
            'Statistics'=>array('index','member_trend','member_buy_rate','consume','order','goods_sales','recharge'),
            'ThreeOrder'=>array('get_order_list','get_order_info','order_manage','get_order_status','get_print_info','quickedit','save_quickedit'),
			'GiftCard'=>array('gift_card_info','add_gift_card_order','get_sale_list','get_order_info'),//礼品卡
			'ShopsRoleAuth'=>array('auth_login'),//授权登录
            'Face'=>array('member_customer_list','member_customer_info','change_membertype'),
            'CallLog'=>array('call_list','call_info'),
            //end
        );
        //不需要登录验证的控制器与方法
        $this->notchecklogin = array(
            'Ajax'=>array('upload','shops','linkage','add_card','is_upd_card','particulars','add_coupon','list_coupon','update_coupon_data','update_card','create','share_url','save_wx','update_config_data','card_update','config_guan','wx_keyword','del_wx_keyword','url_navtype','wx_keyword_add','select_keyword','wx_keyword_upd','wx_menu_list','wx_menu_add','select_menu','wx_menu_upd','wx_menu_del','updatemenu','coupon_issue','coupon_if','logo')
        );
        return empty($key)?$method_array:$method_array[$key];
    }
    //检测请求是否合法
	private function check(){
	    $return['status']=3;
        //请求日志
        //file_put_contents('applog/'.$ControllerName.'/'.$ActionName.'-'.date("YmdHis").'.txt',var_export($_REQUEST,true));
		if(!in_array( $this->ControllerName, array_keys($this->method_array()))){		  
            $return['msg']='请求的控制器('. $this->ControllerName.')不存在';
            $this->ajaxReturn($return);
		}
        if(!in_array( $this->ActionName, $this->method_array($this->ControllerName))){		  
            $return['msg']='请求的方法('.$this->ActionName.')不存在';
            $this->ajaxReturn($return);
		}
        return true;
        if(empty($this->AC_ID)){
            $return['msg']='APPID不能为空';
		    $this->ajaxReturn($return);
        }
        if(!in_array($this->AC_ID,C('AC_ID'))){
            $return['msg']='APPID不匹配';
		    $this->ajaxReturn($return);
        }
        if(empty($this->AppKey)){
            $return['msg']='APPKEY不能为空';
		    $this->ajaxReturn($return);
        }
        $appkeyarr=explode('.',$this->AppKey);
        $sign=$appkeyarr[0];//签名
        $timestamp=$appkeyarr[1];
        $method = 'c='.$this->ControllerName.'&a='.$this->ActionName;
		$my_sign=SHA1($method.$this->AC_ID.$timestamp.C('HANCHAO_KEY'));	
		if($my_sign!=$sign){
		  $return['msg']='签名不正确';
		  $this->ajaxReturn($return);
        }
        return true;
        //验证站点信息是否合法
        $notchecksite = array('Login');//不需要站点验证的控制器
        if(!in_array($this->ControllerName,$notchecksite)){
            $map = array();
            $map['status'] = 1;
            $map['start_time'] = array('lt',NOW_TIME);
            $map['end_time'] = array('gt',NOW_TIME);
            $count = M('SiteInfo')->where($map)->count();
            if($count<=0){
                $return['msg']='站点被禁用或者已过期';
                $this->ajaxReturn($return);
            }
        }
        //验证登录信息是否合法
        $notcheckloginarr = array();
        foreach($this->notchecklogin as $k=>$v){
            foreach($v as $val){$notcheckloginarr[] = $k.$val;}
        }
        if(!in_array($this->ControllerName.$this->ActionName,$notcheckloginarr)){
            $paramdata=I('param.');
            if($paramdata['is_root']==1){
                $this->checkrootauth();
            }else{
                $this->checkshopauth();
            }
        }
        return true;	
	}
    public function checkshopauth(){
        $return=array('status'=>3,'msg'=>'获取登录信息错误,请重新登录!(001)');
        $paramdata=I('param.');
        $paramdata['sid']=intval($paramdata['sid']);

        if(empty($paramdata['sid']) || empty($paramdata['token'])){
		    $this->ajaxReturn($return);
        }
        $accountinfo=idtoname($paramdata['sid'],'ShopsAccount','*','id',false);
        $appkeyarr=explode('.',$this->AppKey);
        $timestamp=$appkeyarr[1];
        if(empty($accountinfo['password']) || $accountinfo['password']!=$paramdata['token']){
		    $this->ajaxReturn($return);
        }
        return $accountinfo;
    }
    public function checkrootauth(){
        $return=array('status'=>3,'msg'=>'获取登录信息错误,请重新登录!(002)');
        $paramdata=I('param.');
        $paramdata['root_id']=intval($paramdata['root_id']);
        if(empty($paramdata['root_id']) || empty($paramdata['root_token'])){
		    $this->ajaxReturn($return);
        }
        $admininfo=idtoname($paramdata['root_id'],'Admin','*','id',false);  
        $appkeyarr=explode('.',$this->AppKey);
        $timestamp=$appkeyarr[1];
        $return['msg']=$admininfo;
        if(empty($admininfo['password']) || $admininfo['password']!=$paramdata['root_token']){
		    $this->ajaxReturn($return);
        }
        return $admininfo;
    }
    public function format_content($content){
        if(empty($content))return false;
        $content=h($content);
        $baseurl='http://'.$_SERVER['HTTP_HOST'].__ROOT__;
        $contentarr = $content;
        preg_match_all("/<img(.*)(src=\"[^\"]+\")[^>]+>/isU", $contentarr, $arr);
        $images = array();
        foreach($arr[0] as $key=>$val){
            $match = array();
            preg_match('/<img.*?src="(.*?)".*?>/is',$val,$match);
            if(str_exists($match[1],'http')||str_exists($match[1],'https')){
                $images['images']['images'.$key] = $match[1];
            }else{
                $images['images']['images'.$key] = $baseurl.$match[1];
            }
            
            $contentarr = str_replace($val,'<img v-lazy="this.xqimages.images'.$key.'">',$contentarr);
        }
        $images['content'] = $contentarr;
        return $images;
    }
    /****/
    function StrToparamArray($str=''){
        $str=html_entity_decode($str);
        if(is_string($str)&&!empty($str)){
            $data = array();
            $arr = explode('^',$str);
            foreach ($arr as $val) {
                if(empty($val))continue;
                $d = array();
                $d = explode('/=/',$val);
                if(is_string($d[1])){
                    $tobj = array();
                    $tarr = explode('@',$d[1]);
                    foreach ($tarr as $v) {
                        if(empty($v))continue;
                        $dt = explode('___',$v);
                        $tobj[$dt[0]] = $dt[1];
                    }
                    $data[$d[0]] = $tobj;
                }else{
                    $data[$d[0]] = $d[1];
                }
            }
            return $data;
        }
        return array();
    }
}
?>