<?php
/**
 * 
 * @file index.php
 * @version v 1.0 2007/3/15 20:52:20
 * @copyright (c) 2005 - 2012 eifr.com
 * @license http://www.gnu.org/copyleft/gpl.html gnu/gpl
 * eifr is free software
 */
ini_set('default_charset', 'utf-8');
if (abs(PHP_VERSION) < 5) {
	echo'您的php版本('.PHP_VERSION.')太老，必须大于等于5.0才能继续安装';
    exit(1);
}

require_once("../libraries/request.php");

function getIP() {
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
        $ip = getenv("HTTP_CLIENT_IP");
    else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
        $ip = getenv("REMOTE_ADDR");
    else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
        $ip = $_SERVER['REMOTE_ADDR'];
    else
        $ip = "unknown";
    return $ip;
} 

function formatIP($ip) {
    $rtn = '';
    $ip_arr = explode('.', $ip);
    $ip_count = count($ip_arr);
    for($i = 0;$i < $ip_count; $i++) {
        $tmp = $ip_arr[$i];
        $tmp_len = strlen($tmp);
        if ($tmp_len < 3) {
            $tmp = str_repeat('0', 3 - $tmp_len) . $tmp;
        } 
        $rtn .= $tmp;
    } 
    return $rtn;
} 

function setDatabase() { // set database
    global $isnew, $cfg_dbhost, $cfg_dbuser, $cfg_dbpwd, $cfg_dbname, $cfg_dbprefix, $adminuser, $adminpwd, $cfg_softpath, $cfg_webtitle, $cfg_weburl, $soft_license;
    global $cfg_dbcharset,$cfg_dbhost,$cfg_dbuser,$cfg_dbpwd,$cfg_dbname;
    
    if (!isset($isnew)) $isnew = 0;
    $conn = mysql_connect($cfg_dbhost, $cfg_dbuser, $cfg_dbpwd) or die("<script>alert('数据库服务器或登录密码无效，\\n\\n无法连接数据库，请重新设定！');history.go(-1);</script>");
    if ($isnew == 1) {
        mysql_query("CREATE DATABASE " . $cfg_dbname, $conn) or die("<script>alert('创建数据库失败，可能权限不足，请指定一个已创建好的数据库！');history.go(-1);</script>");
    } 
    mysql_select_db($cfg_dbname) or die("<script>alert('数据库不存在，请重新设定！');history.go(-1);</script>");
    mysql_query("SET NAMES '$cfg_dbcharset';", $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]; 
    // create table from eifr_sql.txt
    if ($mysql_version < 4.1) {
        echo'<SCRIPT LANGUAGE="JavaScript">alert("您的mysql版本('.$mysql_version.')太老，必须大于等于4.1才能继续安装。");location="index.php";</SCRIPT>';
        exit(1);
    }
    $fp = fopen(dirname(__FILE__) . "/eifr_sql.txt", "r");
    $query = "";
    while (!feof($fp)) {
        $line = trim(fgets($fp, 1024));
        if (preg_match("/;$/", $line)) {
            $query .= $line;
            mysql_query(str_replace("#~lang~#", $cfg_dbcharset, str_replace("#~eifr~#", $cfg_dbprefix, $query)), $conn);
            $query = "";
        } else if (!preg_match("/^\/\//", $line)) {
            $query .= $line . "\n";
        } 
    } 
    fclose($fp); 
    // write data from insert_sql.txt
    $fp = fopen(dirname(__FILE__) . "/insert_sql.txt", "r");
    $query = "";
    while (!feof($fp)) {
        $line = trim(fgets($fp, 2048));
        if (preg_match("/;$/", $line)) {
            $query .= $line;
            $query = str_replace("#~eifr~#", $cfg_dbprefix, $query);
            $query = str_replace("#~/eifr/~#", $cfg_softpath, $query);
            $query = str_replace("#~eifr_webtitle~#", $cfg_webtitle, $query);
            $query = str_replace("#~eifr_weburl~#", $cfg_weburl, $query);
            $query = str_replace("#~eifr_license~#", $soft_license, $query);
            $query = str_replace("#~db_charset~#", $cfg_dbcharset, $query);
            $query = str_replace("#~db_host~#", $cfg_dbhost, $query);
            $query = str_replace("#~db_name~#", $cfg_dbname, $query);
            $query = str_replace("#~db_user~#", $cfg_dbuser, $query);
            $query = str_replace("#~db_pwd~#", $cfg_dbpwd, $query);
            mysql_query($query, $conn);
            $query = "";
        } else if (!preg_match("/^\/\//", $line)) {
            $query .= $line . "\n";
        } 
    } 
    fclose($fp); 
    // insert data
    if ($adminpwd ==='') $adminpwd = md5('admin');
    else $adminpwd = md5($adminpwd);

    $record_arr = array(
        'uid' => '1',
        'username' => $adminuser,
        'password' => $adminpwd,
        'gender' => '1',
        'boss_uid' => '0',
        'user_class_id' => '02',
        'channel_id' => '',
        'regip' => getIP(),
        'fileurl' => '',
        'birthday' => '0',
        'regtime' => time(),
        'lastip' => getIP(),
        'lasttime' => '1311042268',
        'loginnum' => '0',
        'zipcode' => '65535',
        'credit' => '0',
        'email' => 'test@test.com',
        'im' => 'msn:test@test.com;',
        'address_id' => '',
        'address' => '',
        'marriage' => '0',
        'ordernum' => '0',
        'flag' => '1',
        'timeoffset' => '',
        'tel' => '',
        'fax' => '',
        'mobile' => '',
        'realname' => 'administrator',
        'nickname' => '管理员',
        'company' => '',
        'detail' => '',
        'word' => '',
        'certificate_type' => '',
        'certificate_code' => '',
        'parameter' => '',
        'layout_id' => '',
    );
    
    $sql = "INSERT INTO `" . $cfg_dbprefix . "_user` (" . implode(', ', array_keys($record_arr)) . ") VALUES ('" . implode("','", array_values($record_arr)) . "')";
    mysql_query($sql, $conn);

    @mysql_close($conn);

} 


