<?php
/*
[F SCHOOL OA] F 校园网络办公系统 2009
This is a freeware
Version: 2.2.1
Author: 浪子凡 (nbbufan@163.com)
Powered By:【凡·工作室】 (www.microphp.cn)
Last Modified: 2009/3/31 20:08
*/
error_reporting(E_ERROR | E_PARSE);
define('DCPATH',substr(dirname(preg_replace("/\\\/i",'/',__FILE__)), 0,-7));

//function
Function alert($str, $url="",$backtype=true){
	if($backtype){
        if($url!=""){
			$url=($url==1)?$_SERVER['HTTP_REFERER']:$url;
            echo "<script language=JavaScript>alert(\"".$str."\");window.location='".$url."'</script>";
        }else{
            echo "<script language=JavaScript>alert(\"".$str."\");history.go(-1)</script>";
        }
    }else{
    	echo "<script language=JavaScript>alert(\"".$str."\");window.close()</script>";
    }
    exit;
}
function delfile($filename){
	strpos($filename,'..')!==false && exit('Forbidden');
	@chmod ($filename, 0777);
	return @unlink($filename);
}
function openfile($filename,$method="rb"){
	strpos($filename,'..')!==false && exit('Forbidden');
	if($handle=@fopen($filename,$method)){
		flock($handle,LOCK_SH);
		$filedata=@fread($handle,filesize($filename));
		fclose($handle);
	}
	return $filedata;
}
function writefile($filename,$data,$method="rb+",$iflock=1,$check=1,$chmod=1){
	$check && strpos($filename,'..')!==false && exit('Forbidden');
	touch($filename);
	$handle=fopen($filename,$method);
	if($iflock){
		flock($handle,LOCK_EX);
	}
	fwrite($handle,$data);
	if($method=="rb+") ftruncate($handle,strlen($data));
	fclose($handle);
	$chmod && @chmod($filename,0777);
}
// 防止 PHP 5.1.x 使用时间函数报错
function_exists('date_default_timezone_set') && date_default_timezone_set('Etc/GMT+0');
unset($_ENV,$HTTP_ENV_VARS,$_REQUEST,$HTTP_POST_VARS,$HTTP_GET_VARS,$HTTP_POST_FILES,$HTTP_COOKIE_VARS,$HTTP_SESSION_VARS,$HTTP_SERVER_VARS);
unset($GLOBALS['_ENV'],$GLOBALS['HTTP_ENV_VARS'],$GLOBALS['_REQUEST'],$GLOBALS['HTTP_POST_VARS'],$GLOBALS['HTTP_GET_VARS'],$GLOBALS['HTTP_POST_FILES'],$GLOBALS['HTTP_COOKIE_VARS'],$GLOBALS['HTTP_SESSION_VARS'],$GLOBALS['HTTP_SERVER_VARS']);
// Fix for IIS, which doesn't set REQUEST_URI
if ( empty( $_SERVER['REQUEST_URI'] ) ) {
	$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME']; // Does this work under CGI?

	// Append the query string if it exists and isn't null
	if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) {
		$_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
	}
}

// Fix for PHP as CGI hosts that set SCRIPT_FILENAME to something ending in php.cgi for all requests
if ( isset($_SERVER['SCRIPT_FILENAME']) && ( strpos($_SERVER['SCRIPT_FILENAME'], 'php.cgi') == strlen($_SERVER['SCRIPT_FILENAME']) - 7 ) )
	$_SERVER['SCRIPT_FILENAME'] = $_SERVER['PATH_TRANSLATED'];

// Fix for Dreamhost and other PHP as CGI hosts
if (strpos($_SERVER['SCRIPT_NAME'], 'php.cgi') !== false)
	unset($_SERVER['PATH_INFO']);

