<%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="Dvbbs.bbs.Entity" %>
<%@ Import Namespace="Dvbbs.bbs.Handlers" %>
<%@ Import Namespace="Dvbbs.Utils" %>
<%@ Page Inherits="Dvbbs.Utils.Origin" %>
<script language="C#" runat="Server">

//fields
private string _dbLink;  //, mTablePrefix;

//OnInit
protected override void OnInit(EventArgs e)
{
	Response.Buffer = false;
	Response.ContentType = "text/html";
	Response.Charset = "gb2312";

	string mTablePrefix = "dv_";
	string table_prefix = Post("table_prefix").ToLower();
	if (table_prefix != string.Empty && table_prefix != "dv_")
	{
		mTablePrefix = table_prefix;
	}
	if(Request["step"] == "1")        //1.设置配置文件 Web.config
	{
		// 1.1 连接字符串
		MakeupDbLinkString();
		// 1.2 设置配置文件
		SetWebConfig(_dbLink, mTablePrefix);
		// 1.3 设置bbs.config中论坛访问Url地址
		SetBbsUrl();
	}
	else if(Request["step"] == "2")   //2.创建数据表
	{
		// 2.3 创建数据表
		if(conn.Provider == DbProviderEnum.SqlServer)   // sql server
		{
			//创建数据库
			CreateSqlServerDataBase(mTablePrefix);
		}
		else if(conn.Provider == DbProviderEnum.Access) // access
		{
			//创建数据表
			CreateAccessDataTable(mTablePrefix);
		}
	}
	else if(Request["step"] == "3")   //3.安装模板及初始化论坛统计数据
	{
		//安装模板
		//BuildTemplate();
		//初始化论坛统计数据
		RebuildStatisticFile();
	}
	else if(Request["step"] == "4")   //4.设置默认角色及帐号
	{
		// 3.1 设置默认角色
		//SetDefaultRole(mTablePrefix);
		// 3.2 设置默认帐号
		SetDefaultUser(mTablePrefix);
	}
	else if (Request["step"] == "5")	//5.建立系统缓存文件
	{
		// 重建广告设置方案缓存文件
		ForumCaching.RebuildAdsSettingCacheFile(conn);
		// 重建与版面设置有关的缓存文件
		ForumCaching.RebuildBoardSettingCacheFile(conn);
		// 重建用户权限有关的缓存文件
		Dvbbs.bbs.Entity.User.CreateAllUserLimit();
	}
	else if(Request["step"] == "6")   //6.删除安装文件
	{
		//删除安装文件
		RemoveUnusefulFiles();
	}
	Response.Write("{'result' : 1, 'url' : '" + Request.QueryString.ToString() + "'}");
}

//Makeup dblink string
private void MakeupDbLinkString()
{
	//access
	if(Post("dbtype") == "access")
	{
		_dbLink = "files\\localfiles\\data.ascx";
		return;
	}
	//sql server
	string module = "Data Source={0}; Database={1}; UID={2}; Password={3};";
	_dbLink = string.Format(module, Post("server"), Post("dbname"), Post("uid"), Post("pwd"));
}

// 设置配置文件 Dvbbs.Web.config
private bool SetWebConfig(string dblink, string mTablePrefix)
{
	/*string file = Fetch.MapPath("web.config");
	XmlDocument xml = new XmlDocument();
	xml.Load(file);
	XmlNodeList nodes = xml.GetElementsByTagName("add");

	foreach(XmlElement element in nodes)
	{
		string key = element.GetAttribute("key");
		if (key.ToLower() == "dblink")
		{
			element.SetAttribute("value", dblink);
			continue;
		}
		if (key.ToLower() == "tableprefix")
		{
			element.SetAttribute("value", mTablePrefix);
			continue;
		}
		if (key.ToLower() != "appprefix" && key.ToLower() != "cookietoken")
		{
			continue;
		}
		element.SetAttribute("value", Post(key));
	}
	//保存 web.config 文件
	xml.Save(file);
	return true;*/

	string file = Server.MapPath("~/Dvbbs.Web.config");
	XmlDocument xml = new XmlDocument();
	xml.Load(file);

	//数据库链接方式
	XmlNodeList nodes = xml.GetElementsByTagName("DbLink");
	foreach(XmlElement element in nodes)
	{
		element.InnerText = dblink;
	}
	
	//设置应用程序变量名前缀
	nodes = null;
	nodes = xml.GetElementsByTagName("AppPrefix");
	foreach(XmlElement element in nodes)
	{
		element.InnerText = Post("appprefix");
	}
	
	//设置数据库表名称前缀
	nodes = null;
	nodes = xml.GetElementsByTagName("TablePrefix");
	foreach(XmlElement element in nodes)
	{
		element.InnerText = mTablePrefix;
	}
	
	//设置Cookie加密参数
	nodes = null;
	nodes = xml.GetElementsByTagName("CookieToken");
	foreach(XmlElement element in nodes)
	{
		element.InnerText = Post("cookietoken");
	}

	//设置论坛基目录所对应的虚拟目录路径
	nodes = null;
	nodes = xml.GetElementsByTagName("ForumRootVirtualPath");
	foreach(XmlElement element in nodes)
	{
		int start = HttpContext.Current.Request.Url.ToString().IndexOf("/",8);
		int end = HttpContext.Current.Request.Url.ToString().IndexOf("/install/")-HttpContext.Current.Request.Url.ToString().IndexOf("/",8);
		element.InnerText = HttpContext.Current.Request.Url.ToString().Substring(start,end) + "/";
	}
	
	//保存 Dvbbs.web.config 文件
	xml.Save(file);
	return true;
}

