<?php
/**
 * Matomo 统计API
 * @Copyright (C) 2018 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
namespace Common\Vendor;
class Matomo{
    private $token_auth='6bc774351787fed21a9b16fa5e351e96';
    private $scheme ='https:';
    private $baseurl = '//tongji.hanchao9999.com/';
    private $domain;
    public function __construct($token_auth='') {
        if(!empty($token_auth))$this->token_auth=$token_auth;
        $this->domain=$_SERVER['HTTP_HOST'];
    }    
    /**
     * 获取站点统计代码
     * @param $domain 域名
     */
    public function getScript($domain=''){
        $SiteIdinfo=$this->getSiteid($domain,1);
        if($SiteIdinfo['status']==0)return false;
        $SiteId=$SiteIdinfo['siteid'];
        $str='<script type="text/javascript">'.
          'var _paq = _paq || [];'.
          '_paq.push([\'trackPageView\']);'.
          '_paq.push([\'enableLinkTracking\']);'.
          '(function() {'.
          'var u="'.$this->baseurl.'";'.
          '_paq.push([\'setTrackerUrl\', u+\'piwik.php\']);'.
          '_paq.push([\'setSiteId\', \''.$SiteId.'\']);'.
          'var d=document, g=d.createElement(\'script\'), s=d.getElementsByTagName(\'script\')[0];'.
          'g.type=\'text/javascript\'; g.async=true; g.defer=true; g.src=u+\'piwik.js\'; s.parentNode.insertBefore(g,s);'.
          '})();'.
          '</script>';
        return $str;
    }
    
    /**
     * 获取查看统计url
     * @param $domain 域名
     * @param $is_check 是否检查为管理员登录
     */
    public function getviewurl($domain='',$is_check=false){
        if(empty($domain))$domain=$this->domain;
        $return=array('status'=>0,'info'=>'');$admininfo=array();
        if($is_check){
            $admininfo=session('admin_info');
            if(empty($admininfo)){$return['info']='请先登录管理员';return $return;}
        }
        $SiteIdinfo=$this->getSiteid($domain,1);
        if($SiteIdinfo['status']==0)return false;
        if(empty($admininfo))$admininfo=M("Admin")->where('id=1')->field('username,password')->cache(true)->find();
        if($admininfo['username']=='admin')$admininfo['username']=$domain;
        $configpassword=C('STATS_CODE');
        if($configpassword!=$admininfo['password']){
            $passwordlength=strlen($configpassword);
            if(empty($configpassword) || $passwordlength!=32){
                $this->addUser($admininfo['username'],$admininfo['password'],$domain);
            }else{
                $this->updateUser($admininfo['username'],$admininfo['password']);
            }
            $result=$this->checkUserAccess($admininfo['username'],$domain);
            if($result){
                $savedata=array();
                $savedata['value']=$admininfo['password'];
                M("Config")->where("name='STATS_CODE'")->save($savedata);
                S('DB_CONFIG_DATA', null);
            }
        } 
        $SiteId=$SiteIdinfo['siteid'];
        $username=$this->getusername($admininfo['username']);
        return $this->scheme.$this->baseurl.'?module=Login&action=logme&login='.$username.'&password='.md5($admininfo['password']).'&idSite='.$SiteId;
    }
    /**
     * 获取站点ID
     * @param $domain 域名
     * @param $is_auto 如果没有是否自动添加
     */
    private function getSiteid($domain='',$is_auto=0){
        if(empty($domain))$domain=$this->domain;
        $return=array('status'=>0,'info'=>'');
        $cachename='Siteid'.$domain;
        $content=S($cachename);
        if($content){
            $return['status']=1;
            $return['siteid']=$content;
            return $return;
        }
        $param=array(
            'method'=>'SitesManager.getSitesIdFromSiteUrl',
            'url'=>$domain,
        );
        $result=$this->getContent($param);
        if($is_auto && empty($result[0]['idsite'])){
            $result=$this->addSite($domain);
            if($result['siteid'])$result[0]['idsite']=$result['siteid'];
        }
        if($result[0]['idsite']){
            $return['status']=1;
            $return['siteid']=$result[0]['idsite'];
            S($cachename,$return['siteid'],60*60*24*7);
        }else{
            $return['info']='暂无';
        }
        return $return;
    }
    /**
     * 添加站点
     * @param $domain 域名
     */
    private function addSite($domain=''){
        if(empty($domain))$domain=$this->domain;
        $return=array('status'=>0,'info'=>'');
        $param=array(
            'method'=>'SitesManager.addSite',
            'siteName'=>$domain,
            'urls'=>$domain,
            'timezone'=>'UTC+8',
        );
        $result=$this->getContent($param);
        if($result['value']){
            $return['status']=1;
            $return['siteid']=$result['value'];
        }else{
            $return['info']='添加失败';
        }
        return $return;
    }
    /**
     * 添加用户
     * @param $username 用户名
     * @param $password密码
     * @param $domain 域名 赋予新增用户域名查看权限
     */
    private function addUser($username,$password='',$domain=''){
        if(empty($username))return false;
        $username=$this->getusername($username);
        if(empty($password))$password=md5($password);
        $email='user'.$username.'@hanchao9999.com';
        $param=array(
            'method'=>'UsersManager.addUser',
            'userLogin'=>$username,
            'password'=>$password,
            'email'=>$email,
            'alias '=>$username,
        );
        $result=$this->getContent($param);
        if($result['message']=='ok' && $result['result']=='success')$return= true;
        else if(strpos($result['message'],'already exists')>0)$return= true;
        $return= false;
        if($return && $domain){
            $this->setUserAccess($username,$domain);
        }return $return;
    }
    //返回可用用户名
    private function getusername($username=''){
        if(empty($username))return $this->domain;
        if($username=='admin')return $this->domain;
        if (preg_match("/([\x81-\xfe][\x40-\xfe])/", $username, $match))return $this->domain;
        return $username;
    }
    /**
     * 修改用户
     * @param $username 用户名
     * @param $password密码
     */
    private function updateUser($username,$password=''){
        if(empty($username))return false;
        $username=$this->getusername($username);
        if(empty($password))$password=md5($password);
        $email='user'.$username.'@hanchao9999.com';
        $param=array(
            'method'=>'UsersManager.updateUser',
            'userLogin'=>$username,
            'password'=>$password,
            'email'=>$email,
            'alias '=>$username,
        );
        $result=$this->getContent($param);
        if($result['message']=='ok' && $result['result']=='success')return true;
        return false;
    }   
    /**
     * 给会员赋予查看权限
     * @param $username 用户名
     * @param $domain 域名
     */
    private function setUserAccess($username,$domain=''){
        if(empty($username))return false;
        if(empty($domain))$domain=$this->domain;
        $username=$this->getusername($username);
        $SiteIdinfo=$this->getSiteid($domain,1);
        if($SiteIdinfo['status']==0)return false;
        $SiteId=$SiteIdinfo['siteid'];
        $param=array(
            'method'=>'UsersManager.setUserAccess',
            'userLogin'=>$username,
            'access'=>'view',
            'idSites'=>$SiteId,
        );
        $result=$this->getContent($param);
        if($result['message']=='ok' && $result['result']=='success')return true;
        return false;
    }
    
    /**
     * 检查给会员赋予的权限
     * @param $username 用户名
     * @param $domain 域名
     */
    public function checkUserAccess($username,$domain=''){
        if(empty($username))return false;
        if(empty($domain))$domain=$this->domain;
        $username=$this->getusername($username);
        $SiteIdinfo=$this->getSiteid($domain,1);
        if($SiteIdinfo['status']==0)return false;
        $SiteId=$SiteIdinfo['siteid'];
        $param=array(
            'method'=>'UsersManager.getUsersAccessFromSite',
            'idSite'=>$SiteId,
        );
        $result=$this->getContent($param);
        if(empty($result))$return=false;
        $users=array();
        foreach($result as $v){
            foreach($v as $k=>$val){$users[]=$k;}
        }
        if(in_array($username,$users))$return=true;
        if($return)return true;
        return $this->setUserAccess($username,$domain);
    }
    /**
     * 请求api
     * @param $param请求参数
     */
    private function getContent($param){
        if(empty($param))return false;
        $base_param=array(
            'module'=>'API',
            'format'=>'JSON',
            'token_auth'=>$this->token_auth,        
        );
        $params=array_merge($base_param,$param);
        $content=curlget($this->scheme.$this->baseurl,$params);
        return json_decode($content,1);        
    }
}