<?php
namespace app\index\controller;

use \think\Controller;
use \think\Request;
use \think\Session;
use \think\Config;
use \think\Cache;
class Domain extends Controller
{
    protected $request;
	protected static $account;
	private static $uif;
	 
	
    
	public function __construct(Request $request)
    {
		parent::__construct();
		self::$account = \app\index\model\Account::instance();
		if(!Session::has('unique_id')){
			$this->redirect('index/account/login',302);
		}
		self::$uif['unique_id'] = Session::get('unique_id');
		if(!self::$uif = self::$account->findUser(self::$uif['unique_id'],'unique_id')){
			$this->redirect('index/account/login',302);
		}
    	$this->request = $request;
		
    }

	public function create(){
		
		if($this->request->isPost()){
			if(!$this->request->has('zone_name','param')){
				return $this->error('没有设置主域!');
			}
			$zone = $this->request->post('zone_name'); //取主域
			$domain = \app\index\model\Domain::instance();
			if($domain->getEarliestHost($zone)){
				return $this->error('这个域名已经被别人使用了!');
			}
			$data = [
				'act'=>'zone_set',
				'user_key'=>Session::get('user_key'),
				'zone_name'=>$zone,
				'subdomains'=>'',
			];
			$sqlData = [];
			$sub = [];
			$sub['type'] = $this->request->post('type/a');
			$sub['sub'] = $this->request->post('sub/a');
			$sub['record'] = $this->request->post('record/a');
			foreach($sub['type'] as $key=>$val){
				if(!$sub['type'][$key] || !$sub['sub'][$key] || !$sub['record'][$key]){
					unset($sub['type'][$key],$sub['sub'][$key],$sub['record'][$key]);
					continue;
				}
				//当为泛域名时跳过(不允许添加泛域名)
				if($sub['sub'][$key] =='*'){
					continue;
				}
				$recordData = [];
				$recordData['unique_id'] = Session::get('unique_id');
				$recordData['domain'] = $zone;
				$recordData['sub'] = $sub['sub'][$key];
				if($val == "A"||$val == "AAAA"){
					if(!recordChick($sub['record'][$key],$val)){
						return $this->error("子域名{$sub['sub'][$key]}的值不是一个IP!");
					}
					if(!$cif = ip2cname($sub['record'][$key],$val)){
						return $this->error("转换子域名{$sub['sub'][$key]}时出现错误!");
					}
					$recordData['type'] = $val;
					$recordData['ip'] = $sub['record'][$key];
					if(!$cif){
						return $this->error("子域{$sub['sub'][$key]}在设置解析时发生错误,请联系管理员!");
					}else{
						$sub['record'][$key] = $cif['cname']; //使用cname覆盖原来的解析ip
						$recordData['cname'] = $sub['record'][$key];
						$recordData['record_id'] = $cif['record_id'];
					}
				}elseif($val == "CNAME"){
					$recordData['type'] = 'CNAME';
					$recordData['ip'] = null;
					$recordData['cname'] = $sub['record'][$key];
					$recordData['record_id'] = null;
				}else{
					return $this->error('模式错误,我们只支持A|AAAA|CNAME模式.');
				}

				if($sub['sub'][$key] == '@'){
					$data['resolve_to'] = $recordData['cname'];
					$sqlData['_www'] = $recordData;
					$sqlData['_www']['sub'] = 'www';
				}else{
					$data['subdomains'] .= "{$recordData['sub']}:{$sub['record'][$key]},"; 
				}
				$sqlData[] = $recordData;
				
				unset($recordData);
			}
			$data['subdomains'] = substr($data['subdomains'], 0, -1);
			$return = performRequest($data);
			$return = returnCheck($return);
			if(!is_array($return)){
				return $this->error($return);
			}
			if(in_array('www',$sub['sub'])){
				unset($sqlData['_www']); //当子域包含www的时候删除默认值
			}
			$domain->addMultiDomainInfo($sqlData);
			return $this->success('域名添加成功',url('index/domain/info',['domain'=>$zone]));
		}else{
			return $this->fetch();
		}
		
    }

