<?php
/*******************************************************************
 * 版权协议：2009-2019
 * 版权所有: PHP-北京金南曦网络技术有限公司旗下PHPWMS，PHP商城系统技术支持中心http://www.php188.net，并保留所有权利。 
 * PHP商城系统网址: http://www.php188.com
 * PHPWMS系统网址：http://www.phpwms.com
 * 销售电话：010-87875088
 * 销售电话：010-87875188 
*------------------------------------------------------------------
 * 这不是一个完全免费软件！您只能在不用于商业目的的前提下对程序代码进
 * 行修改和使用；不允许对程序代码以任何形式任何目的的再发布。
 *------------------------------------------------------------------
 * 文件名称：install.php
 * 摘　　要：安装
 * 适用范围：PHPWMS 1.0
 * 版　　本：1.0
 *------------------------------------------------------------------
 * Script Written By phpwms项目组
 * 最后更新： 2009-09-24 phpwms 由PHP金南曦网络技术有限公司整理发布
 *******************************************************************/

if(!function_exists('dump')){
	function dump($str,$dump = false,$echo = true,$char = 'GBK'){
		@ob_start();
		@header("Content-Type:text/html;charset=\"$char\"");
		echo '<pre style="text-algin:left;">';
		if($dump)var_dump($str);else print_r($str);
		echo '</pre>';
		$out =  ob_get_contents();
		ob_end_clean();
		if($echo){
			echo $out;
		}else{
			return $out;
		}
		return NULL;
   	}
}
error_reporting(0);
$curent_root = explode('/',strtr(dirname(__FILE__),array('\\'=>'/')));
array_pop($curent_root);
$root_path = join('/',$curent_root).'/';
define('SYS_ROOT',$root_path);
if(file_exists(SYS_ROOT.'data/install.lock'))exit('您已经安装 了本系统,若需重新安装请删除data/install.lock文件');
include(SYS_ROOT.'pub/phpwms.common.fun.php');
	session_start();
	define('IN_SYS',true);
	$sys_dir = str_replace('\\','/',dirname(__FILE__)).'/';
	if(strstr($sys_dir,':')){
		$tmp = explode(':',$sys_dir);
		$sys_dir = $tmp[1];
	}
	define('SYS_DIR',$sys_dir);
	define('TPL_PATH',SYS_ROOT.'include/tpl/');
	define('CLASS_PATH',SYS_ROOT.'include/classes/');
	require(TPL_PATH.'Smarty.class.php');
	require(CLASS_PATH.'cls.data_check.php');
	$step = intval($_REQUEST['step']);
	$do	  = trim($_REQUEST['do']);
	$tpl  = new Smarty();
	$path = SYS_ROOT.'/cache/install/';	
	if(!file_exists($path)){
		createDir($path);
	}
	$tpl  -> compile_dir  = $path;
	$tpl  -> template_dir = str_replace('\\','/',dirname(__FILE__)) .'/tpl';
	$tpl -> assign("step",$step);
	$tpl -> assign("sys_name",'PHPWMS简易安装向导');
	$tpl -> assign("page_name",'阅读许可协议');
	$php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF']:$_SERVER['SCRIPT_NAME'];
	$root_dir = preg_replace("/\/+(api|archiver|wap)?\/*$/i",'',substr($php_self,0,strrpos($php_self,'/'))).'/';
	if($step == 1) {
		$tpl -> assign("page_name",'第一步：安装环境检测');
		$checking_dirs = array(
							SYS_ROOT.'',
							SYS_ROOT.'data/',
							SYS_ROOT.'files/',
							SYS_ROOT.'template/',
							SYS_ROOT.'cache/',
							 );

		$dirs_priv = check_dirs_priv($checking_dirs);
		$sys_info  = get_system_info();
		$tpl -> assign('result',$dirs_priv['result']);
		$tpl -> assign('detail',$dirs_priv['detail']);
		$tpl -> assign('sys_info',$sys_info);
	}
	if($step == 2) {
		$tpl -> assign("page_name",'第二步：选择系统语言');
		$_SESSION ['sys_lan'] = trim ( $_REQUEST ['slang'] );
		if($_SESSION ['sys_lan'])header('Location:?step=3');//如果 $_sssion 有值 跳转
	}
	if($step == 3) {
		$tpl -> assign("page_name",'第三步：填写数据库信息');		
		$dbtype	   = array('mysql');
		$dbcharset = array('gbk');
		$tpl -> assign('dbtype',$dbtype);
		$tpl -> assign('dbcharset',$dbcharset);
		$db_arr = $_SESSION['db_arr'];
		empty($db_arr['dbtype'])    and $db_arr['dbtype']    = 'mysql';
		empty($db_arr['dbcharset']) and $db_arr['dbcharset'] = 'gbk';
		empty($db_arr['dbhost'])    and $db_arr['dbhost']    = 'localhost';
		empty($db_arr['dbport'])    and $db_arr['dbport']    = '3306';
		empty($db_arr['dbuser'])    and $db_arr['dbuser']    = 'root';
		empty($db_arr['tbprefix'])  and $db_arr['tbprefix']  = 'pw_';
		$tpl -> assign('db_arr',$db_arr);
		$do and $flag =  setData($do);
		$flag and header('Location:?step=4&do=create_db');
	}
	if($step == 4) {
		$tpl -> assign("page_name",'第四步：创建数据库');
		include(SYS_ROOT.'config.inc.php');
		include(SYS_ROOT.'install/sql.php');
		include(SYS_ROOT.'include/classes/cls.db_mysql.php');
		$tpl -> assign("tab_list",array_keys($sql_arr));
		$sql_db = 'Db'.ucwords(strtolower($dbtype));
		$db	= new $sql_db;
		$db -> sql_connect($dbhost,$dbuser,$dbpwd,$dbname,$dbport, false, false);
		$do and $flag = setData($do);
		if($flag){
			$create_state = "OK";
		} else {
			$create_state = "ERROR";
		}
		
		$tpl -> assign("create_state",$create_state);
	}

	if($step == 5) {
		include(SYS_ROOT.'config.inc.php');
		include(SYS_ROOT.'include/classes/cls.db_'.$dbtype.'.php');
		$sql_db = 'Db'.ucwords(strtolower($dbtype));
		$db	= new $sql_db;
		$db -> sql_connect($dbhost,$dbuser,$dbpwd,$dbname,$dbport, false, false);
		$tpl -> assign("page_name",'第五步：设置系统管理员');
		
		$do and $flag = setData($do);
		$flag and header('Location:?step=6');
	}

	if($step == 6) {
		include(SYS_ROOT.'config.inc.php');
		$tpl -> assign("page_name",'安装完成');
		$tpl -> assign("root_dir",$root_dir);
		$tpl -> assign("admin_dir",$admin_dir);
		// 创建文件
		create_file('http://www.php188.com',SYS_ROOT . '/data/install.lock');
	}
	
	$tpl -> display('install.tpl');
	
