<?php
if (!defined('ROOT'))
    exit('Can\'t Access !');
//error_reporting(0);
class safe_admin extends admin {

    private $webscan360_getkey_url = "http://webscan.360.cn/mapi/get-key";
	private $webscan360_verifydomain_url = "http://webscan.360.cn/mapi/verify-domain";
	
    function init() {
    }
    function webshell_action() {
		chkpw('func_data_safe');
		$ifSiteAdmin = false;
		$webscan_model = new webscan();
    	$res = $webscan_model->getrow(array('var'=>'key'));
    	if(!empty($res) && !empty($res['value']) && $res['state'] == 1){
    		$ifSiteAdmin = true;
    	}else{
    		$result = $this->verifyDomain( );
    		//$result = array('infocode'=>"202" , 'msg'=>"not get key from 360webscan" ,'httpcode'=>"403");
			if($result['infocode'] == "111"){
				$this->addWebscankey($result);
				$this->webshell_addkey($result['skey']);
				$this->protect_addkey($result['pkey']);
				$ifSiteAdmin = true;
			}else{
				$this->view->infocode = $result['infocode'].'@'.$result['httpcode'];
			}
    		
    	}
		$this->view->ifSiteAdmin = $ifSiteAdmin;	
    	
    }
    function protect_action() {
		chkpw('func_data_safe');
		$ifSiteAdmin = false;
		$webscan_model = new webscan();
    	$res = $webscan_model->getrow(array('var'=>'key'));
    	if(!empty($res) && !empty($res['value']) && $res['state'] == 1){
    		$ifSiteAdmin = true;
    	}else{
    		$result = $this->verifyDomain( );
    		
			if($result['infocode'] == "111"){
				$this->addWebscankey($result);
				$this->protect_addkey($result['pkey']);
				$this->webshell_addkey($result['skey']);
				$ifSiteAdmin = true;
			}else{
				$this->view->infocode = $result['infocode'].'@'.$result['httpcode'];
			}
    		
    	}
    	/*
    	$ifInsertcode = false;
    	if($ifSiteAdmin){
    		$ifInsertcode = $this->insertInclde();
    	}
    	$this->view->ifInsertcode = $ifInsertcode;
		*/
		$this->view->ifSiteAdmin = $ifSiteAdmin;
    	
    }
	function end() {
        $this->render('index.php');
    }
    function addWebscankey($result){
    	$webscan_model = new webscan();
		$webscan_model->rec_update(array('state'=>1),array('var'=>'key'));
		//begin record protect key
		if(!empty($result['pkey'])){
			$res_p = $webscan_model->getrow(array('var'=>'pkey'));
			if(empty($res_p)){
				$webscan_model->rec_insert(array('var'=>'pkey','value'=>$result['pkey']));
			}else{
				$webscan_model->rec_update(array('value'=>$result['pkey']),array('var'=>'pkey'));
			}
		}
		//end record protect key
		//begin record webshell key
		if(!empty($result['skey'])){
			$res_s = $webscan_model->getrow(array('var'=>'skey'));
			if(empty($res_s)){
				$webscan_model->rec_insert(array('var'=>'skey','value'=>$result['skey']));
			}else{
				$webscan_model->rec_update(array('value'=>$result['skey']),array('var'=>'skey'));
			}
		}				
		//end record webshell key   	
    }
	function verifyDomain( ){
		$result = array('infocode'=>"no" , 'msg'=>"");
		
		$model = new webscan_httpd();
		$ret = $model->http_request($this->webscan360_getkey_url , array('host'=>$_SERVER['HTTP_HOST']));
		//print_r($ret);exit;
		$httpcode = $ret['httpcode'];
		$response = $ret['response'];
		$response = json_decode($response , true);
		$webscan_model = new webscan();
		if(!empty($ret) && !empty($response) && $httpcode == 200 && $response['infocode'] == "111" && !empty($response['key'])){
			$key = $response['key'];
			$res_key = $webscan_model->getrow(array('var'=>'key'));
			if(!empty($res_key)){
				$op_ret = $webscan_model->rec_update(array('value'=>$key),array('var'=>'key'));
			}else{
				$op_ret = $webscan_model->rec_insert(array('var'=>'key','value'=>$key));
			}
			if($op_ret){
				$ret_verityDomain = $model->http_request($this->webscan360_verifydomain_url , array('key'=>$key , 'host'=>$_SERVER['HTTP_HOST']));
				//print_r($ret_verityDomain);exit;
				$httpcode_verityDomain = $ret_verityDomain['httpcode'];
				$response_verityDomain = $ret_verityDomain['response'];
				if(!empty($ret_verityDomain) && !empty($response_verityDomain) && $httpcode_verityDomain == 200){
					$response_verityDomain_array = json_decode($response_verityDomain , true);
					$result = $response_verityDomain_array;
				}else{
					$result = array('infocode'=>"203" , 'msg'=>"not verify host from 360webscan" ,'httpcode'=>$httpcode_verityDomain);
				}
			}else{
				$result = array('infocode'=>"202" , 'msg'=>"not insert key");
			}
		}else{
			if($response['infocode'] == "300"){
				$result = $response;
			}else{
				$result = array('infocode'=>"201" , 'msg'=>"not get key from 360webscan" ,'httpcode'=>$httpcode);
			}
		}
		if(!empty($result)){
			$webscan_model->rec_insert(array('var'=>'log_verify','value'=>json_encode($result)));
		}
		return $result;
	}
	function webshell_addkey($key){
		//begin webshell key
		$webscan_model = new webscan();
		$webscan360_webshell_cofigfile = ROOT.'/360scan.php';
		if(is_file($webscan360_webshell_cofigfile)){
			$webscan360_webshell_cofigfile_content = @file_get_contents($webscan360_webshell_cofigfile);
			if(strstr($webscan360_webshell_cofigfile_content,"@webscan360key@")){
				if(is_writable($webscan360_webshell_cofigfile)){
					$webscan360_webshell_cofigfile_content = str_replace("@webscan360key@",$key , $webscan360_webshell_cofigfile_content);
					@file_put_contents($webscan360_webshell_cofigfile , $webscan360_webshell_cofigfile_content);
					$webscan_model->rec_insert(array('var'=>'log_webshell','value'=>'360scan.php replace key success'));
				}else{
					$webscan_model->rec_insert(array('var'=>'log_webshell','value'=>'360scan.php not write'));
				}
			}
		}else{
			$webscan_model->rec_insert(array('var'=>'log_webshell','value'=>'360scan.php not exist'));
		}
		
		//end webshell key		
	}
	function protect_addkey($key){
		$webscan_model = new webscan();
		//begin protect key
		$webscan360_protect_cofigfile = ROOT.'/360safe/webscan_cache.php';
		if(is_file($webscan360_protect_cofigfile)){
			$webscan360_protect_cofigfile_content = @file_get_contents($webscan360_protect_cofigfile);
			if(strstr($webscan360_protect_cofigfile_content,"@webscan360key@")){
				if(is_writable($webscan360_protect_cofigfile)){
					$webscan360_protect_cofigfile_content = str_replace("@webscan360key@",$key , $webscan360_protect_cofigfile_content);
					@file_put_contents($webscan360_protect_cofigfile , $webscan360_protect_cofigfile_content);
					$webscan_model->rec_insert(array('var'=>'log_protect','value'=>'webscan_cache.php replace key success'));
				}else{
					$webscan_model->rec_insert(array('var'=>'log_protect','value'=>'webscan_cache.php not write'));
				}
			}
			
		}else{
			$webscan_model->rec_insert(array('var'=>'log_protect','value'=>'webscan_cache.php not exist'));
		}
		//end protect key		
	}
	function insertInclde( ){
		$commonFile_360webscan = ROOT.'/config/config.php';
		$safefile_360webscan = ROOT."/360safe/360webscan.php";
		//$safelogfile_360webscan = ROOT."/cache/360webscan";
		$webscan_model = new webscan();
		$If_Addcode = false;
		$comonFileContent = @file_get_contents($commonFile_360webscan);
		if(!strstr($comonFileContent , "/360safe/360webscan.php")){
			if(is_file($commonFile_360webscan)){
				if(is_file($safefile_360webscan)){
					if(is_writable($commonFile_360webscan)){
						if(copy($commonFile_360webscan,ROOT."/config/config_bak.php")){
							if(strstr($comonFileContent,"<?php")){
								$include_content = "<?php".PHP_EOL."require_once('".$safefile_360webscan."');".PHP_EOL."?>".PHP_EOL;
								@file_put_contents($commonFile_360webscan,$include_content.$comonFileContent);
								$webscan_model->rec_insert(array('var'=>'log_protect','value'=>'add include success'));
								//@file_put_contents($safelogfile_360webscan,"success\n",FILE_APPEND);
								$If_Addcode = true;
							}else{
								$webscan_model->rec_insert(array('var'=>'log_protect','value'=>'not contain php flag'));
								//@file_put_contents($safelogfile_360webscan,"not contain php flag\n",FILE_APPEND);
							}	
							
						}else{
							$webscan_model->rec_insert(array('var'=>'log_protect','value'=>'bak config file failer'));
							//@file_put_contents($safelogfile_360webscan,"copy failer common.inc.php not write\n",FILE_APPEND);
						}
					}else{
						$webscan_model->rec_insert(array('var'=>'log_protect','value'=>'config file not write'));
						//@file_put_contents($safelogfile_360webscan,"common.inc.php not write\n",FILE_APPEND);
					}
				}else{
					$webscan_model->rec_insert(array('var'=>'log_protect','value'=>'360webscan.php not exist'));
					//@file_put_contents($safelogfile_360webscan,"360webscan.php not exist\n",FILE_APPEND);
				}
			}else{
				$webscan_model->rec_insert(array('var'=>'log_protect','value'=>'config not exist'));
				//@file_put_contents($safelogfile_360webscan,"common.inc.php not exist\n",FILE_APPEND);
			}
		}else{
			$If_Addcode = true;	
		}
		return $If_Addcode;		
	}

}
class webscan_httpd {
  var $method;
  var $post;
  var $header;
  var $ContentType;


