<?php
error_reporting(E_ALL & ~E_NOTICE);
define('ngroot',substr(dirname(__FILE__),0,-8));
define('nginc',dirname(__FILE__));
header("Content-Type: text/html; charset=gb2312");

function FilterNotSafeString(&$str)
{
	 global $ng_notallowstr,$ng_replacestr;
	 if(strlen($str)>10)
	 {
	  	//禁止字串
	  	if(!empty($ng_notallowstr) && eregi($ng_notallowstr,$str)) {
	  		 echo "Messege Error! <a href='javascript:history.go(-1)'>[Go Back]</a>";
	  		 exit();
	  	}
	  	//替换字串
	  	if(!empty($ng_replacestr)) {
	  	  	$str = eregi_replace($ng_replacestr,'***',$str);
	  	}
	 }
}

//注册请求字符串并加转义
function RunMagicQuotes(&$str)
{
	global $needFilter,$ng_notallowstr,$ng_replacestr;
	if(!get_magic_quotes_gpc())
	{
		 if( is_array($str) ) {
			  foreach($str as $key => $val) $str[$key] = RunMagicQuotes($val);
		 }else{
			  if($needFilter) FilterNotSafeString($str);
			  $str = addslashes($str);
		 }
	}
	else
	{
		 if($needFilter) {
		 	  $str = stripslashes($str);
		 	  FilterNotSafeString($str);
		 	  addslashes($str);
		 }
	}
	return $str;
}

foreach(Array('_GET','_POST','_COOKIE') as $_request) 
{
	 foreach($$_request as $_k => $_v){
	 	 if($_k{0} != '_') ${$_k} = RunMagicQuotes($_v);
	 }
}


if(empty($step)) $step = 1;
require_once("./inc_install.php");