function setData($do) {
	global $root_dir;
	$do = strtolower ( $do );
	$flag = false;
	switch ($do) {
		case 'set_lan' :
			$_SESSION ['sys_lan'] = trim ( $_REQUEST ['slang'] );
			$_SESSION ['sys_lan'] and $flag = true;
			break;
		case 'chk_db' :
			$db_arr = $_REQUEST ['db'];
			$_SESSION ['db_arr'] = $db_arr;
			$dbhost = $db_arr ['dbhost'] . ':' . $db_arr ['dbport'];
			//暂时没有考虑其他的数据库
			$conn = @mysql_connect ( $dbhost, $db_arr ['dbuser'], $db_arr ['dbpwd'] );
			if ($conn === false) {
				$flag = false;
				print ( '<script>alert("无法连接数据库!");history.go(-1);</script>' );
				exit();
			} else {
				$flag = true;
			}
			if (isset ( $db_arr ['isnew'] )) {
				$db_charset = trim ( $db_arr ['dbcharset'] );
				if (! empty ( $db_charset ) && version_compare ( mysql_get_server_info ( $conn ), '4.1.3', '>=' )) {
					$create_sql = 'CREATE DATABASE ' . $db_arr ['dbname'] . ' DEFAULT CHARACTER SET ' . $db_charset;
				} else {
					$create_sql = 'CREATE DATABASE ' . $db_arr ['dbname'];
				}
				$create_sql = 'CREATE DATABASE ' . $db_arr ['dbname'] . ' DEFAULT CHARACTER SET ' . $db_charset;
				if (mysql_query ( $create_sql, $conn )) {
					$flag = true;
				} else {
					$flag = false;
					print ( '<script>alert("创建数据库失败，可能权限不足或者库已存在，请指定一个已创建好的数据库!");history.go(-1);</script>' );
				}
			}
			if (mysql_select_db ( $db_arr ['dbname'], $conn ) === false) {
				$flag = false;
				print ( '<script>alert("数据库[' . $db_arr ['dbname'] . ']不存在,请先创建!");history.go(-1);</script>' );
			} else {
				$flag = true;
			}
			if ($flag) {
				// 开始写配置文件
				$config = file_get_contents(SYS_ROOT . '/install/config.txt');
				$letters = array(
								'php188_db_host',
								'php188_db_port',
								'php188_db_user',
								'php188_db_password',
								'php188_db_name',
								'php188_db_prefix',
								'php188_db_char',
							);
				// 替换为 和上边对应的值
				$fruit = array(
					$db_arr['dbhost'],// db_host,
					$db_arr['dbport'],//$db_port,
					$db_arr['dbuser'],//$db_user,
					$db_arr['dbpwd'],//$db_pass,
					$db_arr['dbname'],//$db_name,
					$db_arr['tbprefix'],//$db_prefix,
					$db_arr['dbcharset'],//$php188_db_char,
				);
				// 开始查找替换
				$config = "<?php\r\n" . str_replace($letters, $fruit, $config) . " \r\n ?>";
				$flag = create_file($config,SYS_ROOT . '/config.inc.php');
			}
			break;
		case 'create_db' :
			global $db, $tpl, $sql_arr, $dbcharset, $tbprefix;
			$info = '';
			$tab_list = array_keys ( $sql_arr );
			foreach ( $tab_list as $sql_table_name ) {
				$info .= createTab ( $db, $sql_table_name );
				$tpl->assign ( 'create_info', $info );
			}
			// 创建表完成
			// 读取 默认数据
			$sql_default_data = file_get_contents(SYS_ROOT . '/install/sql/default_data.sql');
			$sql_default_data = str_replace(' `pw_', ' `' . $tbprefix, $sql_default_data);
			$sql_default_arr = split(";[\r\n]", $sql_default_data);
			
			foreach ($sql_default_arr as $sql){
				$sql = trim($sql);
				if(empty($sql)){
					continue;
				}
				$db->sql_query ( $sql );
			}
			/*读取测试数据*/
			$sql_test_data = file_get_contents(SYS_ROOT . '/install/sql/test_data.sql');
			$sql_test_data = str_replace(' `pw_', ' `' . $tbprefix, $sql_test_data);
			$sql_test_arr = split(";[\r\n]", $sql_test_data);
			
			foreach ($sql_test_arr as $sql){
				$sql = trim($sql);
				if(empty($sql)){
					continue;
				}
				$db->sql_query ( $sql );
			}
			$db->sql_close ();
			/*开始移动文件*/
			$path = SYS_ROOT . 'install/install_data/';
			cpdir($path, SYS_ROOT, true);
			$flag = true;
			break;
		case 'set_adminuser' :
			global $db, $dc, $tbprefix;
			$admin = $_REQUEST ['admin'];
			if (strlen ( $admin ['admin_user'] ) > 0) {
				if ($admin ['admin_pwd'] !== $admin ['re_pwd']) {
					print ( '<script>alert("两次输入的密码不一样，请重新输入");window.location="install.php?step=5";</script>' );
					exit ();
				}
			} else {
				$admin ['admin_user'] = 'admin';
				$admin ['admin_pwd'] = 'admin123456';
			}
			$admin ['admin_pwd'] = md5 ( $admin ['admin_pwd'] );
			$admin ['last_login'] = date ( 'Y-m-d H:i:s' );
			$admin ['last_login_ip'] = getRealIp ();
			$admin ['add_user'] = '初始安装人员';
			$admin['is_orgin'] = '1';
			$admin ['add_time'] = date ( 'Y-m-d H:i:s' );
			$admin ['pri_config'] = $admin ['flag'] = '999';
			
			unset ( $admin ['re_pwd'] );
			$exist = "SELECT count(*) total FROM " . $tbprefix . "admin WHERE admin_user = '" . trim ( $admin ['admin_user'] ) . "'";
			
			$re = $db->sql_query ( $exist );
			$arr = $db->sql_fetchrow ( $re );
			if (intval ( $arr ['total'] ) < 1) {
				$sql = 'INSERT INTO ' . $tbprefix . 'admin ' . $db->sql_build_array ( 'INSERT', $admin );
			} else {
				$sql = 'UPDATE ' . $tbprefix . 'admin SET ' . $db->sql_build_array ( 'UPDATE', $admin );
			}
			$re = $db->query( $sql );
			$url = get_site_url(FALSE);
			$host ='http://'.array_shift(explode('/install/',$url)).'/';
			$qd = array(
				'sys_name'=>'phpwms测试站点',
				'sys_url'=>$host,
				'sys_onoff'=>'0',
				'show_debug'=>'1',
				'off_reason'=>'系统维护中...'
			);
			$i_data = array(
				's_name'=>'siteBase',
				's_data'=>serialize_deep($qd),
			);
			$db->insert($i_data,'core_setting');
			$flag = $re;
			break;
	}
	return $flag;
}
function createTab(&$db, $tab_name, $dbcharset = 'GBK') {
	$sql = getSql ( $tab_name );
	$db->sql_query ( "DROP TABLE IF EXISTS " . $tab_name );
	$re = $db->sql_query ( $sql );
	if ($re) {
		$state = '<font color=green>成功</font>';
	} else {
		$state = '<font color=red>失败</font>';
	}
	$result = '<script language="javascript">dbInfo("' . $tab_name . '","创建表[ <font color=blue>' . $tab_name . '</font> ] ......................................... ' . $state . '");</script>';
	return $result;
}
	