// Fix empty PHP_SELF
$PHP_SELF = $_SERVER['PHP_SELF'];
if ( empty($PHP_SELF) )
	$_SERVER['PHP_SELF'] = $PHP_SELF = preg_replace("/(\?.*)?$/",'',$_SERVER["REQUEST_URI"]);

if ( !(phpversion() >= '4.2') )
	die( 'Your server is running PHP version ' . phpversion() . ' but School  OA requires at least 4.2.' );

if ( !extension_loaded('mysql'))
	die( 'Your PHP installation appears to be missing the MySQL which is required for School  OA.' );

if ( get_magic_quotes_gpc() ) {
	//$_GET    = stripslashes_deep($_GET);
	//$_POST   = stripslashes_deep($_POST);
	//$_COOKIE = stripslashes_deep($_COOKIE);
}

!$_SERVER['PHP_SELF'] && $_SERVER['PHP_SELF']=$_SERVER['SCRIPT_NAME'];
$_URI  = $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
$CMSDIR=substr(dirname($_URI),0,-8);
$CMSURL= 'http://'.$_SERVER['HTTP_HOST'].$CMSDIR;

$step = isset($_GET['step']) ? $_GET['step'] : $_POST['step'];

$configfile=DCPATH.'config.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>School  OA - 安装向导</title>
<link href="install.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="main">
  <form method="post" action="<?=$PHP_SELF;?>">
    <p class="title">School  OA V2.2.0 安装向导</p>
    <hr noshade="noshade" />
    <?php