  function __construct() {
    $this->method = '';
    $this->cookie = '';
    $this->post = '';
    $this->header = '';
    $this->errno = 0;
    $this->errstr = '';
	$this->ContentType='';
  }
  function  http_request($url , $postdata = array()){
  	if(function_exists('curl_init')) {
  		$return = $this->webscan_curl($url , $postdata);
  	}else{
  		$return = $this->webscan_fsockopen($url , $postdata);
  	}
  	return  $return;	
  }
  function webscan_curl($url , $postdata = array()){
	  $ch = curl_init();
	  curl_setopt($ch, CURLOPT_URL, $url);
	  curl_setopt($ch, CURLOPT_HEADER, 0);
	  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
	  curl_setopt($ch, CURLOPT_TIMEOUT, 15);
	  curl_setopt($ch, CURLOPT_POST, 1);
	  curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
	  $response = curl_exec($ch);
	  $httpcode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
	  curl_close($ch);
	  return array('httpcode'=>$httpcode,'response'=>$response);
  }
  function webscan_fsockopen($url, $data = array(), $referer = '', $limit = 0, $timeout = 15, $block = TRUE) {
    $this->method = 'POST';
    $this->ContentType = "Content-Type: application/x-www-form-urlencoded\r\n";
    if($data) {
      $post = '';
      foreach($data as $k=>$v) {
        $post .= $k.'='.rawurlencode($v).'&';
      }
      $this->post .= substr($post, 0, -1);
    }
    return $this->fsockopen_base($url, $referer, $limit, $timeout, $block);
  }

