<?php
//后台基础控制器
class baseController extends Controller {

    public  $common;
    public  $smarty;
    public  $templates;
    public  $appkey;
    public  $signstate;
    public  $tokentime;
    public  $tableModel;
    public  $logM;

    //构造方法
    public function __construct(){
        $this->appkey = $GLOBALS['config_api']['appkey'];
        $this->signstate = $GLOBALS['config_api']['signstate'];
        $this->tokentime = $GLOBALS['config_api']['tokentime'];
        $this->common = new Common();
        $this->tableModel = new tableModel();

        //安全验证
        $ignore = [
            //不需验证的接口
            "/api/index/getToken",
            "/api/index/getNewToken",
            "/api/Events/onMessageAction",
            "/api/user/breakNotice",
            "/api/user/getRoomInfo",    //获取直播间信息
        ];
        $url = getController();
        if(!in_array($url,$ignore)){
            $this->apisafefilter();
        }

    }

    /**
     * 获取token
     * @date: 2020-4-2 11:36:27
     * @author: 军师
     * @param: appkey
     * @return: token
     */
    public function getTokenAction(){
        $request = Request::unsetRoute()->all();
        if (empty($request["appkey"]) || $request["appkey"] != $this->appkey){
            returnSuccess([], getcodestr(2117),2117);
        }
        $time = time() + $this->tokentime;
        $data["appkey"] = $request["appkey"];
        $data["time"] = $time;
        $token = $this->common->encryptByqingmiphp(serialize($data));
        returnSuccess($token, getcodestr(2111),2111);

    }

    /**
     * 登录后获取新token
     * @date: 2020-4-3 11:03:11
     * @author: 军师
     * @param: user_info
     * @return: token
    */
    public function getLoginToken($user_info = []){
        $time = time() + $this->tokentime;
        $data["appkey"] = $this->appkey;
        $data["time"] = $time;
        $data["user_info"] = $user_info;
        $token = $this->common->encryptByqingmiphp(serialize($data));
        returnSuccess($token, getcodestr(3013),3013);
    }

    /**
     * token过期后，用旧的token换新的token
     * @date: 2020-4-3 11:03:11
     * @author: 军师
     * @param: token
     * @return: token
    */
    public function getNewTokenAction(){
        $old_token = $this->common->Post("token");
        if (empty($old_token)){
            returnFail([],getcodestr(2118),2118);
        }
        $tokenArray = unserialize($this->common->decryptByqingmiphp($old_token));
        //验证appkey
        if (empty($tokenArray["appkey"]) || $tokenArray["appkey"] != $this->appkey){
            returnFail([],getcodestr(2119),2119);
        }
        $time = time() + $this->tokentime;
        $data["appkey"] = $this->appkey;
        $data["time"] = $time;
        if (!empty($tokenArray["user_info"])){
            $data["user_info"] = $tokenArray["user_info"];
        }
        $token = $this->common->encryptByqingmiphp(serialize($data));
        returnSuccess($token, getcodestr(2120),2120);
    }

    //获取code信息
    public function getcodestr($id) {
        return $GLOBALS['config_code'][$id];
    }

    /**
     * 接口安全过滤方法，处理token,sign
     * @date: 2019年1月28日 下午7:29:59
     * @author: 龚华尧
     * @param: variable
     * @return:
     */
    function apisafefilter() {
        //验证签名开始
        $token = GetHeader();
        $check_token_data = checktoken($token);
        if(!$check_token_data['status']){
            returnSuccess($check_token_data['status'], $check_token_data['msg'] ,$code = 2003);
        }
        //验证用户信息
        $this->checkLogin($token);
    }