if (empty($step)) {
?>
    <p align="center" class="title">School  OA使用许可协议</p>
    <p>版权所有 &copy; 2007-2009，<a href="http://www.microphp.cn" target="_blank">Microphp</a> 保留所有权利。 </p>
    <p>感谢您选择School  OA V2.2.0</p>
    <p class="title">一、本协议适用于 School  OA 任何版本，School  OA官方拥有对本协议的最终解释权。</p>
    <p class="title">二、协议许可和限制</p>
    <p>1、本程序为免费程序，任何人可以任意修改或者二次开发，但请说明修改自本程序。</p>
    <p>1、未对本程序源码(不包括模板)做任意修改，不得对后台版权进行修改。</p>
    <p>2、未经<a href="http://www.microphp.cn" target="_blank">官方</a>许可，不得对本程序进行出租、出售或发放许可证等商业行为。 </p>
    <p class="title">免责声明:</p>
    <p>1 、利用本程序构建的网站的任何信息内容以及导致的任何版权纠纷和法律争议及后果，官方不承担任何责任。</p>
    <p>2 、用户出于自愿而使用本软件，您必须了解使用本软件的风险，在尚未购买产品技术服务之前，
      我们不承诺提供任何形式的技术支持、使用担保，也不承担任何因使用本软件而产生问题的相关责任。 </p>
    <hr noshade="noshade" />
    <p align="right">
      <input type="hidden" name="step" value="1" />
      <input type="button" class="formbutton" value="拒 绝" onClick="window.close();"/>
      <input class="formbutton" type="submit" value="同 意" />
    </p>
    <?php
}elseif ($step == '1') {
	$check=1;
	$no_write=$CMSDIR."程序根目录无法书写,请速将根目录属性设置为777";
	$correct='    ......<font style="color:green;">√</font>';
	$incorrect='<font style="color:red;">× 777属性检测不通过</font>';
	$uncorrect='<font style="color:red;">× 文件不存在请上传此文件</font>';
	$w_check=array(
		'config.php',
		'upfile',
		'cache'
	);
	if($fp=@fopen(DCPATH.'test.txt',"wb")){
		$state=$correct;
		fclose($fp);
	} else{
		$state=$incorrect.$no_write;
	}
	$count=count($w_check);
	for($i=0; $i<$count; $i++){
		if(!file_exists(DCPATH.$w_check[$i])){
			$w_check[$i].= $uncorrect;$check=0;
		} elseif(is_writable(DCPATH.$w_check[$i])){
			$w_check[$i].= $correct;
		} else{
			$w_check[$i].=$incorrect; $check=0; 
		}
	}
	$check && @unlink(DCPATH.'test.txt');
?>
    <p class="title">第一步:安装须知</p>
    <p>欢迎使用 School  OA V2.2.0，本向导将帮助您将程序完整地安装在您的服务器内。<br />
      请您先确认以下安装配置: </p>
    <ul>
      <li>MySQL 主机名称/IP 地址 </li>
      <li>MySQL 用户名和密码 </li>
      <li>MySQL 数据库名称 </li>
    </ul>
    <p>如果您无法确认以上的配置信息, 请与您的服务商联系, 我们无法为您提供任何帮助.</p>
    <p class="title">第二步:检查必要目录和文件是否可写，如果发生错误，请更改文件/目录属性 777 </p>
    <ul>
      <li>程序根目录 (
        <?=$CMSDIR?>
        目录)</li>
      <? foreach($w_check as $key=>$value){ ?>
      <li>
        <?=$value?>
      </li>
      <? }?>
    </ul>
    <hr noshade="noshade" />
    <p align="right">
      <input type="hidden" name="step" value="2" />
      <?php 
if(!$check){
?>
      <input onclick='window.location="install.php"' type='button' value='重新检查'>
      <? }else{?>
      <input class="formbutton" type="submit" value="下一步" />
      <? }?>
    </p>
    <?php
}elseif ($step == '2') {
?>
    <p class="title">第三步:配置数据库信息</p>
    <table width="100%" border="0" cellspacing="0" cellpadding="4">
      <tr>
        <td colspan="2"><span class="title">数据库信息</span></td>
      </tr>
      <tr>
        <td width="30%">服务器地址:</td>
        <td><input type="text" value="localhost" name="dbhost" class="formfield" >
          一般是 localhost</td>
      </tr>
      <tr>
        <td width="30%">数据库名:</td>
        <td><input name="dbname" type="text" class="formfield" value="oa">
          <input name="create" type="checkbox" id="create" value="1"/>
          创建新数据库</td>
      </tr>
      <tr>
        <td width="30%">数据库用户名:</td>
        <td><input name="dbuser" type="text" class="formfield" value="root"></td>
      </tr>
      <tr>
        <td width="30%">数据库用户密码:</td>
        <td><input type="password" value="" name="dbpw" class="formfield"></td>
      </tr>
      <tr>
        <td width="30%">数据表前缀:</td>
        <td><input type="text" value="oa_" name="tablepre" class="formfield">
          不填则默认为 oa_</td>
      </tr>
      <tr>
        <td>数据表编码:</td>
        <td><select name="dbcharset" id="dbcharset">
            <option value="gbk" selected="selected">GBK</option>
          </select></td>
      </tr>
    </table>
    <hr noshade="noshade" />
    <table width="100%" border="0" cellspacing="0" cellpadding="4">
      <tr>
        <td colspan="2"><span class="title">程序配置</span></td>
      </tr>
      <tr>
        <td width="30%">网站地址:<br />
          不般不用修改,向导自动获取</td>
        <td><input name="cmsurl" type="text" class="formfield" id="cmsurl" style="width:320px" value="<?=$CMSURL?>" /></td>
      </tr>
    </table>
    <hr noshade="noshade" />
    <table width="100%" border="0" cellspacing="0" cellpadding="4">
      <tr>
        <td colspan="2"><span class="title">管理配置</span></td>
      </tr>
      <tr>
        <td width="30%">管理员账号:</td>
        <td><input type="text" value="admin" name="admin" class="formfield" /></td>
      </tr>
      <tr>
        <td width="30%">管理员密码:</td>
        <td><input type="password" name="password" class="formfield" />
          请设置密码</td>
      </tr>
    </table><br />
    <hr noshade="noshade" />
    <p align="right">
      <input type="hidden" name="step" value="3" />
      <input class="formbutton" type="button" value="上一步" onclick="history.back(1)" />
      <input class="formbutton" type="submit" value="下一步" />
    </p>
    <?php
} elseif ($step == '3') {
	if(trim($_POST['dbname']) == "" || trim($_POST['dbhost']) == "" || trim($_POST['dbuser']) == "" ){
?>
    <p>请返回并确认所有选项均已填写.</p>
    <hr noshade="noshade" />
    <p align="right">
      <input class="formbutton" type="button" value="上一步" onclick="history.back(1)" />
    </p>
    <?php
	} elseif(!@mysql_connect($_POST['dbhost'],$_POST['dbuser'],$_POST['dbpw'])) {
?>
    <p>数据库不能连接.</p>
    <hr noshade="noshade" />
    <p align="right">
      <input class="formbutton" type="button" value="上一步" onclick="history.back(1)" />
    </p>
    <?php
	} elseif(!@mysql_select_db($_POST['dbname'])&&!$_POST['create']) {

?>
    <p>数据库
      <?=$_POST['dbname']?>
      不存在.</p>
    <hr noshade="noshade" />
    <p align="right">
      <input class="formbutton" type="button" value="上一步" onclick="history.back(1)" />
    </p>
    <?php
	} elseif(strstr($_POST['tablepre'], '.')) { 
?>
    <p>您指定的数据表前缀包含点字符，请返回修改.</p>
    <hr noshade="noshade" />
    <p align="right">
      <input class="formbutton" type="button" value="上一步" onclick="history.back(1)" />
    </p>
    <?php
	} else {
?>
    <p class="title">第四步:导入数据</p>
    <?php
		if(is_writeable($configfile)) {

			$dbhost 	= trim($_POST['dbhost']);
			$dbuser 	= trim($_POST['dbuser']);
			$dbpw 		= trim($_POST['dbpw']);
			$dbname 	= trim($_POST['dbname']);
			$dbprefix	= trim($_POST['tablepre']);
			$dbcharset	= trim($_POST['dbcharset']);

			$cmsurl	= trim($_POST['cmsurl']);
			$admin	= trim($_POST['admin']);
			$password	= trim($_POST['password']);
			empty($password) && alert('管理员密码不能为空！');
		

			$filecontent = openfile($configfile,'r');
			$filecontent = preg_replace("/[$]servername\s*\=\s*[\"'].*?[\"']/is", "\$servername = '$dbhost'", $filecontent);
		$filecontent = preg_replace("/[$]dbusername\s*\=\s*[\"'].*?[\"']/is", "\$dbusername = '$dbuser'", $filecontent);
		$filecontent = preg_replace("/[$]dbpassword\s*\=\s*[\"'].*?[\"']/is", "\$dbpassword = '$dbpw'", $filecontent);
		$filecontent = preg_replace("/[$]dbname\s*\=\s*[\"'].*?[\"']/is", "\$dbname = '$dbname'", $filecontent);
		$filecontent = preg_replace("/[$]tablepre\s*\=\s*[\"'].*?[\"']/is", "\$tablepre = '$dbprefix'", $filecontent);
		$filecontent = preg_replace("/[$]charset\s*\=\s*[\"'].*?[\"']/is", "\$charset = '$dbcharset'", $filecontent);
		$filecontent = preg_replace("/[$]rootpath\s*\=\s*[\"'].*?[\"']/is", "\$rootpath = '$cmsurl'", $filecontent);

			writefile($configfile,$filecontent);
		}
		
		if(!@mysql_select_db($dbname)&&$_POST['create']){
			
    		$database=addslashes($dbname);
    		if(version_compare(mysql_get_server_info(), '4.1.0', '>=')){
		    $DATABASESQL=$dbcharset=='gbk'?"DEFAULT CHARACTER SET gbk COLLATE gbk_chinese_ci":"DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
    		}
    		mysql_query("CREATE DATABASE `$database` ".$DATABASESQL);
		}
		
		require_once ($configfile);
		$installSQL='oa_Install_SQL_'.$dbcharset.'.sql';
		!is_readable($installSQL)&&exit('数据库文件不存在或者读取失败');
		//set db
		$dbmysqlfile=DCPATH.'include/db_mysql.php';
		require_once($dbmysqlfile);
		$db = new FMysql;
    $db->appname="【凡·工作室】";
    $db->appshortname="shool oa 2009";
    $db->database=$dbname;
    $db->server=$dbhost;
    $db->user=$dbuser;
    $db->password=$dbpw;
    $db->connect();
    unset($dbhost, $dbuser, $dbpw, $dbname, $pconnect);
    $db->query("SET NAMES '$charset'");
		runquery(openfile($installSQL));	
		$sql="INSERT INTO members (`userid` ,`username` ,`realname` ,`password` ,`groupid` ,`webgroupid` ,`admining` ,`subjectid` ,`manageid` )
		                   VALUES ('1', '$admin', '管理员', '".md5($password)."', 1, 1, 0, 0, 14);";
		$db->query($sql);
		$query_id=$db->insert_id();
			//生成用户资料
	$query="INSERT INTO `userinfo` ( `id` , `userid`  ,  `tableleft` , `tableright` ) 
                          VALUES ('1', '	$query_id', '$defaultleft', '$defaultright');";
  $db->query($query);	 
?>
    </p>
    <p>共创建了
      <?=$tablenum;?>
      个数据表.</p>
    <hr noshade="noshade" />
    <p>安装程序已经顺利执行完毕，请尽快删除整个 install 目录，以免被他人恶意利用。</p>
    <p>&nbsp;</p>
    <p><a href="../index.php?filename=login">点击这里进入首页</a><br />

    <hr noshade="noshade" />
    <p align="right"><a href="http://www.microphp.cn" target="_blank">Welcome to microphp</a></p>
    <?php
}
}
?>
  </form>
