<?php
/**
 * Magic CMS 首页
 * ============================================================================
 * Copyright 2014 大秦科技，并保留所有权利。
 * 网站地址: http://www.qintech.net；
 * ----------------------------------------------------------------------------
 * 未获商业授权之前，不得将Magic CMS用于商业用途（包括但不限于企业网站、经营性网站
 * 以营利为目的或实现盈利的网站）未经官方许可，禁止在Magic CMS的整体或任何部分基础
 * 上以发展任何派生版本、修改版本或第三方版本用于重新分发。如果您未能遵守本协议的
 * 条款，您的授权将被终止，所被许可的权利将被收回，并承担相应法律责任。
 * ============================================================================
 * Date:2014/12/31
**/
if (!defined('APP_PATH'))exit('No direct script access allowed');
class IndexModule extends CommonModule{

	public function __construct(){

		$this->step = Q('get.step',1,'intval');

		$this->step = $this->step == 0 ? 1 : $this->step;

		if (C('INSTALL_LOCK') && $this->step != 5)
			die('系统已经安装过了，如需重新安装请先修改配置文件！');

		@set_time_limit(0);

		define('TITLE','Magic CMS 内容管理系统');

		define('POWERED','V '.C('VERSION'));

		define('INS_PATH',C('MODULE_PATH').'/'.MODULE.'/');

		define('INS_TPL',INS_PATH.'templates');

		if (phpversion() <= '5.3.0')
			set_magic_quotes_runtime(0);
		if (phpversion() < '5.2.0')
			exit('您的php版本过低，不能安装本软件，请升级到5.2.0或更高版本再安装，当前PHP版本为：' . phpversion());

		$this->sqlfile = 'magic.sql';

		$this->folder = array(
							'/',
							'Data',
							'Data/Cache',
							'Data/Compile',
							'Data/Config',
							'Data/Log',
							'Data/Message',
							'Data/Public',
							'Data/Tag',
							'Include',
							'Include/Config',
							'Include/Data',
							'Module',
							'Templets',
							'Uploads',
						);

	}


