<?php
require_once dirname(__DIR__) . '/Cloak/ReasonHelper.php';
require_once dirname(__DIR__) . '/Cloak/VisitorApiAudit.php';

/**
 * 访客上下文与 API 判定（类名保留历史拼写 visitorInfo）
 */
class visitorInfo
{
    /** @var string */
    public $v_ip;
    public $v_Browser;
    public $v_country;
    public $v_referer;
    public $v_Client;
    public $v_curPageURL;
    public $v_site_server;
    public $accept_language;
    public $visit_md5_code;
    public $costm_ip_score;
    public $check_key;
    public $check_country;
    public $check_result;
    public $v_reason;
    
    /**
     * 从请求/Session 填充访客字段
     *
     * @param string $costm_ip_score 活动 ID（COSTM_IP_SCORE）
     * @param string $check_key      API 密钥
     * @param string $check_country  国家过滤配置
     * @return void
     */
    public function get_visitor_Info($costm_ip_score = '', $check_key = '', $check_country = '')
    {
        $this->v_country = !empty($_SESSION['gcu_country']) ? (string) $_SESSION['gcu_country'] : '';
        $this->v_ip = $this->getIp();
        $this->v_Browser = $this->getBrowser();
        $this->v_referer = $this->getFromPage();
        $this->v_Client = $this->v_isMobile();
        $this->v_curPageURL = $this->curPageURL();
        $this->v_site_server = $this->get_site_server();
        $this->accept_language = $this->get_accept_language();

        $this->costm_ip_score = $costm_ip_score;
        $this->check_key = $check_key;
        $this->check_country = $check_country;

        if ($this->v_country !== '') {
            $_SESSION['gcu_country'] = $this->v_country;
        }
        $_SESSION["gcu_Client"] = $this->v_Client;
        $_SESSION["gcu_ip"] = $this->v_ip;
        $_SESSION["gcu_Browser"] = $this->v_Browser;
    }   
    
    /**
     * 调用远程 cloak API 判定
     *
     * @return array|null API 解码结果；前置条件不足时 null
     */
    public function send_visitor_Info_xyz()
    {
        if(!empty($_REQUEST["send"])&& $_REQUEST["send"] ==1)
        {
            print_r($jsonData); exit();
        }

        if(!empty($this->v_ip)) 
        {
            $return = $this -> cloak_check_curl();
            if (!is_array($return)) {
                $return = ['result' => false, 'reason' => 'API响应异常', 'country' => $this->v_country];
            }
            $this->check_result = !empty($return['result']) ? "true" : "false";
            if ($this->v_country === '' && !empty($return['country'])) {
                $this->v_country = (string) $return['country'];
                $_SESSION['gcu_country'] = $this->v_country;
            }
            $this->v_reason = cloak_api_reason($return, $this->check_result);
            return $return;
        }
        return null;
    }


    function cloak_check_curl()
    {
        $headers = browser_headers();
        //  $visit_domain = str_replace('www.', '', $_SERVER['HTTP_HOST']);     // 当前网站域名
        // $visit_domain = (is_https() ? "https://" : "http://"). $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $jsonData['id'] = $this->costm_ip_score;
        $jsonData['ip'] = $this->v_ip;
        $jsonData['domain'] = $this->v_curPageURL;
        $jsonData['country_code'] = $this->check_country;  //设置该参数后，将替换"广告策略》访问者地理位置>过滤"的设置，填写国家代码,多个用逗号分隔，如：US,GB,CA,AU,IE,NZ
        $jsonData['referer'] = get_SERVER_value('HTTP_REFERER');
        $jsonData['headers'] = json_encode($headers);
        VisitorApiAudit::recordByApiRequest($jsonData);
        $ch = curl_init('www.tiktokba.com/cloak/byApi');

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        curl_setopt($ch, CURLOPT_USERAGENT, get_SERVER_value('HTTP_USER_AGENT'));
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        curl_setopt($ch, CURLOPT_ENCODING, ""); //Enables compression
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-type: application/json"]);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["escloak-key: {$this->check_key}"]);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($jsonData));
        curl_setopt($ch, CURLOPT_HEADERFUNCTION, "forward_response_cookies"); //Forward response's cookies to visitor
        if ($_COOKIE) {//Forward visitor's cookie to our server
            curl_setopt($ch, CURLOPT_COOKIE, encode_visitor_cookies());
        }
        $return = curl_exec($ch);
        if ($return == false) {
            $curl_error = curl_error($ch);
            curl_close($ch);
            $errorPayload = ['result' => false, 'reason' => 'API请求失败:' . $curl_error, 'country' => ''];
            VisitorApiAudit::recordByApiResponse($errorPayload);
            return $errorPayload;
        }
        curl_close($ch);
        $decoded = json_decode($return, true);
        if (!is_array($decoded)) {
            $invalidPayload = ['result' => false, 'reason' => 'API响应失败，请检查API密钥以及广告策略 ID', 'country' => '', '_raw' => $return];
            VisitorApiAudit::recordByApiResponse($invalidPayload);
            return ['result' => false, 'reason' => 'API响应失败，请检查API密钥以及广告策略 ID', 'country' => ''];
        }

        VisitorApiAudit::recordByApiResponse($decoded);
        return $decoded;
    }
    
