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

if ($_GET['a'] == 'tianjia'){
    if (!varify_url($yuanchengurl)){
        $links[0]['title'] = '返回后台首页';
        $links[0]['href'] = $_admin_indexurl;
        showmsg("系统提醒", "互联网连接失败无法，请确定服务器可以链接互联网后再重试！", $links);
    }
	
	$_patchurl = $yuanchengurl.str_replace('-', '', CHARSET).'/list.txt';
	$pathlist_str = @file_get_contents($_patchurl);
	$pathlist_str = @mb_convert_encoding( $pathlist_str, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5' );
	
	$pathlist = array();
	$arrA = explode("--*--*--*--*--*--", $pathlist_str);
	foreach ($arrA as $key => $val) {
		if (!empty($val)) {
			$_arr = explode("|", trim($val));
			$_arr['count'] = $db->get_total("select COUNT(*) AS num from ".table('yingyong')." WHERE `name`='{$_arr[0]}'");
			$pathlist[$key] = $_arr;
		}
	}
	$smarty->assign('pathlist', $pathlist);
}

if ($_GET['a'] == 'az'){
	if ($admin_val['id']!='1') showmsg("系统提醒", "只有网站创始人才可以操作！");
    if (!varify_url($yuanchengurl)){
        $links[0]['title'] = '返回后台首页';
        $links[0]['href'] = $_admin_indexurl;
        showmsg("系统提醒", "互联网连接失败无法，请确定服务器可以链接互联网后再重试！", $links);
    }

	$row = $db->getone("select * from ".table('yingyong')." WHERE `name`='{$_GET['app']}'");
	if ($_GET['dosubmit']){
		//创建缓存文件夹
		if(!file_exists(KF_ROOT_PATH.'caches/caches_yingyong')) {
			@mkdir(KF_ROOT_PATH.'caches/caches_yingyong');
		}
		if ($_CFG['inwebway'] == '2'){
			kf_class::run_sys_class('pclzip','',0);
		}else{
			kf_class::run_sys_class('zip','',0);
		}
		if (!empty($row)){
			//远程升级列表
			$upgrade_path_base = $yuanchengurl.str_replace('-', '', CHARSET).'/'.$_GET['app'].'/';
			$pathlist_str = @file_get_contents($upgrade_path_base);
			$pathlist_str = @mb_convert_encoding( $pathlist_str, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5' );
			preg_match_all("/\"(up_[\w_]+\.zip)\"/", $pathlist_str, $allpathlist);
			$allpathlist = $allpathlist[1];
			if (empty($allpathlist)){
				$links[0]['title'] = '回我的应用';
				$links[0]['href'] = $_admin_indexurl."&amp;c=yingyong";
				$links[1]['title'] = '继续查看更多应用';
				$links[1]['href'] = $_admin_indexurl."&amp;c=yingyong&amp;a=tianjia";
				showmsg("系统提醒", "已经是最新版本无须更新！", $links);
			}
			foreach($allpathlist as $k=>$v) {
				$_v = intval(preg_replace("/up_(.+?)\.zip/is","\\1",$v));
				if ($_v > $row['v']){
					//远程压缩包地址
					$upgradezip_url = $yuanchengurl.str_replace('-', '', CHARSET).'/'.$_GET['app'].'/'.$v;
					//保存到本地地址
					$upgradezip_path = KF_ROOT_PATH.'caches/caches_yingyong'.DIRECTORY_SEPARATOR.$_GET['app'].'.zip';
					//解压路径
					$upgradezip_source_path = KF_ROOT_PATH.'caches/caches_yingyong'.DIRECTORY_SEPARATOR.$_GET['app'];
						
					//下载压缩包
					@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("系统提醒", "应用升级包{$_GET['app']}解压有".count($unevent[2])."个文件错误，请检查服务器是否支持zip扩展！<br/>建议：请稍后再试或到后台“网站配置”更改插件安装方式后再重试。");
						}
					}
					
					//检查插件
					$_infodata = array();
					$_infofile = $upgradezip_source_path.DIRECTORY_SEPARATOR.'info.php';
					if(file_exists($_infofile)) {
						@include($_infofile);
						$_infodata = $data;
					}
					if (empty($_infodata) || $_infodata['name'] != $_GET['app']){
						showmsg("系统提醒", "安装失败，可能应用包出错，请稍后再试！<br/>建议：请稍后再试或到后台“网站配置”更改插件安装方式后再重试。");
					}
						
					//拷贝文件到根目录
					$copy_from = $upgradezip_source_path.DIRECTORY_SEPARATOR.'upload'.DIRECTORY_SEPARATOR;
					$copy_to = KF_ROOT_PATH;
					$copyfailnum = copydir($copy_from, $copy_to, 1); //1覆盖
					//检查文件操作权限，是否复制成功
					if($copyfailnum > 0) {
						showmsg("系统提醒", "安装文件失败，请检查目录权限！");
					}

					//拷贝模板文件
					$copy_from = $upgradezip_source_path.DIRECTORY_SEPARATOR.'template'.DIRECTORY_SEPARATOR;
					$copy_to = KF_ROOT_PATH.'templates'.DIRECTORY_SEPARATOR.$_CFG['template_dir'];
					$copyfailnum = copydir($copy_from, $copy_to, 1); //1覆盖
					//检查文件操作权限，是否复制成功
					if($copyfailnum > 0) {
						showmsg("系统提醒", "安装文件失败，请检查模板目录权限！");
					}

					//执行sql
					//sql目录地址
					$sql_path = $upgradezip_source_path.DIRECTORY_SEPARATOR.'sql'.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])) {
									//获取数据库版本和编码
									$mysql_server_version = $db->dbversion();
									$dbcharset = $db->db_charset;
									$sqls = explode(';', $data);
									//执行sql升级
									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);
											$sqlv = str_replace('kf_', $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];
								}
							}
						}
					}
						
					//更新到应用列表
					$_arr = array();
					$_arr['v'] = $_infodata['v']?$_infodata['v']:$_v; //版本
					$_arr['uptime'] = SYS_TIME; //最后更新时间
					$_arr['setting'] = string2array($row['setting']);
					if ($_infodata['name']) $_arr['name'] = $_infodata['name']; //应用名(英文)
					if ($_infodata['title']) $_arr['title'] = $_infodata['title']; //应用名(中文)
					if ($_infodata['content']) $_arr['content'] = $_infodata['content']; //介绍
					if ($_infodata['database']) $_arr['setting']['database'] = $_infodata['database']; //所包含的数据表（卸载用）
					if ($_infodata['datafile']) $_arr['setting']['datafile'] = strinfo($_infodata['datafile']); //所包含的文件（卸载用）
					if ($_infodata['datamulu']) $_arr['setting']['datamulu'] = strinfo($_infodata['datamulu']); //所包含的目录（卸载用）
					if ($_infodata['dataphp']) $_arr['setting']['dataphp'] = strinfo($_infodata['dataphp']); //所包含的php执行文件（卸载用）
					if ($_infodata['dataurl']) $_arr['setting']['dataurl'] = $_infodata['dataurl']; //链接菜单
					$_arr['setting']['uplist'][$_arr['v']] = SYS_TIME; //已经升级过的版本
					$_arr['setting'] = array2string($_arr['setting']);
					updatetable(table('yingyong'), $_arr, "`id`=".$row['id']);
					//删除文件
					@unlink($upgradezip_path);
					//删除文件夹
					deletedir($upgradezip_source_path);
				}
			}
			$links[0]['title'] = '回我的应用';
			$links[0]['href'] = $_admin_indexurl."&amp;c=yingyong";
			$links[1]['title'] = '继续查看更多应用';
			$links[1]['href'] = $_admin_indexurl."&amp;c=yingyong&amp;a=tianjia";
			showmsg("系统提醒", "应用更新成功！", $links);
		}else{
			//远程压缩包地址
			$upgradezip_url = $yuanchengurl.str_replace('-', '', CHARSET).'/'.$_GET['app'].'/index.zip';
			//保存到本地地址
			$upgradezip_path = KF_ROOT_PATH.'caches/caches_yingyong'.DIRECTORY_SEPARATOR.$_GET['app'].'.zip';
			//解压路径
			$upgradezip_source_path = KF_ROOT_PATH.'caches/caches_yingyong'.DIRECTORY_SEPARATOR.$_GET['app'];

			//下载压缩包
			@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/>建议：请稍后再试或到后台“网站配置”更改插件安装方式后再重试。");
				}
			}
			
			//检查插件
			$_infodata = array();
			$_infofile = $upgradezip_source_path.DIRECTORY_SEPARATOR.'info.php';
			if(file_exists($_infofile)) {
				@include($_infofile);
				$_infodata = $data;
			}
			if (empty($_infodata) || $_infodata['name'] != $_GET['app']){
				showmsg("系统提醒", "安装失败，可能应用包出错，请稍后再试！<br/>建议：请稍后再试或到后台“网站配置”更改插件安装方式后再重试。");
			}
			
			//拷贝文件到根目录
			$copy_from = $upgradezip_source_path.DIRECTORY_SEPARATOR.'upload'.DIRECTORY_SEPARATOR;
			$copy_to = KF_ROOT_PATH;
			$copyfailnum = copydir($copy_from, $copy_to, 1); //1覆盖
			//检查文件操作权限，是否复制成功
			if($copyfailnum > 0) {
				showmsg("系统提醒", "安装文件失败，请检查目录权限！");
			}

			//拷贝模板文件
			$copy_from = $upgradezip_source_path.DIRECTORY_SEPARATOR.'template'.DIRECTORY_SEPARATOR;
			$copy_to = KF_ROOT_PATH.'templates'.DIRECTORY_SEPARATOR.$_CFG['template_dir'];
			$copyfailnum = copydir($copy_from, $copy_to, 1); //1覆盖
			//检查文件操作权限，是否复制成功
			if($copyfailnum > 0) {
				showmsg("系统提醒", "安装文件失败，请检查模板目录权限！");
			}
			
			//执行sql
			//sql目录地址
			$sql_path = $upgradezip_source_path.DIRECTORY_SEPARATOR.'sql'.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])) {
							//获取数据库版本和编码
							$mysql_server_version = $db->dbversion();
							$dbcharset = $db->db_charset;
							$sqls = explode(';', $data);
							//执行sql升级
							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);
									$sqlv = str_replace('kf_', $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];
						}
					}
				}
			}
			
			//添加到应用列表
			$_arr = array();
			$_arr['name'] = $_infodata['name']; //应用名(英文)
			$_arr['title'] = $_infodata['title']; //应用名(中文)
			$_arr['content'] = $_infodata['content']; //介绍
			$_arr['v'] = $_infodata['v']; //版本
			$_arr['intime'] = SYS_TIME; //安装时间
			$_arr['setting']['database'] = $_infodata['database']; //所包含的数据表（卸载用）
			$_arr['setting']['datafile'] = strinfo($_infodata['datafile']); //所包含的文件（卸载用）
			$_arr['setting']['datamulu'] = strinfo($_infodata['datamulu']); //所包含的目录（卸载用）
			$_arr['setting']['dataphp'] = strinfo($_infodata['dataphp']); //所包含的php执行文件（卸载用）
			$_arr['setting']['dataurl'] = $_infodata['dataurl']; //链接菜单
			$_arr['setting']['uplist'][$_arr['v']] = SYS_TIME; //版本安装历史时间
			$_arr['setting'] = array2string($_arr['setting']);
			inserttable(table('yingyong'), $_arr);
			//删除文件
			@unlink($upgradezip_path);
			//删除文件夹
			deletedir($upgradezip_source_path);
			$links[0]['title'] = '回我的应用';
			$links[0]['href'] = $_admin_indexurl."&amp;c=yingyong";
			$links[1]['title'] = '继续安装更多应用';
			$links[1]['href'] = $_admin_indexurl."&amp;c=yingyong&amp;a=tianjia";
			showmsg("系统提醒", "应用安装成功！", $links);
							
			
		}
	}else{
		if (!empty($row)){
			//远程升级列表
			$upgrade_path_base = $yuanchengurl.str_replace('-', '', CHARSET).'/'.$_GET['app'].'/';
			$pathlist_str = @file_get_contents($upgrade_path_base);
			$pathlist_str = @mb_convert_encoding( $pathlist_str, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5' );
			preg_match_all("/\"(up_[\w_]+\.zip)\"/", $pathlist_str, $allpathlist);
			$allpathlist = $allpathlist[1];
			$noup = 0;
			if (!empty($allpathlist)){
				foreach($allpathlist as $k=>$v) {
					$_v = intval(preg_replace("/up_(.+?)\.zip/is","\\1",$v));
					if ($_v > $row['v']){
						$noup = 1; break;
					}
				}
			}
			if ($noup == 0){
				$links[0]['title'] = '回我的应用';
				$links[0]['href'] = $_admin_indexurl."&amp;c=yingyong";
				$links[1]['title'] = '返回来源地址';
				$links[1]['href'] = -1;
				showmsg("系统提醒", "已经是最新版本无须更新！", $links);
			}else{
				$links[0]['title'] = '立即升级';
				$links[0]['href'] = get_link()."&amp;dosubmit=1";
				$links[1]['title'] = '返回来源地址';
				$links[1]['href'] = -1;
				showmsg("系统提醒", "检测到新版本是否现在升级？", $links);
			}
		}else{
			$links[0]['title'] = '确定安装';
			$links[0]['href'] = get_link()."&amp;dosubmit=1";
			$links[1]['title'] = '返回来源地址';
			$links[1]['href'] = -1;
			showmsg("系统提醒", "确定安装此应用吗？", $links);
		}
	}
}