    //验证用户信息
    public function checkLogin($token){
        //定义需要登录的路由
        $array = [

            //用户模块
            "/api/user/userFocus",              //关注、拉黑
            "/api/user/getUserFocus",           //获取我的关注列表
            "/api/user/getUserFans",            //获取我的粉丝列表
            "/api/user/userCertification",      //用户认证
            "/api/user/getUserBlacklist",       //获取我的黑名单列表
            "/api/user/bandUserPhone",          //绑定手机号
            "/api/user/getUserPush",            //修改消息推送
            "/api/api/helpCenter/feedback",     //意见反馈
            "/api/user/userLeavel",             //用户当前等级信息
            "/api/user/updateUserInfo",         //修改用户的基本信息
            "/api/user/getUserHistory",         //最近来访

            //直播模块
            "/api/live/getRTMPPush",            //获取RTMP推流地址
            "/api/live/getRTMPPlay",            //获取RTMP直播地址
            "/api/live/getHDLPlay",             //获取HDL直播地址
            "/api/live/getHLSPlay",             //获取HLS直播地址
            "/api/live/getCover",               //获取截图直播地址
            "/api/live/userOpenLive",           //开启直播
            "/api/live/finishLive",             //结束直播
            "/api/live/editOnLive",             //编辑直播信息
            "/api/live/setRoomManage",          //房间人员管理
            "/api/live/getPkLog",               //我的PK战绩

            //礼物模块
            "/api/gift/userSentGift",           //我的PK战绩

            //贵族模块
            "/api/vip/openingVip",              //开通贵族

            //短视频
            "/api/user/userCollection",         //收藏、分享
            "/api/user/userEvaluation",         //评价
            "/api/shortVideo/addVideoPlay",     //增加播放记录
            "/api/shortVideo/getUserRelease",   //获取用户动态或小视频列表
            "/api/shortVideo/getMusicType",     //获取音乐类型
            "/api/shortVideo/getMusicList",     //获取音乐列表
            "/api/shortVideo/getVideoSpanList", //获取视频标签
            "/api/shortVideo/getMusic",         //获取音乐信息
            "/api/shortVideo/uploadShortVideo", //发布

            //靓号
            "/api/beault/userBuyNumber",        //靓号购买

        ];

        //获取当前目录
        $url = getController();
        //判断当前目录是否属于登录目录
        if(in_array($url,$array)){
            //判断是否登录
            $token_array = unserialize($this->common->decryptByqingmiphp($token));
            if(empty($token_array["user_info"])){
                returnSuccess([], $this->getcodestr(3001) ,$code = 3001);
            }
        }
    }

    /**
     * 处理查询表名称，防止跨脚本攻击
     */
    protected function TablenameFilter($t) {
        //调用common类
        $commonClass=$this->common;
        if($t==""){
            returnSuccess(false, "t参数不能为空",$code=2006);
        }
        $table_arr = explode(',',$t);
        if(count($table_arr)==0||count($table_arr)==1)
        {
            //待处理的表名
            $t=$commonClass->SafeFilterStr($t);
            //die($t);
            //增加权限判断
            if(!$this->tableModel->isableapi($t)){
                returnSuccess(false, "数据表无权限查询1",$code=2005);
            }

        }else
        {
            $t="";
            for($i=0;$i<count($table_arr);$i++)
            {
                //增加权限判断
                if(!$this->tableModel->isableapi($table_arr[$i])){
                    returnSuccess(false, "数据表无权限查询2",$code=2005);
                }

                if($t=="")
                {
                    $t="sl_".$commonClass->SafeFilterStr($table_arr[$i]);
                }else
                {
                    $t= $t ." , ". "sl_".$commonClass->SafeFilterStr($table_arr[$i]);
                }

            }

        }

        return $t;

    }

    /**
     * 处理查询表的查询字段，自动生成查询sql
     */
    protected function FiledFilter($t) {
        //调用common类
        $commonClass=$this->common;
        if(strpos($t,",")=="")
        {
            $t=$commonClass->SafeFilterStr($t);
            $temp_model=new Model($t);
            return $temp_model->getSqlWhereStr();
        }

    }