</div>
<strong>Powered by <a href="http://www.microphp.cn" target="_blank">School  OA</a> V2.2.0 &copy; 2007-2009 </strong>
</body>
</html>
<?php
function runquery($sql) {
	global  $db, $tablenum,$tablepre,$dbcharset;
	$sql = str_replace("\r", "\n", str_replace('#schooloa@_',$tablepre,$sql));
	$ret = array();
	$num = 0;
	foreach(explode(";\n", trim($sql)) as $query) {
		$queries = explode("\n", trim($query));
		foreach($queries as $query) {
			$ret[$num] .= $query[0] == '#' ? '' : $query;
		}
		$num++;
	}
	unset($sql);
	foreach($ret as $query) {
		$query = trim($query);
		if($query) {
			if(substr($query, 0, 12) == 'CREATE TABLE') {
				preg_match("|CREATE TABLE (.*) \(  |i",$query, $name);
				echo '创建表 '.$name[1].' ... <font color="#0000EE">成功</font><br />';
				$db->query(createtable($query, $dbcharset));
				$tablenum++;
			} else {
				$db->query($query);
			}
		}
	}
}

function createtable($sql, $dbcharset) {
	$type = strtoupper(preg_replace("/^\s*CREATE TABLE\s+.+\s+\(.+?\).*(ENGINE|TYPE)\s*=\s*([a-z]+?).*$/isU", "\\2", $sql));
	$type = in_array($type, array('MYISAM', 'HEAP')) ? $type : 'MYISAM';
	$sql =preg_replace("/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU", "\\1", $sql);
	if ( !empty($dbcharset) && version_compare(mysql_get_server_info(), '4.1.0', '>=') ){
		$sql.=" ENGINE=$type DEFAULT CHARSET=$dbcharset";
	}else{
		$sql.=" TYPE=$type";
	}
	return $sql;
}
?>