if ($_GET['a'] == 'del'){
	if ($admin_val['id']!='1') showmsg("系统提醒", "只有网站创始人才可以操作！");
	$row = $db->getone("select * from ".table('yingyong')." WHERE `name`='{$_GET['app']}'");
	if (empty($row)){
		showmsg("系统提醒", "应用不存在或还没有安装！");
	}
	
	if ($_GET['dosubmit']){
		$_setting = string2array($row['setting']);
		//删除数据库
		$_setting['database'] = explode(",", $_setting['database']);
		if (!empty($_setting['database'])){
			foreach ($_setting['database'] as $val){
				$db->query("DROP TABLE IF EXISTS `".table($val)."`");
			}
		}
		//执行php文件
		$_setting['dataphp'] = str_replace("|", DIRECTORY_SEPARATOR, $_setting['dataphp']);
		$_setting['dataphp'] = explode(",", $_setting['dataphp']);
		foreach ($_setting['dataphp'] as $val){
            if (file_exists(KF_ROOT_PATH.$val)) @include KF_ROOT_PATH.$val;
		}
		//删除文件
		$_setting['datafile'] = str_replace("|", DIRECTORY_SEPARATOR, $_setting['datafile']);
		$_setting['datafile'] = explode(",", $_setting['datafile']);
		foreach ($_setting['datafile'] as $val){
			if (file_exists(KF_ROOT_PATH.$val)) @unlink(KF_ROOT_PATH.$val);
		}
		if ($_CFG['inwebway'] == '2'){
			kf_class::run_sys_class('pclzip','',0);
		}else{
			kf_class::run_sys_class('zip','',0);
		}
		//删除文件夹
		$_setting['datamulu'] = str_replace("|", DIRECTORY_SEPARATOR, $_setting['datamulu']);
		$_setting['datamulu'] = explode(",", $_setting['datamulu']);
		foreach ($_setting['datamulu'] as $val){
			if (file_exists(KF_ROOT_PATH.$val) && strlen(trim($val))>3) deletedir(KF_ROOT_PATH.$val);
		}
		//删除应用信息
		$db->query("Delete from ".table('yingyong')." WHERE `id`=".$row['id']);
		//
		$links[0]['title'] = '回我的应用';
		$links[0]['href'] = $_admin_indexurl."&amp;c=yingyong";
		showmsg("系统提醒", "删除成功！", $links);
	}else{
		$links[0]['title'] = '确定删除';
		$links[0]['href'] = get_link()."&amp;dosubmit=1";
		$links[1]['title'] = '返回来源地址';
		$links[1]['href'] = -1;
		showmsg("系统提醒", "确定删除此应用和它所包含的所有数据及文件且不可恢复吗？", $links);
	}
}

/*
 ************************************************************************************************
 ************************************************************************************************
 * 函数部分
 */
function strinfo($str){
	global $_CFG;
	$str = str_replace("{t}", 'templates'.DIRECTORY_SEPARATOR.$_CFG['template_dir'], $str);
	$str = str_replace(array(DIRECTORY_SEPARATOR, "\\", "/"), "|", $str);
	return $str;
}
function appurl($str){
	global $_CFG;
	$domainurl = $_CFG['site_domain'].$_CFG['site_dir'];
  if ($_CFG['admin_url']){
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $domainurl = $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$_CFG['site_dir'];
  }
	$str = str_replace("{url}", $domainurl, $str);
	$str = str_replace("{allow}", $_GET['allow'], $str);
	$str = str_replace("{vs}", $_GET['vs'], $str);
	$str = str_replace("{sid}", $_GET['sid'], $str);
	$str = str_replace("{m}", $_GET['m'], $str);
	$str = str_replace("{c}", $_GET['c'], $str);
	$str = str_replace("{a}", $_GET['a'], $str);
	$str = str_replace("&amp;", "&", $str);
	$str = str_replace("&", "&amp;", $str);
	return $str;
}
?>