    // api.ttt.sh  API查询国家代码
    public function get_ip_country($client_ip)
    {
        $str = "";
        //$url = "https://api.ttt.sh/ip/qqwry/".$client_ip."?type=addr";
        //$str = file_get_contents($url);
        return $str;        
    }

    public function set_visit_md5_code($code)
    {
        $this->visit_md5_code = $code;      
    }

    public function get_visit_md5_code()
    {
        $domain = str_replace("www.","",$_SERVER['HTTP_HOST']);
        $time = date("YmdHis");
        $ip = $this->getIp();
        $this->visit_md5_code = substr(md5($domain.$time.$ip) , 0 , 12 );
        
        return $this->visit_md5_code;       
    }
        
    //获取访客ip
    public function getIp($type = 0)
    {
        if ($type) {
            return ClientIpResolver::resolve();
        }
        return ClientIpResolver::resolve();
    }

    //客户当前浏览的页面 url（浏览器实际访问地址，含正确 scheme 与 query）
    function curPageURL()
    {
        return cloak_current_request_url();
    }

    //根据ip获取城市、网络运营商等信息
    public function findCityByIp($ip){
        $country_res = @file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".$ip);
        $country_json = json_decode($country_res,true);
        // Array ( [code] => 0 [data] => Array ( [ip] => 104.223.98.4 [country] => 美国 [area] => [region] => 德克萨斯 [city] => 达拉斯 [county] => XX [isp] => XX [country_id] => US [area_id] => [region_id] => US_143 [city_id] => US_1099 [county_id] => xx [isp_id] => xx ) )
        $country = $country_json["data"]["country"];

        return $country;
    }

    //site_server
    function get_site_server()
    {
        $dqml=getcwd();
        $dpml_ary = explode(DIRECTORY_SEPARATOR, $dqml);
        $dqml_str = $dpml_ary[2];
        $dqml_str = substr($dqml_str,0,4);

        return $dqml_str;
    }

    //字符串截取函数
    function ip_p_substr($p_bof,$p_eof,$p_str)
    {
        $p_1=explode($p_bof,$p_str);
        $p_e=strpos($p_1[1],$p_eof);
        $p_0=substr($p_1[1],0,$p_e);
    
        return $p_0;
    }

    //获取用户浏览器类型
    public function getBrowser(){
        $agent=$_SERVER["HTTP_USER_AGENT"];
        if(strpos($agent,'MSIE')!==false || strpos($agent,'rv:11.0')) //ie11判断
            return "ie";
        
        else if(strpos($agent,'Firefox')!==false)
            return "firefox";
        
        else if(strpos($agent,'Chrome')!==false)
            return "chrome";
        
        else if(strpos($agent,'Opera')!==false)
            return 'opera';
        
        else if((strpos($agent,'Chrome')==false)&&strpos($agent,'Safari')!==false)
            return 'safari';
        
        else
            return 'unknown';
    }

    //获取网站来源
    public function getFromPage(){
        if(empty($_SERVER['HTTP_REFERER'])) {
            return NULL;
        }
        else    
            return $_SERVER['HTTP_REFERER'];
    }

    function get_accept_language()
    {
        $lang = "";
        if(!empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) && isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) )
        {
            $accept_language = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 4); //只取前4位，这样只判断最优先的语言。如果取前5位，可能出现en,zh的情况，影响判断。 
            if (preg_match("/zh-c/i", $accept_language)) 
            $lang =  "Chinese"; 
            else if (preg_match("/zh/i", $accept_language)) 
            $lang =  "Chinese_Trad"; 
            else if (preg_match("/en/i", $accept_language)) 
            $lang =  "English"; 
            else if (preg_match("/fr/i", $accept_language)) 
            $lang =  "French"; 
            else if (preg_match("/de/i", $accept_language)) 
            $lang =  "German"; 
            else if (preg_match("/jp/i", $accept_language)) 
            $lang =  "Japanese"; 
            else if (preg_match("/ko/i", $accept_language)) 
            $lang =  "Korean"; 
            else if (preg_match("/es/i", $accept_language)) 
            $lang =  "Spanish"; 
            else if (preg_match("/sv/i", $accept_language)) 
            $lang =  "Swedish"; 
            else $lang =  $_SERVER["HTTP_ACCEPT_LANGUAGE"]; 
        }
        
        return $lang;
    }

    /*移动端判断*/
    function v_isMobile()
    { 
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        {
            return true;
        } 
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA']))
        { 
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        } 
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT']))
        {
            $clientkeywords = array ('nokia', 'sony',   'ericsson', 'mot',  'samsung',  'htc',  'sgh',  'lg',   'sharp',    'sie-', 'philips',  'panasonic',    'alcatel',  'lenovo',   'iphone',   'ipod', 'blackberry',   'meizu',    'android',  'netfront', 'symbian',  'ucweb',    'windowsce',    'palm', 'operamini',    'operamobi',    'openwave', 'nexusone', 'cldc', 'midp', 'wap',  'mobile'
                ); 
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            {
                return "Mobile";
            } 
        } 
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT']))
        { 
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
            {
                return "Mobile";
            } 
        } 
        return "PC";
    }
}