function getSql($tab_name) {
		global $sql_arr;
		if (array_key_exists ( $tab_name, $sql_arr )) {
			return $sql_arr [$tab_name];
		}
	}
	
function check_dirs_priv($checking_dirs) {
	global $sql_arr;
	$msgs = array ('result' => 'OK', 'detail' => array () );
	foreach ( $checking_dirs as $dir ) {
		if (! file_exists ($dir )) {
			$msgs ['result'] = 'ERROR';
			$msgs ['detail'] [] = array ($dir, '不存在' );
			continue;
		}
		$mod = substr(sprintf('%o', fileperms($dir)), -4);
		if($false && $mod!='0777'){
			$msgs ['result'] = 'ERROR';
			$msgs ['detail'] [] = array ($dir, '不可写' );
		}else{
			$msgs ['detail'] [] = array ($dir, '可写' );
		}
	
	}
	return $msgs;
}
	
	// 获得系统的信息
	function get_system_info() {
		$system_info = array ();
		
		/* 检查系统基本参数 */
		$system_info [] = array ('操作系统', PHP_OS );
		$system_info [] = array ('PHP 版本', PHP_VERSION );
		
		/* 检查MYSQL支持情况 */
		$mysql_enabled = function_exists ( 'mysql_connect' ) ? '支持' : '不支持';
		$system_info [] = array ('是否支持MySQL', $mysql_enabled );
		
		/* 检查图片处理函数库 */
		$gd_ver = gd_version ();
		$gd_ver = empty ( $gd_ver ) ? '不支持' : $gd_ver;
		if ($gd_ver > 0) {
			if (PHP_VERSION >= '4.3' && function_exists ( 'gd_info' )) {
				$gd_info = gd_info ();
				$jpeg_enabled = ($gd_info ['JPG Support'] === true) ? '支持' : '不支持';
				$gif_enabled = ($gd_info ['GIF Create Support'] === true) ? '支持' : '不支持';
				$png_enabled = ($gd_info ['PNG Support'] === true) ? '支持' : '不支持';
			} else {
				if (function_exists ( 'imagetypes' )) {
					$jpeg_enabled = ((imagetypes () & IMG_JPG) > 0) ? '支持' : '不支持';
					$gif_enabled = ((imagetypes () & IMG_GIF) > 0) ? '支持' : '不支持';
					$png_enabled = ((imagetypes () & IMG_PNG) > 0) ? '支持' : '不支持';
				} else {
					$jpeg_enabled = '不支持';
					$gif_enabled = '不支持';
					$png_enabled = '不支持';
				}
			}
		} else {
			$jpeg_enabled = '不支持';
			$gif_enabled = '不支持';
			$png_enabled = '不支持';
		}
		$system_info [] = array ('GD 版本', $gd_ver );
		$system_info [] = array ('是否支持 JPEG', $jpeg_enabled );
		$system_info [] = array ('是否支持 GIF', $gif_enabled );
		$system_info [] = array ('是否支持 PNG', $png_enabled );
		
		/* 服务器是否安全模式开启 */
		$safe_mode = ini_get ( 'safe_mode' ) == '1' ? '开启' : '关闭';
		$system_info [] = array ('服务器是否开启安全模式', $safe_mode );
		
		return $system_info;
	}