  function fsockopen_base($url, $referer = '', $limit = 0, $timeout = 30, $block = TRUE) {
    $matches = parse_url($url);
    $host = $matches['host'];
    $path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
    $port = $matches['port'] ? $matches['port'] : 80;
    if($referer == '') $referer = URL;
    $out = "$this->method $path HTTP/1.1\r\n";
    $out .= "Accept: */*\r\n";
    $out .= "Referer: $referer\r\n";
    $out .= "Accept-Language: zh-cn\r\n";
    $out .= "User-Agent: ".$_SERVER['HTTP_USER_AGENT']."\r\n";
    $out .= "Host: $host\r\n";
    if($this->method == 'POST') {
      $out .= $this->ContentType;
      $out .= "Content-Length: ".strlen($this->post)."\r\n";
      $out .= "Cache-Control: no-cache\r\n";
      $out .= "Connection: Close\r\n\r\n";
      $out .= $this->post;
    } else {
      $out .= "Connection: Close\r\n\r\n";
    }
    if($timeout > ini_get('max_execution_time')) @set_time_limit($timeout);
    $fp = @fsockopen($host, $port, $errno, $errstr, $timeout);
    $this->post = '';
    if(!$fp) {
      return false;
    } else {
      stream_set_blocking($fp, $block);
      stream_set_timeout($fp, $timeout);
      fwrite($fp, $out);
      $this->data = '';
      $status = stream_get_meta_data($fp);
      if(!$status['timed_out']) {
        $maxsize = min($limit, 1024000);
        if($maxsize == 0) $maxsize = 1024000;
        $start = false;
        while(!feof($fp)) {
          if($start) {
            $line = fread($fp, $maxsize);
            if(strlen($this->data) > $maxsize) break;
            $this->data .= $line;
          } else {
            $line = fgets($fp);
            $this->header .= $line;
            if($line == "\r\n" || $line == "\n") $start = true;
          }
        }
      }
      fclose($fp);
	  if(!empty($this->header)){
		  $header_info=preg_replace("/\r\n\r\n.*\$/",'',$this->header);
		  $headers=explode("\r\n",$header_info);
		  $httpcode = substr($headers[0], 9, 3);
	  }
	  $response = $this->data;
	  return array('httpcode'=>$httpcode,'response'=>$response);
    }
  }

}