<?php
defined('PP_PATH') or exit;
class upgrade_control extends admin_control {
	public function index(){
		$this->assign('upgrade_url', $upgrade_url);
		$this->display();
	}
	public function down(){
		$did	= htmlspecialchars(R('did','P'));
		$dir 	= 'cache';
		$sDir 	= ADM_PATH.$dir;
		if(!file_exists($sDir)){
			@mkdir($sDir, 0777, true);
		}
		//$this->download($dir,$did);
		$url 	= $this->_vip['api_url'].'?u=nzdown-upgrade_down-did-'.$did;
		try{
			$s = fetch_url($url, 20);
			if(empty($s) || substr($s, 0, 2) != 'PK') E(1, '没读取到更新文件？'.$s);
		}catch(Exception $e) {
			E(1, '下载更新出错了？'.$s);
		}
		try{
			file_put_contents(ADM_PATH.$dir.'/update.zip', $s);
		}catch(Exception $e) {
			E(1, '升级包写入出错，权限不对？');
		}
		
		$zipfile = $sDir.'/update.zip';
		try{
			kp_zip::unzip($zipfile, $dir);
		}catch(Exception $e) {
			E(1, '解压升级包出错！');
		}
		unlink($zipfile);
		E(0, '成功准备升级文件');
	}
	public function apply(){
		$dir 	= 'cache';
        $sDir 	= ADM_PATH.$dir;
        $tDir 	= PP_PATH;	//根目录
		$inc_file	= $sDir.'/tmp.inc';
		$adm_tmp	= explode('/', $_SERVER['SCRIPT_NAME']);
		$adminDir	= $adm_tmp[1];
		
		//先备份原模板目录
		$backup_dir = PP_PATH.'backup/';
		$theme_dir = PP_PATH.'nzcms/view/'.$this->_cfg['theme'].'/';
		kp_zip::zip($theme_dir, $backup_dir.$this->_cfg['theme'].'_'.date('YmdHis').'.zip');
		
		@copy($inc_file, RUNTIME_PATH.'tmp.inc');

		include RUNTIME_PATH.'tmp.inc';
		$filerr	= 0 ;
        if(isset($files) && is_array($files)){
            foreach($files as $f){
                if(substr($f,0,5)=='admin'){
                    $tf = preg_replace('#^admin#', $adminDir, $f);
                }else{
                    $tf = $f;
                }
                if(file_exists($sDir.'/'.$f) && $f!='tmp.inc' && $f!='date.sql'){
                    $rs = @copy($sDir.'/'.$f, $tDir.'/'.$tf);
                    if($rs){
						unlink($sDir.'/'.$f);
					}else{
                        $filerr++;
                    }
                }
            }
        }
		$filemsg = $sqlmsg = '';
        if($filerr > 0){
            $filemsg = "<br/>其中失败 ".$filerr." 个文件，请复制临时目录[".$adminDir."/".$dir."]中的文件覆盖到根目录。";
        }
		$sql_file	= ADM_PATH.$dir.'/date.sql';
		if(!empty($issql) && file_exists($sql_file)){
			$sql = file_get_contents($sql_file);
			if(!$this->sql_execute($sql)){
				$sqlmsg = "<br/>数据库文件恢复失败，请尝试用phpmyadmin执行[".$adminDir."/date.sql]中的语句。";
			}
		}

		//更新版本号
		$this->kv->xset('version', $version,'vip');
		$this->kv->xset('release', $release,'vip');
		$this->kv->save_changed();
		if($filerr < 1){
			_rmdir($sDir);
		}
		E(0, '成功完成升级，请手动清空缓存！'.$filemsg.$sqlmsg);
	}
	public function backup_bind() {
		_trim($_POST);
		$backup_theme = intval(R('backup_theme', 'P'));
		$this->kv->xset('backup_theme', $backup_theme,'vip');
		$this->kv->save_changed();
		E(0, '保存成功');
	}
	private function get_list(){
		if(empty($this->_vip['key'])) {
			return array();
		}
		$list	= array();
		$url 	= $this->_vip['api_url'].'?u=nzdown-upgrade_list-key-'.$this->_vip['_key'].'-version-'.$this->_vip('version').'-release-'.$this->_vip('release');
		$s 		= fetch_url($url, 5);
		if(empty($s)) exit();
		$list 	= (array)json_decode($s);
		if(!empty($list)) {
			exit();
		}
		return $list;
	}
	//copy from database
 	private function sql_execute($sql) {
	    $sqls = $this->sql_split($sql);
		if(is_array($sqls)) {
			foreach($sqls as $sql) {
				if(trim($sql) != '') {
					$this->db->query($sql);
				}
			}
		} else {
			$this->db->query($sqls);
		}
		return true;
	}
	private function sql_split($sql) {
		$tablepre	= $this->db->tablepre ;
		if($this->db->version() > '4.1') {
			$sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8",$sql);
		}
		//if($tablepre != "pre_")
		$sql = str_replace("`pre_", '`'.$tablepre, $sql);
		$sql = str_replace("\r", "\n", $sql);
		$ret = array();
		$num = 0;
		$queriesarray = explode(";\n", trim($sql));
		unset($sql);
		foreach($queriesarray as $query) {
			$ret[$num] = '';
			$queries = explode("\n", trim($query));
			$queries = array_filter($queries);
			foreach($queries as $query) {
				$str1 = substr($query, 0, 1);
				if($str1 != '#' && $str1 != '-') $ret[$num] .= $query;
			}
			$num++;
		}
		return($ret);
	}
}