function gd_version() {
	static $version = - 1;
	
	if ($version >= 0) {
		return $version;
	}
	
	if (! extension_loaded ( 'gd' )) {
		$version = 0;
	} else {
		// 尝试使用gd_info函数
		if (PHP_VERSION >= '4.3') {
			if (function_exists ( 'gd_info' )) {
				$ver_info = gd_info ();
				preg_match ( '/\d/', $ver_info ['GD Version'], $match );
				$version = $match [0];
			} else {
				if (function_exists ( 'imagecreatetruecolor' )) {
					$version = 2;
				} elseif (function_exists ( 'imagecreate' )) {
					$version = 1;
				}
			}
		} else {
			if (preg_match ( '/phpinfo/', ini_get ( 'disable_functions' ) )) {
				/* 如果phpinfo被禁用，无法确定gd版本 */
				$version = 1;
			} else {
				// 使用phpinfo函数
				ob_start ();
				phpinfo ( 8 );
				$info = ob_get_contents ();
				ob_end_clean ();
				$info = stristr ( $info, 'gd version' );
				preg_match ( '/\d/', $info, $match );
				$version = $match [0];
			}
		}
	}
	return $version;
}
	
function getRealIp() {
	$ip = false;
	if (! empty ( $_SERVER ["HTTP_CLIENT_IP"] )) {
		$ip = $_SERVER ["HTTP_CLIENT_IP"];
	}
	if (! empty ( $_SERVER ['HTTP_X_FORWARDED_FOR'] )) {
		$ips = explode ( ", ", $_SERVER ['HTTP_X_FORWARDED_FOR'] );
		if ($ip) {
			array_unshift ( $ips, $ip );
			$ip = FALSE;
		}
		for($i = 0; $i < count ( $ips ); $i ++) {
			if (! eregi ( "^(10|172\.16|192\.168)\.", $ips [$i] )) {
				$ip = $ips [$i];
				break;
			}
		}
	}
	return ($ip ? $ip : $_SERVER ['REMOTE_ADDR']);
}

?>