<?php
/*
 * 版本升级
 * ============================================================================
 * 版权所有: 快范网络，并保留所有权利。
 * 网站地址: http://www.kuaifan.net；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 */
if(!defined('IN_KUAIFAN')) exit('Access Denied!');


if ($_GET['a'] == 'peizhi'){
	if ($_POST['dosubmit']){
		$links[0]['title'] = '返回继续';
		$links[0]['href'] = get_link("dosubmit");
		$links[1]['title'] = '返回在线升级';
		$links[1]['href'] = get_link("dosubmit|auto");
		$links[2]['title'] = '返回后台首页';
		$links[2]['href'] = $_admin_indexurl;
		!$db->query("UPDATE ".table('peizhi')." SET value='".intval($_POST['shengjiauto'])."' WHERE name='shengjiauto'")?showmsg("系统提醒", "保存失败！", $links):"";
		$db->query("UPDATE ".table('peizhi')." SET value='".$timestamp."' WHERE name='shengjiauto_time'");
		refresh_cache('peizhi');
		showmsg("系统提醒", "保存成功！", $links);
	}
}else{
  kf_class::run_sys_func('ubb');
	$system_info = array();
	$system_info['version'] = KUAIFAN_VERSION;
	$system_info['release'] = KUAIFAN_RELEASE;
	//md5验证地址
	$_upgrademd5 = 'http://www.kuaifan.net/upgrademd5/';
	//补丁地址
	$_patchurl = 'http://download.kuaifan.net/patch/v'.KUAIFAN_VERSION.'/';

	$patch_charset = str_replace('-', '', CHARSET);
	$upgrade_path_base = $_patchurl.$patch_charset.'/';
	$pathlist_str = @file_get_contents($upgrade_path_base);
	$pathlist = $allpathlist = array();
	$key = -1;
	//获取压缩包列表
	preg_match_all("/\"(patch_[\w_]+\.zip)\"/", $pathlist_str, $allpathlist);
	$allpathlist = $allpathlist[1];
	//获取说明文件列表
	preg_match_all("/\"(patch_[\w_]+\.txt)\"/", $pathlist_str, $allpathlist_txt);
	$allpathlist_txt = $allpathlist_txt[1];
	//获取可供当前版本升级的压缩包
	foreach($allpathlist as $k=>$v) {
		if(strstr($v, 'patch_'.$system_info['release'])) {
			$key = $k;
			break;
		}
	}
	$key = $key < 0 ? 9999 : $key; $_n = 1;
	foreach($allpathlist as $k=>$v) {
		if($k >= $key) {
			$pathlist[$k]['n'] = $_n;
			$pathlist[$k]['name'] = $v;
			$pathlist[$k]['txt'] = substr($pathlist[$k]['name'], 0, -4).'.txt';
			if (in_array($pathlist[$k]['txt'], $allpathlist_txt)){
				$pathlist[$k]['txt'] = @file_get_contents($upgrade_path_base.$pathlist[$k]['txt']);
				$pathlist[$k]['txt'] = @mb_convert_encoding( $pathlist[$k]['txt'], 'UTF-8', 'UTF-8,GBK,GB2312,BIG5' );
				$pathlist[$k]['txt'] = str_replace(array("\r\n", "\n", "\r"), "[br]", $pathlist[$k]['txt']);
			}else{
				$pathlist[$k]['txt'] = "";
			}
			$_n++;
		}
	}
	$smarty->assign('pathlist', $pathlist);
	$smarty->assign('system_info', $system_info);
	$smarty->assign('upgrade_path_base', $upgrade_path_base);
}
//开始升级
if ($_GET['dosubmit']){
	if ($admin_val['id']!='1') showmsg("系统提醒", "只有网站创始人才可以操作！");
	$links[0]['title'] = '返回页面';
	$links[0]['href'] = get_link("do|dosubmit|tid");
	$links[1]['title'] = '返回后台首页';
	$links[1]['href'] = $_admin_indexurl;
	if(empty($_GET['do'])) {
		showmsg("系统提醒", "正在自动进入升级。", $links, get_link("do|tid").'&amp;do=1');
	}else{
		//检查服务器是否支持zip
		if(empty($pathlist)) {
			showmsg("系统提醒", "升级成功，建议您<a href='".$_admin_indexurl."&amp;c=huancun'>更新一下缓存</a>！", $links);
		}
		//创建缓存文件夹
		if(!file_exists(KF_ROOT_PATH.'caches/caches_upgrade')) {
			@mkdir(KF_ROOT_PATH.'caches/caches_upgrade');
		}
		//根据版本下载zip升级包，解压覆盖
		if ($_CFG['inwebway'] == '2'){
			kf_class::run_sys_class('pclzip','',0);
		}else{
			kf_class::run_sys_class('zip','',0);
		}
		
		foreach($pathlist as $k=>$_v) {
			$v = $_v['name'];
			//远程压缩包地址
			$upgradezip_url = $upgrade_path_base.$v;
			//保存到本地地址
			$upgradezip_path = KF_ROOT_PATH.'caches/caches_upgrade'.DIRECTORY_SEPARATOR.$v;
			//解压路径
			$upgradezip_source_path = KF_ROOT_PATH.'caches/caches_upgrade'.DIRECTORY_SEPARATOR.basename($v,".zip");

			//下载压缩包
			@file_put_contents($upgradezip_path, @file_get_contents($upgradezip_url));
			
			//解压缩
			if ($_CFG['inwebway'] == '2'){
				$archive = new PclZip($upgradezip_path);
				if($archive->extract(PCLZIP_OPT_PATH, $upgradezip_source_path, PCLZIP_OPT_REPLACE_NEWER) == 0) {
					showmsg("系统提醒", "升级失败：".$archive->errorInfo(true)."<br/>建议：请稍后再试或到后台“网站配置”更改升级方式后再重试。");
				}
			}else{
				$archive = new PHPZip();
				$unevent = $archive -> unZipfun($upgradezip_path, $upgradezip_source_path);
				if (count($unevent[2]) > 0){
					showmsg("系统提醒", "升级包{$v}解压有".count($unevent[2])."个文件错误，请检查服务器是否支持zip扩展！<br/>建议：请稍后再试或到后台“网站配置”更改升级方式后再重试。");
				}
			}
			//配置文件地址
			$configpath = KF_ROOT_PATH.'caches/caches_upgrade'.DIRECTORY_SEPARATOR.basename($v,".zip").DIRECTORY_SEPARATOR.$patch_charset.DIRECTORY_SEPARATOR.'upgrade'.DIRECTORY_SEPARATOR.'config.php';
			if(file_exists($configpath)) {
				$config_arr = include $configpath;
				if (empty($config_arr['to_release'])){
					showmsg("系统提醒", "升级失败，可能升级包出错，请稍后再试！err:-1<br/>建议：请稍后再试或到后台“网站配置”更改插件安装方式后再重试。");
				}
			}else{
				showmsg("系统提醒", "升级失败，可能升级包出错，请稍后再试！err:-2<br/>建议：请稍后再试或到后台“网站配置”更改插件安装方式后再重试。");
			}

			//拷贝utf8/upload文件夹到根目录
			$copy_from = $upgradezip_source_path.DIRECTORY_SEPARATOR.$patch_charset.DIRECTORY_SEPARATOR.'upload'.DIRECTORY_SEPARATOR;
			$copy_to = KF_ROOT_PATH;

			$copyfailnum = copydir($copy_from, $copy_to, 1); //1覆盖模板

			//检查文件操作权限，是否复制成功
			if($copyfailnum > 0) {
				//如果失败，恢复当前版本
				@file_put_contents(KF_ROOT_PATH.'caches'.DIRECTORY_SEPARATOR.'version.php', '<?php return '.var_export($current_version, true).';?>');

				showmsg("系统提醒", "复制文件失败，请检查目录权限！", $links);
			}

			//执行sql
			//sql目录地址
			$sql_path = KF_ROOT_PATH.'caches/caches_upgrade'.DIRECTORY_SEPARATOR.basename($v,".zip").DIRECTORY_SEPARATOR.$patch_charset.DIRECTORY_SEPARATOR.'upgrade'.DIRECTORY_SEPARATOR.'ext'.DIRECTORY_SEPARATOR;
			$file_list = glob($sql_path.'*');
			if(!empty($file_list)) {
				foreach ($file_list as $fk=>$fv) {
					if(in_array(strtolower(substr($fv, -3, 3)), array('sql', 'php'))) {
            if (strtolower(substr($file_list[$fk], -3, 3)) == 'sql' && $data = file_get_contents($file_list[$fk])) {
              $base_filename = basename($fv);
              $model_name = substr($base_filename, 0, -4);
              //检查表是否存在
              if (mysql_query("show tables like '".table($model_name)."'")) {
                //获取数据库版本和编码
                $mysql_server_version = $db->dbversion();
                $dbcharset = $db->db_charset;
                //执行sql升级
                $sqls = explode(';', $data);
                foreach ($sqls as $sqlv) {
                  if (empty($sqlv)) continue;
                  if(mysql_get_server_info > '4.1' && $dbcharset) {
                    $sqlv = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=".str_replace("-","",$dbcharset),$sqlv);
                    $sqlv = str_replace('$kuaifan$', $pre, $sqlv);
                  }
                  if (trim($sqlv)) $db->query(trim($sqlv));
                }
              }
						} elseif (strtolower(substr($file_list[$fk], -3, 3)) == 'php' && file_exists($file_list[$fk])) {
              include $file_list[$fk];
						}
					}
				}			
			}
			//读取版本号写入version.php文件
			$version_arr = "<?php
					if(!defined('IN_KUAIFAN'))die('Access Denied!');
					define('KUAIFAN_VERSION','{$config_arr['to_version']}');
					define('KUAIFAN_RELEASE', '{$config_arr['to_release']}');
				?>";
			//版本文件地址
			@file_put_contents(KF_ROOT_PATH.'include'.DIRECTORY_SEPARATOR.'kfcms_version.php', $version_arr);

			//删除文件
			@unlink($upgradezip_path);
			//删除文件夹
			deletedir($upgradezip_source_path);
				
			//提示语
			$tmp_k = $k + 1;
			if(!empty($pathlist[$tmp_k]['name'])) {
				$next_update = '<br/>正在升级: '.basename($pathlist[$tmp_k]['name'],".zip");
			} else {
				$next_update;
			}
			//文件校验是否升级成功
			admin_log(basename($v,".zip").'升级成功', $admin_val['name']);
			$smarty->force_compile = true;
			showmsg("系统提醒", basename($v,".zip").'升级成功！'.$next_update, $links, get_link("tid").'&amp;tid='.$timestamp);
		}
	}
}

?>