// 设置基本设置中 论坛访问Url地址 一项
private void SetBbsUrl()
{
	System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
	//string path = Server.MapPath("../" + ApplicationSettings.Get("CustomConfigFile"));
	string path = Server.MapPath("../" + Fetch.GetCurrentForumSystemConfigInfo().CustomConfigFile);
	xml.Load(path);

	System.Xml.XmlNode node = xml.DocumentElement.SelectSingleNode("//Config/Settings/Basic/Item[Name='bbsurl']/Value");

	if(null != node)
	{
		node.InnerText = Post("bbsaddress");
	}
	node = null;
	xml.Save(path);
}

//创建 sql server 数据库
private bool CreateSqlServerDataBase(string mTablePrefix)
{
	if (conn.Provider == DbProviderEnum.Access)
	{
		return false;
	}
	// 读取 mssql.sql 中 sql 语句
	string sqlfile = Fetch.MapPath("install\\mssql.sql");
	string stmt = "";
	using (StreamReader reader = new StreamReader(sqlfile, System.Text.Encoding.GetEncoding("GB2312")))
	{
		string[] arr = reader.ReadToEnd().Split('~');
		foreach (string sql in arr)
		{
			stmt = sql.Trim().Replace("dv_", mTablePrefix);
			if (0 == stmt.Length)
			{
				continue;
			}
			conn.Execute(stmt);
		}
		return true;
	}
	return true;
}

// 创建 Access 数据表
private bool CreateAccessDataTable(string mTablePrefix)
{
	if (conn.Provider == DbProviderEnum.SqlServer)
	{
		return false;
	}
	// 读取 access.sql 中 sql 语句
	string sqlfile = Fetch.MapPath("install\\access.sql");
	string stmt = string.Empty;
	using (StreamReader reader = new StreamReader(sqlfile, System.Text.Encoding.GetEncoding("GB2312")))
	{
		string[] arr = reader.ReadToEnd().Split('~');
		foreach (string sql in arr)
		{
			stmt = sql.Trim().Replace("dv_", mTablePrefix);
			if (0 == stmt.Length)
			{
				continue;
			}
			if (Regex.IsMatch(stmt, @"^drop table", RegexOptions.IgnoreCase))
			{
				try
				{
					conn.Execute(stmt);
				}
				catch
				{
				}
			}
			else
			{
				conn.Execute(stmt);
			}
		}
	}
	return true;
}

// 安装模板
/*private void BuildTemplate()
{
	return;
	TemplateInfo[] tis = TemplateInfo.GetAllTemplateInfo();
	if (null == tis || 0 == tis.Length)
	{
		throw new Exception("模板安装失败！");
	}
	for (int i = 0; i < tis.Length; i++)
	{
		string[,] tpl_files = tis[i].GetFiles();
		int rank1_length = tpl_files.GetLength(0);
		string html_tpl_dir = Fetch.MapPath(TemplateInfo.TemplateSourceDirectory + tis[i].Name + "/html/");
		string aspx_tpl_dir = Fetch.MapPath(TemplateInfo.TemplateSourceDirectory + tis[i].Name + "/aspx/");
		for (int j = 0; j < rank1_length; j++)
		{
			if (null == tpl_files[j, 0] || string.Empty == tpl_files[j, 0] || '_' == tpl_files[j, 0][0])
			{
				continue;
			}
			string html_tpl_file = html_tpl_dir + Path.GetFileNameWithoutExtension(tpl_files[j, 0]) + ".html";
			if (!File.Exists(html_tpl_file))
			{
				//throw new Exception("模板安装失败，文件“" + html_tpl_file + "”不存在！");
				continue;
			}
			string aspx_tpl_file = aspx_tpl_dir + Path.GetFileNameWithoutExtension(tpl_files[j, 0]) + ".aspx";
			SimpleAspNetTemplateConvert.ToCSharp(html_tpl_file, aspx_tpl_file, Encoding.GetEncoding("gb2312"));
		}
	}
}*/