    /**
     * 处理返回的列名称，用于多表查询
     */
    protected function LiemingchengFilter($liemingcheng) {
        //调用common类
        $commonClass=$this->common;
        if($liemingcheng=="")
            return "*";
        $liemingcheng_arr = explode(',',$liemingcheng);
        if(count($liemingcheng_arr)==0)
        {
            //待处理的列名称
            $liemingcheng=$commonClass->SafeFilterStr($liemingcheng);


        }else
        {
            $liemingcheng="";
            for($i=0;$i<count($liemingcheng_arr);$i++)
            {
                if($liemingcheng=="")
                {
                    $liemingcheng=$commonClass->SafeFilterStr($liemingcheng_arr[$i]);
                }else
                {
                    $liemingcheng= $liemingcheng." , ". $commonClass->SafeFilterStr($liemingcheng_arr[$i]);
                }

            }

        }

        return $liemingcheng;

    }

    /**
     * 返回条数
     */
    protected function NumberFilter($number) {
        //调用common类
        $commonClass=$this->common;
        if ($number=="" )
        {
            $number="0";
        }
        else if(!$commonClass->isNumber($number))
        {
            $number="0";
        }
        return  $number;
    }

    /**
     * 默认查询方式
     * 如果有多个用逗号分隔，“|”会替换成=号
     * 多个字使用逗号“，”分开
     * 如果是or，比如sqlvalue=biaoti|'姓名/shouji|‘15982851365’，使用“/”分隔
     */
    protected function SqlvalueFilter($sqlvalue) {
        //调用common类
        $commonClass=$this->common;
        $sqlvalue=str_replace("|"," = ",$sqlvalue);
        $sqlvalue=str_replace(","," and ",$sqlvalue);
        $sqlvalue=str_replace("/"," or ",$sqlvalue);
        $sqlvalue=str_replace("dh"," , ",$sqlvalue);//把逗号替换为，
        $sqlvalue=str_replace("{bdy}"," <> ",$sqlvalue);//替换不等于
        //处理模糊查询
        $sqlvalue=str_replace("{like}"," like ",$sqlvalue);
        $sqlvalue=str_replace("{bfb}","%",$sqlvalue);

        // dtime between '2017-08-27 00:00' and '2017-08-27 23:59'
        $sqlvalue=str_replace("{between}"," between ",$sqlvalue);
        $sqlvalue=str_replace("{and}"," and ",$sqlvalue);

        //验证字符合法性

        if($sqlvalue!="")
        {
            $sqlvalue=" (".$sqlvalue.") ";
        }
        return $sqlvalue;
    }

    /**
     * 自动拼接sql 语句
     */
    protected function getSql($t,$liemingcheng,$number,$page=0,$ordertype,$orderby,$sqlvalue) {
        //调用common类
        $commonClass=$this->common;

        $_sql="select ";
        if($sqlvalue=="")
        {
            $_sql=$_sql." ".$liemingcheng." from {$t} ";
        }else
        {
            $_sql=$_sql." ".$liemingcheng." from {$t} where {$sqlvalue}  ";
        }

        if($this->FiledFilter($t)!="")
        {
            if($sqlvalue=="")
            {
                $_sql=$_sql." where  ".$this->FiledFilter($t);
            }else
            {

                $_sql=$_sql." and  ".$this->FiledFilter($t);
            }
        }

        if($ordertype!="")
        {
            if($ordertype=="id")
            {
                $_sql=$_sql." order by ".$ordertype." ".$orderby ;
            }else if(strlen(strstr($t, ','))>0)
            {

                $_sql=$_sql." order by ".$ordertype." ".$orderby ;

            }else
            {
                $_sql=$_sql." order by ".$ordertype." ".$orderby ."  , id desc ";
            }
        }else
        {
            $_sql=$_sql." order by id desc ";
        }

        if($number!="0")
        {
            if($page<=1)
            {
                $a=0;
            }else
            {
                $a=$number * ($page-1);
            }

            $b=$number ;
            $_sql=$_sql . " limit  $a , $b ";
        }

        return $_sql;
    }

}
