<?php

class theme_logAction extends BackendAction{

    public function _initialize() {
        parent::_initialize();
        $this->_mod = D('theme_log');
    }

    public function index() {		
		$p = I('p',1, 'intval');	
		$count = $this->_mod->count();
		$pager = new Page($count,100);
		$list = $this->_mod->order('id DESC')->limit($pager->firstRow.','.$pager->listRows)->select();		
		foreach($list as $key=>$val){ 
		   $list[$key] = $val;
		   $list[$key]['add_time'] = date('Y-m-d H:i:s',$val['add_time']);			   
		   $list[$key]['is'] = $this->check($val['theme_key'],$val['theme_version']);
		}			
		$this->assign('list',$list);				
		$page = $pager->show();
        $this->assign("page", $page);						
		$this->display();
	}
	public function uplist() {
		$key = I('key');	    
		$map = array();
		$map['theme_key'] = $key;
		$item = $this->_mod->where($map)->find();
        ($keyword = $this->_request('keyword', 'trim')) && $map['title'] = array('like', '%'.$keyword.'%');
        $this->assign('search', array(
            'keyword' => $keyword,
        ));
		$p = I('p',1 ,'intval');          
		$page_size = 100;	
	    $start = $page_size * ($p - 1) ;
		$list = D('theme_up_log')->where($map)->order('id desc')->limit($start . ',' . $page_size)->select();
		$this->assign('list', $list);
		$count = D('theme_up_log')->where($map)->count('id');
        $pager = new Page($count, 100);
		$page = $pager->show();
        $this->assign("page", $page);
		$this->assign("item", $item);
		$this->assign('list_table', true);
		$this->display();
    }
	protected function check($key,$v){	
	    $url = 'https://cms.douhao.com/?m=xiazai&a=theme_up_version';
		$post = array(
	    'mod' => 'theme_up_version',
        'key' => $key,
		'v' => $v
	    );
		$data = $this->curl_post($url,$post);	
		$item = json_decode($data,true);		
		return $item;
	}
	public function down() {
		$sqldir = 'app/Lib/Action/index/upsqlAction.class.php';	
		if(file_exists($sqldir)){			
		unlink($sqldir);
		}
		// 这里省略了版本判断逻辑，根据自己需要去写							
		// 更新包信息	
		$theme_upkey = I('theme_upkey');//升级包KEY		
		$theme_version = I('theme_version');//升级版本
		$theme_key = I('theme_key');//主题KEY
		$cmsversion = I('cmsversion');//支持CMS版本
		$title = I('title');//补丁名称		
		if($cmsversion>DOUHAO_CMS_BANBEN){
		$this->ajaxReturn(0,'该补丁版本不适用于当前程序版本号，请先升级CMS至最新版！');		
		}
		//更新包文件名称
		$filename = $theme_upkey.'.zip';	
		//检查和创建文件夹
		$dir = C('ftx_attach_path') . 'themeup/';				
		$this->make_dir($dir);
		// 下载更新包到本地并赋值文件路径变量
		$path = file_exists($dir.$filename)?$dir.$filename:$this->download_file($theme_upkey,$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 . ']目录的写入权限');
			}
			
			$data['theme_version'] = $theme_version;
			$data['version'] = $cmsversion;
			$data['install_time'] = time();
			$map['theme_key'] = $theme_key;	
			D('theme_log')->where($map)->save($data);	
			$item['title'] = $title;		
			$item['theme_upkey'] = $theme_upkey;	
			$item['theme_key'] = $theme_key;	
			$item['theme_version'] = $theme_version;
			$item['install_time'] = time();
			D('theme_up_log')->add($item);	
									
			if(file_exists($sqldir)) {
				$sqlurl = C('ftx_site_url')."?m=upsql&a=index";	
				$this->ajaxReturn(1,'主题升级完成，点此升级数据库：<a href="'.$sqlurl.'" target="_blank" class="red">去升级SQL</a>');	
			}
			
			$this->ajaxReturn(1,'主题升级完成');	
			
		} else {
			//压缩包打开失败，删除文件并且返回报错
			unlink($path);			
			$this->ajaxReturn(0, '文件解压失败，请重试！');
		}
	}
	public function make_dir($path) {
		if (!file_exists($path)) {
			$mk = @mkdir($path, 0777, true);
			@chmod($path, 0777, true);
		}
		return true;
	}
	protected function download_file($theme_upkey, $dir, $filename = '') {
		if (empty($theme_upkey)) {
			return false;
		}
		$dir = realpath($dir);
		$filename = $dir . "/".$filename;
		//开始捕捉			    
		$url = 'https://cms.douhao.com/?m=xiazai&a=download_theme_up';
		$post = array(
	    'mod' => 'down',
        'theme_upkey' => $theme_upkey,
	    );
		$data = $this->curl_post($url,$post);		
		if($data==1){
		$this->ajaxReturn(0, '该补丁所属主题未安装！');		
		}
		if($data==2){
		$this->ajaxReturn(0, '补丁不存在！');		
		}
		if($data==3){
		$this->ajaxReturn(0, '错误，请勿非法请求！');		
		}
		if($data==4){
		$this->ajaxReturn(0, '非正式环境禁止安装主题补丁！');		
		}
		$size = strlen($data);
		$fp2 = fopen($filename, "a");		
		fwrite($fp2, $data);
		fclose($fp2);
		return $filename;
	}
	public function curl_post($url,$post){
		$post = $post + array(
	    'from' => C('ftx_site_url'),
		'svs'=>get_client_ip()
	    );		
		$post = http_build_query($post);
		$ch = curl_init();      
	    $timeout = 300;       
	    curl_setopt($ch, CURLOPT_URL, $url);         
		curl_setopt($ch, CURLOPT_REFERER, $_SERVER["HTTP_REFERER"]);  
	    curl_setopt($ch, CURLOPT_POST, true);      
	    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);      
	    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);	
		return $source;
	}
    
}