	public function info(){
		if(!$this->request->has('domain','param')){
			$this->error('参数错误!','index/panel/index');
		}
		$zone = $this->request->param('domain');
		$return = $this->getDomainList($zone);
		if(!is_array($return)){
			return $this->error($return);
		}
		if(!$return['response']['zone_exists']){
			return $this->error('这个域名已被删除或不属于你！');
		}
		$sub = [];
		//添加域名对应cname
		foreach($return["response"]['forward_tos'] as $key=>$val){
			$sub[$key]['cname'] = $val;
		}
		$forwardDomain = \think\Config::get('forward_domain');//读取转发域名
		$domain = null;
		//添加域名对应源地址
		foreach($return["response"]['hosted_cnames'] as $key=>$val){
			if($key == $zone){
				$sub[$key]['sub'] = '@';
			}else{
				$sub[$key]['sub'] = substr($key,0,strlen($key) - strlen($zone) - 1);//去除根域得到子域
			}
			
			if(substr($val,-12) == 'comodoca.com'){//如果回源域名是comodo验证域
				$sub[$key]['cname'] = $val;
				$sub[$key]['source'] = "";
			}elseif(substr($val, 0 - strlen($forwardDomain)) == $forwardDomain){ //如果源cname来自转发域名
				$domain = \app\index\model\Domain::instance($domain);
				$source = $domain->findHost($sub[$key]['sub'],$zone);
				if(!$source){ //没有从本地记录里找到解析记录
					$sub[$key]['source'] = $val; 
                }elseif($source['type'] == 'A' || $source['type'] == 'AAAA'){ //如果本地记录是A记录
					$sub[$key]['source'] = $source['ip'];
				}elseif($source['type'] == 'CNAME'){ //如果本地记录是CNAME记录
					$sub[$key]['source'] = $val;
				}
			}else{
				$sub[$key]['source'] = $val;
			}
		}
		$this->assign('sub',$sub);
		$this->assign('domain',$zone);
		return $this->fetch();
		
    }
    
	public function edit(){
		if(!$this->request->has('domain','param') || !$this->request->has('sub','param')){
			$this->error('参数错误!','index/panel/index');
		}
		$domain = \app\index\model\Domain::instance();
		$sub = $this->request->param('sub');
		$zone = $this->request->param('domain');
		if($this->request->isPost()){
			$type = $this->request->param('type');
			$record = $this->request->param('record');
			$allHost = $domain->findDomain($zone,Session::get('unique_id'));
			$subHostInfo = []; //用于后面的更新记录使用
			$sourceHostInfo = []; //源记录,用于请求成功删除用
			$data = [
				'act'=>'zone_set',
				'user_key'=>Session::get('user_key'),
				'zone_name'=>$zone,
				'subdomains'=>'',
			];
			foreach($allHost as $key=>$val){
				if($val['sub'] != $sub){ //子域不是要修改的子域名时
					if($val['sub'] =='@'){
						$data['resolve_to'] = $val['cname']; //如果是顶级域名就设置顶级域名解析
					}else{
						$data['subdomains'] .= "{$val['sub']}:{$val['cname']},"; //如果是自己域名则添加到子域
					}
					
				}else{
					$subHostInfo = $sourceHostInfo = $val; //先将现有数据另存2份
					unset($subHostInfo['id']);
					if($type == 'A' || $type == 'AAAA'){
						if(!recordChick($record,$type)){
							return $this->error("{$record}的值不是一个IP!");
						}
						if(!$cif = ip2cname($record,$type)){
							return $this->error("转换子域名时出现错误!");
						}
						if($val['sub'] == '@'){
							$data['resolve_to'] = $cif['cname'];
						}else{
							$data['subdomains'] .= "{$val['sub']}:{$cif['cname']},"; //将解析的cname设置为新的cname
						}
						$subHostInfo['type'] = $type;
						$subHostInfo['ip'] = $record;
						$subHostInfo['cname'] = $cif['cname'];
						$subHostInfo['record_id'] =$cif['record_id'];
					}elseif($type =='CNAME'){
						if($val['sub'] == '@'){
							$data['resolve_to'] = $record;
							//continue; //当域名是主域名时设置解析值后跳出本次循环
						}else{
							$data['subdomains'] .= "{$val['sub']}:{$record},"; //将解析的cname设置为新的cname
						}
						$subHostInfo['type'] = 'CNAME';
						$subHostInfo['ip'] = null;
						$subHostInfo['cname'] = $record;
						$subHostInfo['record_id'] = null;
					}else{
						return $this->error('模式错误,我们只支持A模式和CNAME模式.');
					}
				}
			}
			
			$comodo = $this->getComodoSub($zone); //获取comodossl
			if($comodo['code'] == 1){
				$data['subdomains'] .=$comodo['data']; //如果有comodo域名
			}elseif($comodo['code'] == 0){
				$data['subdomains'] = substr($data['subdomains'], 0, -1); //去除最后一个标点
			}else{
				return $this->error($comodo);
			}
			$return = performRequest($data);
			$return = returnCheck($return);
			if(!is_array($return)){
				return $this->error($return);
			}
			$domain->addDomainInfo($subHostInfo); //添加新的解析记录
			if($sourceHostInfo){
				$domain->delForwardRecord($sourceHostInfo['id']); //删除原来的解析记录
				delForwardRecord($sourceHostInfo['record_id']); //删除xns原来的解析
            }
            Cache::rm('cf_'.$zone);
			return $this->success('解析记录更新成功!',url('index/domain/info',['domain'=>$zone]));
		}else{
			$dif = $domain->findHost($sub,$zone);
			$this->assign('dif',$dif);
			return $this->fetch();
		}
	}