	public function index(){

		switch ($this->step) {

			case '1':
				break;
			case '2':

				$error = 0;

				$os = PHP_OS;

				$phpv = phpversion();

				$tmp = function_exists('gd_info') ? gd_info() : array();

				$server = $_SERVER["SERVER_SOFTWARE"];

				$host = (empty($_SERVER["SERVER_ADDR"]) ? $_SERVER["SERVER_HOST"] : $_SERVER["SERVER_ADDR"]);

				$name = $_SERVER["SERVER_NAME"];

				$max_execution_time = ini_get('max_execution_time');

				$allow_reference = (ini_get('allow_call_time_pass_reference') ? '<font color=green>[√]On</font>' : '<font color=red>[×]Off</font>');

				$allow_url_fopen = (ini_get('allow_url_fopen') ? '<font color=green>[√]On</font>' : '<font color=red>[×]Off</font>');

				$safe_mode = (ini_get('safe_mode') ? '<font color=red>[×]On</font>' : '<font color=green>[√]Off</font>');


				if ($phpv > '5.2.0') {
					$phpv =  '<span class="correct_span">&radic;</span> '.$phpv;
				}else{
					$phpv =  '<span class="correct_span error_span">&radic;</span> '.$phpv;
					$error++;
				}

				if (empty($tmp['GD Version'])) {
					$gd = '<font color=red>[×]Off</font>';
					$error++;
				} else {
					$gd = '<font color=green>[√]On</font> ' . $tmp['GD Version'];
				}
				if (function_exists('mysql_connect')) {
					$mysql = '<span class="correct_span">&radic;</span> 已安装';
				} else {
					$mysql = '<span class="correct_span error_span">&radic;</span> 出现错误';
					$error++;
				}
				if (ini_get('file_uploads')) {
					$uploadsize = '<span class="correct_span">&radic;</span> ' . ini_get('upload_max_filesize');
				} else {
					$uploadsize = '<span class="correct_span error_span">&radic;</span>禁止上传';
					$error++;
				}
				if (function_exists('session_start')) {
					$session = '<span class="correct_span">&radic;</span> 支持';
				} else {
					$session = '<span class="correct_span error_span">&radic;</span> 不支持';
					$error++;
				}

				break;
			case '3':
				$type = @$_POST['type'];
				if ($type==1 || $type==2) {
					$conn = @mysql_connect($_POST['dbhost'].':'.$_POST['dbport'], $_POST['dbuser'], $_POST['dbpwd']);

					$version = mysql_get_server_info($conn);
					if ($version < 4.1)  $this->error('数据库版本太低!');

					if ($type==1) {
						if ($conn) {
							$this->success('数据库连接成功');
						}else{
							$this->error('数据库连接失败');
						}
					}elseif($type==2){
						if (!$conn) $this->error('数据库连接失败');
						if (mysql_select_db($_POST['dbname'], $conn)){
							$this->success('数据库已存在，如果继续安装到或许会导致安装失败');
						}else{
							$this->success('数据库检测通过');
						}
					}
				}

				break;
			case '4':
				if (intval($_GET['install'])) {

					$n = intval($_GET['n']);
					$dbhost = trim($_POST['dbhost']);
					$dbport = trim($_POST['dbport']);
					$dbname = trim($_POST['dbname']);
					$dbuser = trim($_POST['dbuser']);
					$dbpwd  = trim($_POST['dbpw']);

					$dbhost   = empty($dbport) || $dbport == 3306 ? $dbhost : $dbhost . ':' . $dbport;
					$dbprefix = empty($_POST['dbprefix']) ? 'mac_' : trim($_POST['dbprefix']);

					$username = trim($_POST['username']);
					$password = encrypt(trim($_POST['repassword']));

					Maclic::oauth(1,$username,trim($_POST['repassword']),false);

					$conn = @mysql_connect($dbhost, $dbuser, $dbpwd);

					if (!$conn) $this->error('连接数据库失败!');

					mysql_query("SET NAMES 'utf8'");

					$version = mysql_get_server_info($conn);

					if ($version < 4.1)  $this->error('数据库版本太低!');

					if (!mysql_select_db($dbname, $conn)) {
						if (!mysql_query("CREATE DATABASE IF NOT EXISTS `" . $dbname . "` DEFAULT CHARACTER SET utf8;", $conn)) $this->error('数据库 '.$dbname.' 不存在，也没权限创建新的数据库！');

						if (empty($n)){
							exit(json_encode(array('n'=>0,'content'=>'成功创建数据库:'.$dbname.'<br>')));
						}

						mysql_select_db($dbname, $conn);

					}
					if (!is_file(INS_PATH.$this->sqlfile)){
						exit(json_encode(array('content'=>'读取数据库文件失败！')));
					}

					//读取数据文件
					$sqldata = @file_get_contents(INS_PATH.$this->sqlfile);

					$sqlformat = sql_split($sqldata, $dbprefix);

					 //执行SQL语句
					$counts = count($sqlformat);

					for ($i = $n; $i < $counts; $i++) {
						$sql = trim($sqlformat[$i]);

						//创建表
						if (strstr($sql, 'CREATE TABLE')) {
								preg_match('/CREATE TABLE IF NOT EXISTS `([^ ]*)`/', $sql, $matches);

								mysql_query("DROP TABLE IF NOT EXISTS `$matches[1]");

								$ret = mysql_query($sql);
								if ($ret) {
									$msg = '<li><span class="correct_span">&radic;</span>创建数据表' . $matches[1] . '，完成</li> ';
								} else {
									$msg = '<li><span class="correct_span error_span">&radic;</span>创建数据表' . $matches[1] . '，失败</li>';
								}
								$i++;
								exit(json_encode(array('n'=>$i,'content'=>$msg)));

							//插入数据
							}else{
								$ret = mysql_query($sql);
								//exit(json_encode(array('n'=>$i,'content'=>'数据插入成功')));
							}
						}

						if ($i == 999999) exit;

						$query = "INSERT INTO `{$dbprefix}user` (`uid`,`uname`,`nickname`,`utype`,`password`,`regtime`,`status`,`rid`) VALUES (1,'{$username}','超级管理员','-1','{$password}','".time()."',1,1);";
						mysql_query($query);

						//写入配置文件
						$config = array(
								'DB_TYPE'     => 'mysql',//数据库类型
								'DB_CHARSET'  => 'utf8',//数据库编码
								'DB_HOST'     => $dbhost,//数据库主机
								'DB_PORT'     => $dbport,//数据库端口
								'DB_DATABASE' => $dbname,//数据库名
								'DB_USER'     => $dbuser,//数据库用户名
								'DB_PASSWORD' => $dbpwd,//数据库密码
								'DB_PREFIX'   => $dbprefix,//数据库前缀
							);

						$config_lock = array('INSTALL_LOCK'=>true);

						$config      = CA(ROOT_PATH.'Config.php',$config);

						$config_lock = CA(CONFIG_PATH . 'Config.class.php',$config_lock);

						if ($config_lock) {
							$msg = '<li><span class="correct_span">&radic;</span>成功写入配置文件</li> ';
						}else{
							$msg = '<li><span class="correct_span error_span">&radic;</span>写入配置文件失败</li>';
						}

						exit(json_encode(array('n'=>999999,'content'=>'<li><span class="correct_span">&radic;</span>成功添加管理员</li>'.$msg)));
				}
				break;
			case '5':
				$domain = empty($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
				if ((int)$_SERVER['SERVER_PORT'] != 80)
					$domain .= ":" . $_SERVER['SERVER_PORT'];
				break;
		}
		include_once ("templates/main.php");
		exit;
	}
}

/**
	* 相关函数
*/
function testwrite($d) {
	$tfile = "_test";
	$fp = @fopen($d . "/" . $tfile, "w");
	if (!$fp)
		return false;
	fclose($fp);
	$rs = @unlink($d . "/" . $tfile);
	if ($rs) return true;
	return false;
}


function sql_split($sql, $tablepre) {
    if ($tablepre != "mac_"){
        $sql = str_replace("mac_", $tablepre, $sql);
		$sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8", $sql);
	}
    if ($r_tablepre != $s_tablepre){
        $sql = str_replace($s_tablepre, $r_tablepre, $sql);
	}
    $sql = str_replace("\r", "\n", $sql);
    $ret = array();
    $num = 0;
    $queriesarray = explode("--MagicCMS;", trim($sql));

    unset($sql);
    foreach ($queriesarray as $query) {
        $ret[$num] = '';
        $queries = explode("\n", trim($query));
        $queries = array_filter($queries);
        foreach ($queries as $query) {
            $str1 = substr($query, 0, 1);
            if ($str1 != '#' && $str1 != '-')
                $ret[$num] .= $query;
        }
        $num++;
    }
    return $ret;
}