//初始化论坛统计数据
private void RebuildStatisticFile()
{
	StatisticHandler.SetValues(new string[]{"TodayDate", "NewUserName", "Users", "Topics", "Replies", "TodayTopics", "YestodayTopics", "Today", "MaxOnlines", "MaxOnlineTime", "MaxPost", "ForumVersion"}, new string[]{DateTime.Today.ToString(), Post("adminname"), "1", "0", "0", "0", "0", DateTime.Now.ToString("yyyy-MM-dd"), "0", DateTime.Now.ToString("G"), "0", "1.1"});
}

//set default role
/*private void SetDefaultRole(string mTablePrefix)
{
	if (conn.Provider == DbProviderEnum.SqlServer)
	{
		conn.Execute(default_role_prefix.Replace("dv_", mTablePrefix));
	}
	string[] arr = this.defaultrole.Split('~');
	foreach (string s in arr)
	{
		string sql = s.Trim().Replace("dv_", mTablePrefix);
		try
		{
			if (conn.Provider == DbProviderEnum.Access)
			{
				sql = sql.Replace("INSERT INTO [dbo].[", "INSERT INTO ");
				sql = sql.Replace("](", "(");
			}
			conn.Execute(sql);
		}
		catch
		{
			Response.Write(sql);
			Response.End();
		}
	}

	//object obj = conn.GetScalar("SELECT id FROM " + mTablePrefix + "usergroups WHERE rolename='管理员'");
	//if (null != obj)
	//{
		//conn.Execute("UPDATE " + mTablePrefix + "user SET usergroupid=" + obj.ToString() + " WHERE username = '" + Post("adminname").ToString().Trim() + "' ");
	//}
	if (conn.Provider == DbProviderEnum.SqlServer)
	{
		conn.Execute(default_role_postfix.Replace("dv_", mTablePrefix));
	}
}*/

//set default user
private void SetDefaultUser(string mTablePrefix)
{
	string name = Post("adminname");
	string pass = Text.MD5(Post("adminpass"));

	//conn.Execute("TRUNCATE TABLE " + mTablePrefix + "user");
	conn.Execute("INSERT INTO " + mTablePrefix + "user ([UserName], [UserPassword], [UserSex], [UserEmail], [UserInfo], [UserFace], [UserSign], [UserPower], [firstip], [usergroupid]) VALUES ('" + name.Trim() + "', '" + pass.Trim() + "', 0, 'webmatster@dvbbs.com', '					', 'userface/1.gif', '', 0, '127.0.0.1', 1)");
	//conn.Execute("TRUNCATE TABLE " + mTablePrefix + "admin");
	conn.Execute("INSERT INTO " + mTablePrefix + "admin ([adduser], [username], [password], [lastloginip]) VALUES ('" + name.Trim() + "', '" + name.Trim() + "', '" + pass.Trim() + "', '127.0.0.1')");
}

//Remove Unuseful Files
private void RemoveUnusefulFiles()
{
	string[] remove_files = new string[]{"install/install.html", "install/save.aspx", "install/environment_test.aspx"};
	for (int i = 0; i < remove_files.Length; i++)
	{
		try
		{
			File.Delete(Fetch.MapPath(remove_files[i]));
			//Response.Write("→ &nbsp;删除" + remove_files[i] + "成功<br /><br />");
		}
		catch
		{
			//Response.Write("<span style='color:red'>→ &nbsp;删除" + remove_files[i] + "失败，请务必手动删除，否则会被他人执行并危及数据</span><br /><br />");
			//Response.Write("{'result' : 1, 'url' : '" + Request.QueryString.ToString() + "'}");
			Response.Write("{'result' : 0, 'url' : '<span color=red>→ &nbsp;删除" + remove_files[i] + "失败，请务必手动删除，否则会被他人执行并危及数据</span><br /><br />'}");
			//Response.End();
		}
	}
}

</script>