	public function del(){
		if(!$this->request->has('domain','param') || !$this->request->has('sub','param')){
			$this->error('参数错误!','index/panel/index');
		}
		$sub = $this->request->param('sub');
		$zone = $this->request->param('domain');
		
		if($sub =='@'){
			return $this->error('你不能删除顶级域名的解析记录.');
		}
		$data = [
			'act'=>'zone_set',
			'user_key'=>Session::get('user_key'),
			'zone_name'=>$zone,
			'subdomains'=>'',
		];
		$domain = \app\index\model\Domain::instance();
		$allHost = $domain->findDomain($zone,Session::get('unique_id')); //取用户所有列表
		if(!$allHost){
			return $this->error('没有这个域名的解析记录或者这个域名不属于你!');
		}
		foreach($allHost as $key=>$val){
			if($val['sub'] == $sub){
				$delId['id'] = $val['id'];
				if($val['type'] =='A' || $val['type'] =='AAAA'){
					$delId['xid'] = $val['record_id'];
				}
			}else{
				if($val['sub'] == '@'){
					$data['resolve_to'] = $val['cname'];
				}else{
					$data['subdomains'] .= "{$val['sub']}:{$val['cname']},";
				}
			}
		}
		if(!isset($delId)){
			return $this->error('没有找到需要删除的记录!');
		}
		$comodo = $this->getComodoSub($zone); //获取comodossl
		if($comodo['code'] == 1){
			$data['subdomains'] .=$comodo['data']; //如果有comodo域名
		}elseif($comodo['code'] == 0){
			$data['subdomains'] = substr($data['subdomains'], 0, -1); //去除最后一个标点
		}else{
			return $this->error($comodo);
		}
		$return = performRequest($data);
		$return = returnCheck($return);
		if(!is_array($return)){
			return $this->error($return);
		}
		if(isset($delId['xid'])){
			delForwardRecord($delId['xid']);
		}
		$domain->delForwardRecord($delId['id']);
		Cache::rm('cf_'.$zone);
		return $this->success('记录成功删除');
	}

	//获取域名下的子域名
	private function getDomainList($zone){
        if(!$return = Cache::get('cf_'.$zone)){
            $data = [
                'act'=>'zone_lookup',
                'user_key'=>Session::get('user_key'),
                'zone_name'=>$zone,
            ];
            $return = performRequest($data);
            $return = returnCheck($return);
            if(is_array($return)){
				Cache::set('cf_'.$zone,$return);
			}
        }
		return $return;

	}