function setFileConfig() { // config.php
    global $cfg_softpath, $cfg_webtitle, $cfg_weburl, $soft_license;
    global $cfg_dbcharset,$cfg_dbhost,$cfg_dbuser,$cfg_dbpwd,$cfg_dbname;

    $fp = fopen(dirname(__FILE__) . "/config.php", "r") or die("<script>alert('读取配置，请检查install/config.php 是否可读取！');history.go(-1);</script>");;
    $configstr = fread($fp, filesize(dirname(__FILE__) . "/config.php"));
    fclose($fp);

    $configstr = str_replace("#~/eifr/~#", $cfg_softpath, $configstr);
    $configstr = str_replace("#~eifr_webtitle~#", $cfg_webtitle, $configstr);
    $configstr = str_replace("#~eifr_weburl~#", $cfg_weburl, $configstr);
    $configstr = str_replace("#~eifr_license~#", $soft_license, $configstr);
    $configstr = str_replace("#~db_charset~#", $cfg_dbcharset, $configstr);
    $configstr = str_replace("#~db_host~#", $cfg_dbhost, $configstr);
    $configstr = str_replace("#~db_name~#", $cfg_dbname, $configstr);
    $configstr = str_replace("#~db_user~#", $cfg_dbuser, $configstr);
    $configstr = str_replace("#~db_pwd~#", $cfg_dbpwd, $configstr);

    $fp = fopen(dirname(__FILE__) . "/../includes/config.php", "w") or die("<script>alert('写入配置失败，请检查include/config.php是否可写入！');history.go(-1);</script>");
    fwrite($fp, $configstr);
    fclose($fp);
} 

