<?php
class updateAction  extends BackendAction {
	public function _initialize() {
		parent::_initialize();			
	}
	public function make_dir($path) {
		if (!file_exists($path)) {
			$mk = @mkdir($path, 0777, true);
			@chmod($path, 0777, true);
		}
		return true;
	}
	public function index() {	
        $sqldir = C('ftx_attach_path') . 'sql/sql.txt';	
	    unlink($sqldir);
		$p = I('p',1, 'intval');
		$url = "https://cms.douhao.com/?m=api&a=getupdate";		
		$data = array(
	    'p' => $p	        
	    );	
	    $data = http_build_query($data);	 
	    $ch = curl_init();      
	    $timeout = 300;       
	    curl_setopt($ch, CURLOPT_URL, $url);         
		curl_setopt($ch, CURLOPT_REFERER, $_SERVER["QUERY_STRING"]);  
	    curl_setopt($ch, CURLOPT_POST, true);      
	    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);      
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);      
	    $source = curl_exec($ch);      
	    curl_close($ch);		
		$arr = json_decode($source,true);	
		if(!$arr['msg']){
		$list = $arr['list'];
		$count = $arr['count'];
		foreach($list as $key=>$val){ 
		   $list[$key] = $val;
		   $list[$key]['add_time'] = date('Y-m-d H:i:s',$val['add_time']);
		   $list[$key]['ok'] = $this->check($val['update_key'],$val['version']);
		}		
		$this->assign('list',$list);		
		$pager = new Page($count, 50);
		$page = $pager->show();
        $this->assign("page", $page);			
		}			
		$this->display();
	}
	
	
	protected function check($update_key,$version){	        
		if(D('up_log')->where(array('update_key'=>$update_key))->find() || $version<=DOUHAO_CMS_BANBEN){
		return 1;	
		}else{
		return 0;		
		}
	}
	public function down() {
		// 这里省略了版本判断逻辑，根据自己需要去写							
		// 更新包信息	
		$update_key = I('update_key');	
		$version = I('version');//补丁版本号
		$mustvsn = I('mustvsn');//限定版本号
		if($mustvsn != DOUHAO_CMS_BANBEN){
		$this->ajaxReturn(0,'请先升级CMS版本至'.$mustvsn);		
		}
		if($version<=DOUHAO_CMS_BANBEN){
		$this->ajaxReturn(0,'当前版本号大于或等于最新版号！');		
		}
		if($this->check($update_key,$version)){
		  $this->ajaxReturn(0,'该补丁你已经升级过！');	
		}
		$file_url = 'https://cms.douhao.com/?m=api&a=download_update&update_key='.$update_key;
		//更新包的下载地址
		$filename = $update_key.'.zip';						
		//更新包文件名称
		//检查和创建文件夹
		$dir = C('ftx_attach_path') . 'update/';
		$sqldir = C('ftx_attach_path') . 'sql/sql.txt';	
		$this->make_dir($dir);
		// 下载更新包到本地并赋值文件路径变量
		$path = file_exists($dir.$filename)?$dir.$filename:$this->download_file($file_url,$dir,$filename);
		// 如果下载没成功就返回报错
		if (!file_exists($dir.$filename)) {
			$this->ajaxReturn(0,'文件下载失败');
		}
		// PHP解压的扩展类
		if(!class_exists("\ZipArchive")) 				
			    $this->ajaxReturn(0, '请安装ZipArchive扩展');
		// 实例化ZipArchive
		$zip = new \ZipArchive();
		
		//打开压缩包
		if ($zip->open($path) === true) {			
			$tpath	= Root_PATH;		
			try {
				// 解压文件到dir路径下
				$zip->extractTo($tpath);
				// 必须销毁变量，否则会报错
				unset($zip);
				// 删除更新包
				unlink($path);
			}
			catch (\Exception $e) {				
				$this->ajaxReturn(0, '没有[' . $tpath . ']目录的写入权限');
			}
			$item['update_key'] = $update_key;		
			D('up_log')->add($item);	
			if($version) {				
				$config_file = CONF_PATH . 'version.php';
				$data = file_get_contents($config_file);
				preg_match_all("/(?:\()(.*)(?:\))/i",$data, $result);
				$info  = str_replace($result[1][1], "'DOUHAO_CMS_BANBEN', '".$version."'", $data);				
				file_put_contents($config_file,$info,LOCK_EX);
			}
			if(file_exists($sqldir)) {
				$sql =  file_get_contents($sqldir);	
				if(C('DB_PREFIX') != 'douhao_'){
				$sql = str_replace('`douhao_', '`' . C('DB_PREFIX'), $sql);	
				}
				$is = $this->upsql($sql);				
				if($is){					
				$this->ajaxReturn(1,'补丁更新完成');	
				}else{
				$this->ajaxReturn(0,'插件安装完成，但数据库升级失败，请打开文件手动执行SQL：'.$sqldir,'，安全起见，执行完成后务必删除文件');	
				}				
			}
			
			$this->ajaxReturn(1,'补丁更新完成');	
			
		} else {
			// 压缩包打开失败，删除文件并且返回报错
			unlink($path);			
			$this->ajaxReturn(0, '更新包解压失败，请重试！');
		}
	}
	
	/*
    * 文件下载方法
    * $url 文件下载地址
    * $dir 存储的文件夹
    * $filename 文件名字
    */
	protected function download_file($url, $dir, $filename = '') {
		if (empty($url)) {
			return false;
		}
		$dir = realpath($dir);
		$filename = $dir . "/".$filename;
		//开始捕捉
		$ch = curl_init();      
	    $timeout = 300;       
	    curl_setopt($ch, CURLOPT_URL, $url);         
		curl_setopt($ch, CURLOPT_REFERER, $_SERVER["QUERY_STRING"]);  
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);      
	    $data = curl_exec($ch);      
	    curl_close($ch);
		if($data==2){
		$this->ajaxReturn(0, '插件不存在！');		
		}
		if($data==3){
		$this->ajaxReturn(0, '错误，请勿非法请求！');		
		}
		$size = strlen($data);
		$fp2 = fopen($filename, "a");
		fwrite($fp2, $data);
		fclose($fp2);
		return $filename;
	}
	
	protected function upsql($queries){			
			if($queries){
				$queries = trim( stripslashes( $queries ) );
				$list = explode( ";", $queries );
				$rs = M();
				$length = count( $list );
				if(1 <$length){
					foreach($list as $i => $sql){
						$sql = trim($sql);
						if (!empty($sql)){
							$mes = M()->execute($sql);
						}
						if (FALSE === $mes){							
							return 2;	
						}
					}
				}else{
					$rs->query( $sql );
				}
				return 1;
			}else{				
				return 0;	
			}
		
	}
}