<?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.需要登录验证的方法和控制器统一用$this->checkuserauth()验证，验证成功则返回用户数据
 */
namespace Uapp\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(
            //添加控制器和方法
            'Index'=>array('index','getvindex','get_category','format_cat_item','adv_info','get_vindex','nearby','get_fight_group'),
            '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','getconfig','sendsms','resetlocation'),
            'Cart'=>array('index','del_cart','add_cart','sub_cart','add_pro_goods','change_pro_goods'),
            'Goods'=>array('index','buy_nows','lists','get_cont','ticket','get_ecv','activity','goods_attr','goods_article','addcart','buy_now','goods_comment','get_collect','check_act','fx_cont','get_memberadds'),
            'Member'=>array('invite','member_invite','index','myorder_list','my_collect','del_collect','get_user','update_login_pwd','address_list','mymoney','integral','money_change_dec','mycoupon_list','get_order_group','mycoupon_cont','get_paypwd','saveuser','balance','my_sign','get_bestgoods_list','sign_log','sign_rule','to_sign','address','rechange','sub_recharge','myorder_info','distance','getmemberbank','add_bank','go_withdrawals','wd_way','go_c_withdrawals'),
            'Login'=>array('dologin','set_push_param','wxlogin','setshopid'),
            'Takeout'=>array('index','add_carts','cont','update_myshop','cont_tgercode'),
            'PromotSale'=>array('index'),
            'Coupon'=>array('index','countop_count','get_coupon_wx'),
            'Dp'=>array('index','add_dp'),
            'Order'=>array('continu_pay','continue_payhtml','cancel_order','confirm_order','continue_count_total','sub_continue_order','index','count_total','order_invoice','sub_invoice','sub_order','order_success'),
            'ExtensionMatter'=>array('posters','save_matter','save_xcx_matter'),
            'Activity'=>array('index','activity_list','promat_sale'),
            'Address'=>array('update_address','address_list','del_address','edit_address'),
            'LittleShop'=>array('pro_level','info','index','choice','my_goods_up','go_isshow','update_myshop','sub_shop','order_info','check_lshop'),
            'PromotAct'=>array('index','cont','seckill','seckill_cont'),
            'FightGroup'=>array('cont','group_join'),
            'Article'=>array('index','content','cate_article','news'),
            //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'),
            'Login'=>array('dologin')
        );
        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')) && $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']='签名不正确-------'.$method.$this->AC_ID.$timestamp.C('HANCHAO_KEY');
		  $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 checkuserauth(){
        $return['status'] = 3;
        $return['msg']='获取登录信息错误,请重新登录!';
        $paramdata=I('param.');
        $paramdata['uid']=intval($paramdata['uid']);
        // $paramdata['uid']=37;
        if(empty($paramdata['uid']) || empty($paramdata['token'])){
            $this->ajaxReturn($return);
        }
        $userinfo=idtoname($paramdata['uid'],'Member','*','id',false);  
        $appkeyarr=explode('.',$this->AppKey);
        $timestamp=$appkeyarr[1];
        if(SHA1($userinfo['password'].$timestamp)!=SHA1($paramdata['token'].$timestamp)){
            $this->ajaxReturn($return);
        }

        if(!isset($paramdata['HCshopid'])||$paramdata['HCshopid']==0){
            $result = D('Wxsmall/Login')->bind_shop(array('uid'=>$paramdata['uid'],'xpoint'=>$paramdata['xpoint'],'ypoint'=>$paramdata['ypoint']));
            if($result['status']==1){
                $userinfo['HCshop']['code'] = 'bind_shop_success';
                $userinfo['HCshop']['bind_shop_id'] = $result['data']['id'];
                $userinfo['HCshop']['send'] = $result['send'];
                $userinfo['HCshop']['location_n'] = $result['location_n'];
                return $userinfo;
            }else{
                $return['code'] = 'bind_shop_error';
                $return['msg'] = $result['msg'];
                echo(json_encode($return));exit;
            }
        }
        elseif($paramdata['HCshopid']>0&&$paramdata['HCtemp']!=1){//由于当前HCshopid是临时缓存，需重新定位匹配门店
            $return['code'] = 'bind_shop_error';
            $return['msg']="登录信息失效，请重新登录";
            echo(json_encode($return));exit;
        }
        return $userinfo;
    }
    public function checkrootauth(){
        $return['status'] = 3;
        $return['msg']='获取登录信息错误,请重新登录!';
        $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);  
        if($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();
    }

}
?>