function setFileTable() { // table.php
    global $cfg_dbprefix;

    $fp = fopen(dirname(__FILE__) . "/table.php", "r") or die("<script>alert('读取配置，请检查install/table.php 是否可读取！');history.go(-1);</script>");;
    $configstr = fread($fp, filesize(dirname(__FILE__) . "/table.php"));
    fclose($fp);

    $configstr = str_replace("#~eifr~#", $cfg_dbprefix, $configstr);

    $fp = fopen(dirname(__FILE__) . "/../includes/table.php", "w") or die("<script>alert('写入配置失败，请检查../include目录是否可写入！');history.go(-1);</script>");
    fwrite($fp, $configstr);
    fclose($fp);
} 

// main -----------------------------------------
$ip = formatIP(getIP());
$soft_license = '2012-' . time() . '-' . $ip;

if (empty($step)) $step = 1;
if ($step == 1) { // read initial data
    $web_title = '';
    if (!empty($_SERVER["REQUEST_URI"])) {
        $scriptName = $_SERVER["REQUEST_URI"];
    } else {
        $scriptName = $_SERVER["PHP_SELF"];
    } 
    $softpath = @eregi_replace("/install(.*)$", "", $scriptName) . '/';
    if (empty($_SERVER['HTTP_HOST'])) $web_url = "http://" . $_SERVER['HTTP_HOST'];
    else $web_url = "http://" . $_SERVER['SERVER_NAME'];
    if ($_SERVER['SERVER_PORT'] != '80') $web_url .= ':' . $_SERVER['SERVER_PORT'];
} else if ($step == 2) { // setup program
    setFileConfig(); //config.php
    setFileTable(); //table.php  
    setDatabase(); //set database

    echo'<SCRIPT LANGUAGE="JavaScript">alert("完成设置.\n为了安全请删除安装目录!\n现转向管理登录面页...");location="../admin/";</SCRIPT>';
    exit();
} 

?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>系统 EIFR SITE 安装程序</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body >

<table width="80%" border="0" align="center" cellpadding="0" cellspacing="0" class="edit_tb">
  <tr > 
    <td >
    	<table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr bgcolor="#FFFFFF"> 
        	<td height="80" ><a href='http://www.eifr.com/' target='_blank'><img src="img/logo.gif" width="159" height="92" border="0"></a></td>
          <td align="right" ><img src="img/p5.gif" width="43" height="41"><img src="img/p4.gif" width="43" height="41"><img src="img/p3.gif" width="43" height="41"><img src="img/p2.gif" width="43" height="41"><img src="img/p1.gif" width="43" height="41"><img src="img/safarilogo.png" width="43" height="41"><img src="img/chromelogo.jpg" width="43" height="41"><img src="img/operalogo.jpg" width="43" height="41"></td>
        </tr>
      </table></td>
  </tr>
  <tr class="list_title_bg"> 
    <td width="100%" height="27" >
    	&nbsp;<IMG  src="img/applications.gif"  border="0" align="absmiddle">&nbsp; 安装 EIFR SITE 版
    </td>
  </tr>
  <tr> 
    <td width="100%" height="1" background="img/sp_bg.gif"></td>
  </tr>
  <tr> 
    <td width="100%" height="2"></td>
  </tr>
  <form name="form1" method="post" action="index.php">
    <input type="hidden" name="step" value="2">
    <tr> 
      <td width="100%" valign="top">
      	<table width="100%" border="0" cellpadding="2" cellspacing="1" >
          <tr > 
            <td width="19%" height="87">&nbsp;目录权限：</td>
            <td width="81%">
            	如果在linux或Unix平台，网站根目录的以下文件、目录及子目录需手工在FTP中设为组用户可读写，或用全权限 0777 <br>
            	/includes<br>/cache<br>