	public function add(){
		if($this->request->isGet()){
			return $this->error('你好像走错路了');
		}
		if(!$this->request->has('domain','param')){
			$this->error('参数错误!','index/panel/index');
		}
		$zone = $this->request->param('domain');
		$domain = \app\index\model\Domain::instance();
		if(!$allHost = $domain->findDomain($zone,Session::get('unique_id'))){
			return $this->error('您的帐户下不存在这个域名!');
		}
		$data = [
			'act'=>'zone_set',
			'user_key'=>Session::get('user_key'),
			'zone_name'=>$zone,
			'subdomains'=>'',
		];
		$subList = [];
		//将sql里所有记录的子域全部取出并添加相应的子域记录
		foreach($allHost as $key=>$val){
			$subList [] = $val['sub'];
			if($val['sub'] == '@'){
				$data['resolve_to'] = $val['cname'];
			}else{
				$data['subdomains'] .= $val['sub'].':'.$val['cname'].',';
			}
			
		}
		$sqlData = []; //最后插入sql
		//获取新添加的子域记录
		$sub = []; 
		$sub['type'] = $this->request->post('type/a');
		$sub['sub'] = $this->request->post('sub/a');
		$sub['record'] = $this->request->post('record/a');
		foreach($sub['type'] as $key=>$val){
			//去除无效的解析记录
			if(!$sub['type'][$key] || !$sub['sub'][$key] || !$sub['record'][$key]){
				unset($sub['type'][$key],$sub['sub'][$key],$sub['record'][$key]);
				continue;
			}
			//当为顶级域和泛域名时跳过(添加子域解析不允许添加顶级域名解析)
			if(in_array($sub['sub'][$key],$subList) || $sub['sub'][$key] =='*'){
				continue;
			}
			$recordData = [];
			$recordData['unique_id'] = Session::get('unique_id');
			$recordData['domain'] = $zone;
			$recordData['sub'] = $sub['sub'][$key];
			if($val == "A" || $val == "AAAA"){
				if(!recordChick($sub['record'][$key],$val)){
					return $this->error("子域名{$sub['sub'][$key]}的值不是一个IP!");
				}
				if(!$cif = ip2cname($sub['record'][$key],$val)){
					return $this->error("转换子域名{$sub['sub'][$key]}时出现错误!");
				}
				$recordData['type'] = $val;
				$recordData['ip'] = $sub['record'][$key];
				if(!$cif){
					return $this->error("子域{$sub['sub'][$key]}在设置解析时发生错误,请联系管理员!");
				}else{
					$sub['record'][$key] = $cif['cname']; //使用cname覆盖原来的解析ip
					$recordData['cname'] = $sub['record'][$key];
					$recordData['record_id'] = $cif['record_id'];
				}
			}elseif($val == "CNAME"){
				$recordData['type'] = 'CNAME';
				$recordData['ip'] = null;
				$recordData['cname'] = $sub['record'][$key];
				$recordData['record_id'] = null;
			}else{
				return $this->error('模式错误,我们只支持A|AAAA|CNAME模式.');
			}
			$data['subdomains'] .= "{$recordData['sub']}:{$sub['record'][$key]},"; 
			$sqlData[] = $recordData;
			unset($recordData);
		}

		//添加comodo验证域名
		$comodo = $this->getComodoSub($zone); //获取comodossl
		if($comodo['code'] == 1){
			$data['subdomains'] .=$comodo['data']; //如果有comodo域名
		}elseif($comodo['code'] == 0){
			$data['subdomains'] = substr($data['subdomains'], 0, -1); //去除最后一个标点
		}else{
			return $this->error($comodo);
		}
		$return = performRequest($data);
		$return = returnCheck($return);
		if(!is_array($return)){
			return $this->error($return);
		}
		$domain->addMultiDomainInfo($sqlData);
		Cache::rm('cf_'.$zone);
		return $this->success('子域名记录添加成功',url('index/domain/info',['domain'=>$zone]));
	}

	public function deldomain(){
		$zone = $this->request->param('domain');
		$data = [
			'act'=>'zone_delete',
			'user_key'=>Session::get('user_key'),
			'zone_name'=>$zone
		];
		$return = performRequest($data);
		$return = returnCheck($return);
		if(!is_array($return)){
			return $this->error($return);
		}
		$unique_id = Session::get('unique_id');
		$domain = \app\index\model\Domain::instance();
		$subList = $domain->delAllDomainInfo($zone);

		return $this->success('域名删除成功!');
	}

	private function getComodoSub($zone,$sub = true){
			if(!$lastDomain =Cache::get('comodo-'.$zone)){
				$lastDomain = $this->getDomainList($zone);
				if(!is_array($lastDomain)){
					return ['code'=>-1,'data'=>$this->error($return)];
				}
			}
			foreach($lastDomain['response']['hosted_cnames'] as $key=>$val){
				if(substr($val,-12) == 'comodoca.com'){//如果回源域名是comodo验证域
					Cache::set('comodo-'.$zone,$lastDomain); //取到comodo域名的时候缓存记录
					if($sub){
						$sub = substr($key,0,strlen($key) - strlen($zone) - 1);
						return ['code'=>1,'data'=>$sub.':'.$val];
					}else{
						$sub = substr($key,0,strlen($key) - strlen($zone) - 1);
						return ['code'=>1,'data'=>['sub'=>$sub,'record'=>$val]];
					}
					break;
				}
			}
			return ['code'=>0,'data'=>null];
	}

}