$gototime = 2000;
/*------------------------
显示协议文件
------------------------*/
if($step==1){
	if(file_exists('install.lock')) {
		echo '你已经安装过该系统，如果想重新安装，请先删除install目录的 install.lock 文件，然后再次运行该程序';
		exit;
	}
	include_once("./templets/s1.html");
	exit();
}
/*------------------------
测试环境要求
------------------------*/
else if($step==2)
{
	$phpv = @phpversion();
	$sp_os = strtolower(isset($_ENV['OS']) ? $_ENV['OS'] : @getenv('OS'));
	$sp_gd = @gdversion();
	$sp_server = $_SERVER["SERVER_SOFTWARE"];
	$sp_host = (empty($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_HOST"] : $_SERVER["REMOTE_ADDR"]);
	$sp_name = $_SERVER["SERVER_NAME"];
	$sp_max_execution_time = ini_get('max_execution_time');
	$sp_allow_reference = (ini_get('allow_call_time_pass_reference') ? '<font color=green>[√]On</font>' : '<font color=red>[×]Off</font>');
    $sp_allow_url_fopen = (ini_get('allow_url_fopen') ? '<font color=green>[√]On</font>' : '<font color=red>[×]Off</font>');
    $sp_safe_mode = (ini_get('safe_mode') ? '<font color=red>[×]On</font>' : '<font color=green>[√]Off</font>');
    $sp_gd = ($sp_gd>0 ? '<font color=green>[√]On</font>' : '<font color=red>[×]Off</font>');
    $sp_mysql = (function_exists('mysql_connect') ? '<font color=green>[√]On</font>' : '<font color=red>[×]Off</font>');

  if($sp_mysql=='<font color=red>[×]Off</font>') $sp_mysql_err = true;
  else $sp_mysql_err = false;

  $sp_testdirs = array(
        '/',
        '/include'
  );
	include_once("./templets/s2.html");
	exit();
}
/*------------------------
收集参数
------------------------*/
else if($step==3)
{
	if(!empty($_SERVER["REQUEST_URI"])){$scriptName = $_SERVER["REQUEST_URI"]; }
  else{ $scriptName = $_SERVER["PHP_SELF"]; }
  $netgoupath = ereg_replace("/install/index\.php(.*)$","",$scriptName);
  if(empty($_SERVER['HTTP_HOST'])) $baseurl = "http://".$_SERVER['HTTP_HOST'];
  else $baseurl = "http://".$_SERVER['SERVER_NAME'];
  
  include_once("./templets/s3.html");
  exit();
}
/*------------------------
开始安装
------------------------*/
else if($step==5)
{
  if(empty($setupsta)) $setupsta = 0;
  //初始化基本安装数据、创建表
  //----------------------------------
  if($setupsta==0)
  {
  	$setupinfo = '';
  	$gotourl = '';
  	$gototime = 2000;
  	if(eregi("[^\.0-9a-z@!_-]",$adminuser) || eregi("[^\.0-9a-z@!_-]",$adminpwd)){
  		echo GetBackAlert("管理员会员名或密码含有非法字符！");
  		exit();
  	}

  	//检测数据库权限
  	$conn = @mysql_connect($dbhost,$dbuser,$dbpwd);
  	if(!$conn){
  		echo GetBackAlert("数据库服务器或登录密码无效，\\n\\n无法连接数据库，请重新设定！");
  		exit();
  	}
  	$rs = mysql_select_db($dbname,$conn);
  	if(!$rs){
  		$rs = mysql_query(" CREATE DATABASE `$dbname`default character set $db_language; ",$conn);
  		if(!$rs){
  		  $errstr = GetBackAlert("数据库 {$dbname} 不存在，也没权限创建新的数据库！");
  		  echo $errstr;
  		  exit();
  		}else{
  			$rs = mysql_select_db($dbname,$conn);
  			if(!$rs){
  		    $errstr = GetBackAlert("你对数据库 {$dbname} 没权限！");
  		    echo $errstr;
  		    exit();
  		  }
  		}
  	}

  	//读取配置模板，并替换真实配置
  	$errstr = GetBackAlert("读取配置 sql_config.php 失败，请检查install/sql_config.php是否可读取！");
  	$fp = fopen(ngroot."/install/sql_config.php","r") or die($errstr);
    $configstr1 = fread($fp,filesize(ngroot."/install/sql_config.php"));
    fclose($fp);

    $configstr1 = str_replace('~dbhost~',$dbhost,$configstr1);
    $configstr1 = str_replace('~dbname~',$dbname,$configstr1);
    $configstr1 = str_replace('~dbuser~',$dbuser,$configstr1);
    $configstr1 = str_replace('~dbpwd~',$dbpwd,$configstr1);
    $configstr1 = str_replace('~dbprefix~',$dbprefix,$configstr1);
    $configstr1 = str_replace('~db_language~',$db_language,$configstr1);
	$configstr1 = str_replace('~http://localhost~',$weburl,$configstr1);
	$configstr1 = str_replace('~/netgou~',$netgoupath,$configstr1);
	
    $errstr = GetBackAlert("写入配置 sql_config.php 失败，请检查 include文件夹 是否可读写！");
  	$fp = fopen(ngroot."/sql_config.php","w") or die($errstr);
  	fwrite($fp,$configstr1);
  	fclose($fp);



  	 //检测数据库信息并创建基本数据表
  	 mysql_query("SET NAMES '{$db_language}';",$conn);
     $rs = mysql_query("SELECT VERSION();",$conn);
     $row = mysql_fetch_array($rs);
     $mysql_version = $row[0];
     $mysql_versions = explode(".",trim($mysql_version));
     $mysql_version = $mysql_versions[0].".".$mysql_versions[1];

	  
	  $fp = fopen(ngroot."/install/xinyong.sql","r");
	  $query = "";
      while(!feof($fp))
	  {
		   $line = trim(fgets($fp,1024));
		   if(ereg(";$",$line)){
			   $query .= $line;
			   $query = str_replace('#@__',$dbprefix,$query);
			   if($mysql_version < 4.1) mysql_query($query,$conn);
			   else mysql_query(str_replace('#~lang~#',$db_language,$query),$conn);
			   $query='';
		   }else if(!ereg("^(//|--)",$line)){
			   $query .= $line;
		   }
	  }
	  fclose($fp);
	 
	  mysql_close($conn);
	 
	  $gotourl = '../admin/index.php';
	  $setupinfo = "
	    成功安装系统数据库<br />
		<a href='../'>浏览商城前台</a><br /><br />
		
		后台默认的管理员帐号和密码都是admin<br />
		<a href='{$gotourl}'>登录后台管理</a>
	  ";
  		include_once("./templets/s4.html");
	  exit();
  }
  //安装数据
    
	exit();
}
/*------------------------
检测数据库是否有效
------------------------*/
else if($step==10)
{
	header("Pragma:no-cache\r\n");
  header("Cache-Control:no-cache\r\n");
  header("Expires:0\r\n");
	header("Content-Type: text/html; charset=gb2312");
	$conn = @mysql_connect($dbhost,$dbuser,$dbpwd);
	if($conn)
	{
	  $rs = mysql_select_db($dbname,$conn);
	  if(!$rs)
	  {
		   $rs = mysql_query(" CREATE DATABASE `$dbname`; ",$conn);
		   if($rs){
		  	  mysql_query(" DROP DATABASE `$dbname`; ",$conn);
		  	  echo "<font color='green'>信息正确</font>";
		   }else{
		      echo "<font color='red'>数据库不存在，也没权限创建新的数据库！</font>";
		   }
	  }else{
		    echo "<font color='green'>信息正确</font>";
	  }
	}else{
		echo "<font color='red'>数据库连接失败！</font>";
	}
	@mysql_close($conn);
	exit();
}
?>