/linkfiles<br>
              在安装完本程序后，请在后台进行一次目录权限检测
              </td>
          </tr>
          <tr class="list_parent_tr_bg"> 
            <td colspan="2">&nbsp;数据库设定：</td>
          </tr>
          <tr class="list_sub_tr_bg"> 
            <td height="24">&nbsp;数据库主机：</td>
            <td><input name="cfg_dbhost" type="text" id="cfg_dbhost" value="localhost"></td>
          </tr>
          <tr class="list_sub_tr_bg"> 
            <td height="24">&nbsp;数据库名称：</td>
            <td><input name="cfg_dbname" type="text" id="cfg_dbname" value="eifr"> 
              <input name="isnew" type="checkbox" id="isnew" value="1">
              创建新数据库</td>
          </tr>
          <tr class="list_sub_tr_bg"> 
            <td height="24">&nbsp;数据库用户：</td>
            <td><input name="cfg_dbuser" type="text" id="cfg_dbuser" value="root"></td>
          </tr>
          <tr class="list_sub_tr_bg"> 
            <td height="24">&nbsp;数据库密码：</td>
            <td><input name="cfg_dbpwd" type="password" id="cfg_dbpwd"></td>
          </tr>
          <tr class="list_sub_tr_bg"> 
            <td height="24">&nbsp;数据库前缀：</td>
            <td><input name="cfg_dbprefix" type="text" id="cfg_dbprefix" value="eifr"></td>
          </tr>
          <tr class="list_sub_tr_bg"> 
            <td height="24">&nbsp;数据库编码：</td>
            <td><input name="cfg_dbcharset" type="radio" value="utf8" checked>
              utf8
              <input name="cfg_dbcharset" type="radio" value="latin1">
              latin1 （仅对4.1+以上版本的MySql选择）</td>
          </tr>
          <tr class="list_parent_tr_bg"> 
            <td colspan="2">&nbsp;网站初始数据设定：</td>
          </tr>
          <tr class="list_sub_tr_bg"> 
            <td height="24">&nbsp;网站标题：</td>
            <td><input name="cfg_webtitle" type="text" id="cfg_webtitle" value="<?=$web_title?>"></td>
          </tr>
          <tr class="list_sub_tr_bg"> 
            <td height="24">&nbsp;网站网址：</td>
            <td><input name="cfg_weburl" type="text" id="cfg_weburl" value="<?=$web_url?>"></td>
          </tr>
          <tr class="list_sub_tr_bg"> 
            <td height="24">&nbsp;系统安装目录：</td>
            <td><input name="cfg_softpath" type="text" id="cfg_softpath" value="<?=$softpath?>"></td>
          </tr>
          <tr bgcolor="#F9FDF2"> 
            <td colspan="2">&nbsp;管理员初始化：</td>
          </tr> 
          <tr class="list_sub_tr_bg"> 
            <td height="24">&nbsp;用户名：</td>
            <td><input name="adminuser" type="text" id="adminuser" value="admin"></td>
          </tr>
          <tr class="list_sub_tr_bg"> 
            <td height="24">&nbsp;密　码：</td>
            <td><input name="adminpwd" type="text" id="adminpwd" value="admin"></td>
          </tr>
          <tr class="list_parent_tr_bg"> 
            <td height="24">&nbsp;License：</td>
            <td ><?=$soft_license?></td>
          </tr>
          <tr class="list_parent_tr_bg"> 
            <td height="24">&nbsp;</td>
            <td ><input name="acceptgnu"  type="checkbox"  checked><a href="http://www.gnu.org/copyleft/gpl.html" target="_blank">GNU(GPL)</a>&nbsp;&nbsp;<a href="../gnu_gpl.html" target="_blank">GNU 通用公共授权 (简体中文翻译版)</a></td>
          </tr>
          <tr class="list_parent_tr_bg"> 
            <td height="24">&nbsp;</td>
            <td ><input name="btnSubmit"  type="submit" class="btn_submit" value="确定" ></td>
          </tr>
          
        </table> </td>
    </tr>
  </form>
  <tr> 
    <td width="100%" height="2" valign="top"></td>
  </tr>
</table>
<p align="center">
<a href='http://www.eifr.com/' target='_blank'>易孚网站系统 Power by EIFR </a><br><br>
</p>

</body>
</html>
