<?php
/*
fiemeCP - BETA.
Written by, and managed by xDario.

The script may be altered at wish, but redistributing any part of it, even with credets, is prohibited. Currently, only myself and my website (http://www.dario-ml.com/) along with kryptodev are aloud to host my script.

©2011 xDario (created for Ohai Online)

You must provide a thanks on the page from which this is called, unless you have donated. If I find my class used without copyright, or a mention of appreciation, I will pursude you. Fiesta servers aren't thousands, so you're not hard to spot out.

Page: install.php
Last Change: 30 June 2011
*/

session_start();
if (!defined('PHP_VERSION_ID'))
{
    define('PHP_VERSION_ID', 0);
}
if (PHP_VERSION_ID < 50300)
{
	die("fiemeCP has been written for PHP5.3 Please upgrade to the newest version of PHP. The best solution is xampp.");
}

$current_rev = "0.8.0.0";
@include("LOCK");

if (!isset($_POST['step']))
{
	$_POST['db_host'] = "(local)\SQLExpress";
	$_POST['db_char'] = "World00_Character";
	$_POST['db_account'] = "Account";
	$_POST['srv_name'] = "";
	$_POST['game_srv_ip'] = "";
	$_POST['php_loc'] = substr($_SERVER['MIBDIRS'], 0, -11) . "php.exe";
	$_POST['lang'] = "en";
	$_POST['serial'] = "";
}
elseif (@$_POST['step'] == '1')
{
	//check everything!
	
	array_walk($_POST, 'trim_value');
	
	if (!function_exists('sqlsrv_connect'))
	{
		$error = "Oh, that's embarrassing. Looks like you don't have the appropriate .dlls installed :(. Install them and try again, pl0x.";
	}
	elseif ($_POST['srv_name'] == "")
	{
		$error = "Don't want me to know your server name, huh?";
	}
	elseif (!sqlsrv_connect($_POST['db_host']))
	{
		$error = "Maww, couldn't connect to the provided MsSql host...Let's try that again.";
	}
	elseif (!sqlsrv_connect( $_POST['db_host'], array("Database"=>"$_POST[db_account]")))
	{
		$error = "Could not connect to the Account database. Please make sure your given mssql values are correct.";
	}
	elseif (!sqlsrv_connect( $_POST['db_host'], array("Database"=>"$_POST[db_char]")))
	{
		$error = "Could not connect to the Character database. Please make sure your given mssql values are correct";
	}
	elseif ($_POST['srv_name'] == "")
	{
		$error = "Could not connect to the Character database. Please make sure your given mssql values are correct";
	}
	elseif ($_POST['db_account'] == "")
	{
		$error = "Please give a valid Account database.";
	}
	elseif ($_POST['game_srv_ip'] == "")
	{
		$error = "Please put the Game Server IP into the field provided.";
	}
	elseif (!is_file($_POST['php_loc']) || !substr($_POST['php_loc'], -4) == '.exe')
	{
		$error = "That is not a valid file for your php file.";
	}
	elseif (!is_file("../includes/lang/$_POST[lang].php"))
	{
		$error = "Language file does not exist. Please use \"en\", unless you've translated yourself. This is still Beta, so I won't translate until it's at a work-able stage.";
	}
	
	if (!isset($error))
	{
		$conn = sqlsrv_connect( $_POST['db_host'], array("Database"=>"$_POST[db_account]"));
		$result = sqlsrv_query($conn, "SELECT TOP 1 * FROM dbo.tUser WHERE [nAuthID] >= '9'", array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET));
		if (sqlsrv_num_rows($result) == 0)
		{
			$error = "No accounts with nAuthID 9.<br />Please make sure you have at least one user with admin level 9+ to use fiemeCP, to use as a full-admin.";
		}
		else
		{
			//let's start building!
			//SQL STUFF:
			
			$_POST['php_loc'] = str_replace("'", "''", $_POST['php_loc']);
			
			$sql['1'] = "IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fUserSettings]') AND type in (N'U'))
DROP TABLE [dbo].[fUserSettings]";

			$sql['2'] = "IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fUserCPLog]') AND type in (N'U'))
DROP TABLE [dbo].[fUserCPLog]";
			
			$sql['3'] = "IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fSettings]') AND type in (N'U'))
DROP TABLE [dbo].[fSettings]";
			
			$sql['4'] = "IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fPlugins]') AND type in (N'U'))
DROP TABLE [dbo].[fPlugins]";
			
			$sql['5'] = "IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fPatches]') AND type in (N'U'))
DROP TABLE [dbo].[fPatches]";
			
			$sql['6'] = "IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fLoginLog]') AND type in (N'U'))
DROP TABLE [dbo].[fLoginLog]";
			
			$sql['7'] = "CREATE TABLE [dbo].[fUserSettings](
	[user_id] [int] NOT NULL,
	[setting] [nvarchar](50) NOT NULL,
	[value] [nvarchar](50) NOT NULL
)";
			
			$sql['8'] = "CREATE TABLE [dbo].[fUserCPLog](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[type] [varchar](50) NOT NULL,
	[ip] [varchar](50) NOT NULL,
	[user_name] [varchar](50) NOT NULL,
	[time] [varchar](50) NOT NULL,
	[value_1] [nvarchar](max) NOT NULL,
	[value_2] [nvarchar](max) NULL,
	[value_3] [nvarchar](max) NULL
)";
			
			$sql['9'] = "CREATE TABLE [dbo].[fSettings](
	[setting_order] [int] NULL,
	[setting_group] [nvarchar](50) NOT NULL,
	[setting_save_name] [nvarchar](50) NOT NULL,
	[setting_name] [nvarchar](50) NOT NULL,
	[setting_desc] [nvarchar](max) NULL,
	[setting_form] [nvarchar](max) NULL,
	[setting_form_type] [nvarchar](max) NOT NULL,
	[setting_value] [nvarchar](max) NULL
)";
			
			$sql['10'] = "CREATE TABLE [dbo].[fPlugins](
	[plugin_name] [varchar](50) NOT NULL,
	[active] [int] NOT NULL
)";
			
			$sql['11'] = "CREATE TABLE [dbo].[fPatches](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[title] [varchar](50) NOT NULL,
	[notes] [nvarchar](max) NOT NULL,
	[patch_name] [nvarchar](50) NOT NULL,
	[postedby] [nvarchar](50) NOT NULL,
	[time] [nvarchar](50) NOT NULL,
	[ip_poser] [nvarchar](50) NOT NULL,
	[only_admin] [tinyint] NOT NULL,
	[deleted] [tinyint] NOT NULL
)";
			
			$sql['12'] = "CREATE TABLE [dbo].[fLoginLog](
	[log_id] [int] IDENTITY(1,1) NOT NULL,
	[username] [varchar](50) NOT NULL,
	[password] [varchar](50) NULL,
	[ip] [varchar](50) NOT NULL,
	[time] [varchar](50) NOT NULL,
	[is_admin_login] [tinyint] NOT NULL,
	[success] [tinyint] NOT NULL,
	[login_cookie] [tinyint] NOT NULL
)";
			
			$sql['13'] = "INSERT INTO fSettings ([setting_order], [setting_group], [setting_save_name], [setting_name], [setting_desc], [setting_form], [setting_form_type], [setting_value]) VALUES('0', 'global', 'dev_mode', 'Developer Mode', 'Do you want to activate developer mode - all users are affected!', 'array(''1''=>''Yes'', ''0''=>''No'')', 'radio', '0'), ('0', 'global', 'dev_mode_admin', 'Admin Developer Mode', 'Add Developer Mode to the AdminCP (NOT RECOMMENDED)', 'array(''1''=>''Yes'', ''0''=>''No'')', 'radio', '0'), ('0', 'global', 'php_location', 'PHP location', 'Where is php.exe located?', '', 'text', '$_POST[php_loc]'), ('0', 'global', 'status_update', 'Server Status Refresh', 'How often will we check if the game servers are online/offline? Value in seconds<br/>Default: 60', '', 'text', '60'), ('0', 'global', 'template_locations', 'Templates to Use', 'What templates do we want to use. Currently, only use \"fiedef\".', '', 'text', 'fiedef'), ('0', 'global', 'security_auto_hide', 'Auto Protect', 'Do we want to automatically protect sensitive data of FiemeCP? RECOMMENDED!', 'array(''1''=>''Yes'', ''0''=>''No'')', 'radio', '1'), ('0', 'global', 'security_auto_hide_overwrite', 'Overwrite when Auto Protecting?', 'Default: No', 'array(''1''=>''Yes'', ''0''=>''No'')', 'radio', '0'), ('0', 'global', 'security_auto_hide_htaccess', '.htaccess content', 'This is what will be added to the protected directories', '', 'textarea', 'order deny,allow
deny from all'), ('0', 'global', 'admin_panel_min_entry', 'AdminCP access', 'What''s the minimum nAuthLevel to enter the AdminCP? Default: 7', '', 'text', '7'), ('0', 'global', 'admin_panel_folder', 'AdminCP folder', 'Where is the adminCP folder? Edit this for security reasons.', '', 'text', 'admin'), ('0', 'global', 'logging_logins', 'Log the Logins?', '2 = Log everywhere, 1 = Log only admin CP, 0 = log nothing', 'array(''0''=>''Log nothing'', ''1''=>''Log the AdminCP only'', 2=>''Log everything'')', 'radio', '2'), ('0', 'global', 'logging_logins_storetime', 'How long do we save the logs?', 'How long do we store the logs for (in seconds)? Default 1 week: 604800', '', 'text', '604800'), ('0', 'global', 'logging_logins_passwords', 'Save passwords when logging?', 'Do you want to store passwords in the logs? //2 = Log everywhere, 1 = Log only admin CP, 0 = log no passwords', 'array(''0''=>''Log nothing'', ''1''=>''Log the AdminCP only'', 2=>''Log everything'')', 'radio', '1'), ('0', 'global', 'logging_logins_passwords_conditions', 'Conditions for saving passwords', 'If we are logging the password, when do they need to be logged? 0 = only when wrong password, 1 = always', 'array(''0''=>''Only when wrong'', ''1''=>''Always'')', 'radio', '0'), ('0', 'leaderboard', 'lb_allow', 'Activate the Leaderboard?', '', 'array(''0''=>''No'', ''1''=>''Yes'')', 'radio', '1'), ('0', 'leaderboard', 'lb_top_howmany', 'List how many users', 'Top xx will be shown in the Leaderboards?', '', 'text', '20'), ('0', 'leaderboard', 'lb_min_adminlevel', 'Filter out GMs & Staff', 'What adminlevel, and below, will be accepted. The selected value WILL BE INCLUDED in your leaderboard', '', 'text', '10'), ('0', 'usercp', 'log_usercp', 'Log UserCP activity?', 'Recomended!', 'array(''0''=>''No'', ''1''=>''Yes'')', 'radio', '1'), ('0', 'usercp', 'keep_usercp_logs', 'Log Life', 'How long shall fieme keep the logs for?', '', 'text', '1814400'), ('0', 'usercp', 'user_see_account_id', 'Can users see their Account Number?', '', 'array(''0''=>''No'', ''1''=>''Yes'')', 'radio', '1'), ('0', 'usercp', 'user_change_gender', 'Allow Gender Change?', '', 'array(''0''=>''No'', ''1''=>''Yes'')', 'radio', '1'), ('0', 'usercp', 'user_change_gender_copper', 'Price for gender change', 'In copper', '', 'text', '1000000'), ('0', 'usercp', 'user_change_gender_fame', 'Fame for gernder change', 'In fame... duh?', '', 'text', '0'), ('0', 'usercp', 'user_change_name', 'Allow Name Change?', '', 'array(''0''=>''No'', ''1''=>''Yes'')', 'radio', '0'), ('0', 'usercp', 'user_change_name_copper', 'Price for name change', 'In copper', '', 'text', '5000000'), ('0', 'usercp', 'user_change_name_fame', 'Fame for name change', '', '', 'text', '5000'), ('0', 'member', 'register_captcha', 'Captcah when Registering?', 'Do the users need to enter a captcha when they register? Stops bots!', 'array(''0''=>''No'', ''1''=>''Yes'')', 'radio', '1'), ('0', 'member', 'register_licence', 'Show a licence?', 'Show licence to user?', 'array(''0''=>''No'', ''1''=>''Yes'')', 'radio', '1'), ('0', 'member', 'register_licence_content', 'Licence', '', '', 'textarea', 'You might want to change the licence here.

This can be done in the AdminCP (Settings->Configuration->member)

Use the language variable to have difference licences in different languages (Advanced!)'), ('0', 'member', 'register_min_pass_length', 'Minimim password length', '', '', 'text', '6')";
			foreach ($sql as $num=>$query)
			{
				if (!sqlsrv_query($conn, $query, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET)))
				{
					$error = "Oh no! Fieme encountered an error when executing sql script $num. Please send a report to xDario.<br /><br />$query";
					break;
				}
			}
			
			if (!isset($error))
			{
				//SQL success! Let's write away
				if (preg_match('/^[0-9]{4}\-[0-9]{4}\-[0-9]{4}\-[0-9]{4}$/i', $_POST['serial']))
				{
					$extra = "
\$cfg['serial'] = \"$_POST[serial]\";
					";
				} else { $extra = ""; }
				$file = fopen("../includes/cfg.php", "w+"); 
				$content = "<?php
\$cfg['srv_name'] = \"$_POST[srv_name]\";

\$cfg['database_account'] = \"$_POST[db_account]\";
\$cfg['database_characters'] = \"$_POST[db_char]\";
\$cfg['database_host'] = \"$_POST[db_host]\";

\$cfg['script_root'] = \"" . str_replace("\\", "/", dirname(dirname(__FILE__))) . "/\";

\$cfg['lang_prefix'] = \"$_POST[lang]\";
$extra
\$game_server['login']['name'] = \"Login Server\";
\$game_server['login']['ip'] = \"$_POST[game_srv_ip]\";
\$game_server['login']['port'] = \"9010\";
\$game_server['login']['service'] = \"PG_Login_Server\";

\$game_server['w_manager']['name'] = \"World Manager\";
\$game_server['w_manager']['ip'] = \"$_POST[game_srv_ip]\";
\$game_server['w_manager']['port'] = \"9110\";
\$game_server['w_manager']['service'] = \"PG_World00_Manager_Server\";

\$game_server['world1']['name'] = \"World Server 1\";
\$game_server['world1']['ip'] = \"$_POST[game_srv_ip]\";
\$game_server['world1']['port'] = \"9120\";
\$game_server['world1']['service'] = \"PG_Zone_Server\";

\$game_server['world2']['name'] = \"World Server 2\";
\$game_server['world2']['ip'] = \"$_POST[game_srv_ip]\";
\$game_server['world2']['port'] = \"9121\";
\$game_server['world2']['service'] = \"PG_Zone_Server1\";

\$game_server['world3']['name'] = \"World Server 3\";
\$game_server['world3']['ip'] = \"$_POST[game_srv_ip]\";
\$game_server['world3']['port'] = \"9122\";
\$game_server['world3']['service'] = \"PG_Zone_Server2\";

?>";
				fwrite($file, $content);
				fclose($file);
					
				$file = fopen("LOCK", "w+");
				$content = "<?php
\$allow_install = \"no\";";
				fwrite($file, $content);
				fclose($file);
			}
		}
	}
	
	
	if (isset($error))
	{
		$_POST['step'] = $_POST['step'] - 1;
		$error = "<div id=\"error\"><img src=\"notick.png\" /> $error</div>";
	}
}

?>
<!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=utf-8" />
<title>Installing fiemeCP - xDario</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>

<body>
<div id="logo">
<?php
if (@$allow_install == "no" and !isset($_POST['step']))
{
	echo "<img src=\"install-already.png\" />";
}
elseif (isset($error))
{
	echo "<img src=\"install-1.png\" />";
}
elseif (!isset($error) && isset($_POST['step']))
{
	echo "<img src=\"install-2.png\" />";
}
else
{
	echo "<img src=\"install-0.png\" />";
}
?>
</div>
<div id="content-holder">
<?php
if (@$allow_install == "no" and !isset($_POST['step']))
{
	echo "Installation already done, there's no need to run this again. If you really need to, delete the file named LOCK in the install directory to re-create the config file, or recrate the fiemeCP tables.";
}
elseif (!isset($_POST['step']) || $_POST['step'] == 0)
{
	echo @$error . "<br />
<form action=\"index.php\" method=\"POST\">Dear valued developer,<br />
<br />
Welcome to the fresh installation, of the fiemeCP script. (Current Revision: <b><u>$current_rev</u></b>)<br />
<span style=\"color: #A00\">Please notice: FiemeCP is still under development. Make sure you are always running the newest version.</span><br />
<br />
<div style=\"color: #353535; font-weight: bold;\">If you wish you upgrade your script, rather than re-installing, please click <a href=\"update\">here</a>.<br />
This feature is only available from revision 0.8 onwards.</div>
<br />
<div style=\"border: #000 thin solid\">
<div style=\"font-size: 90%; color: #009900\">MANUAL WORK!</div>
While most of the script works automatically, the following is up to you!<br />
-> <b>YOU must make backups of your databases!</b> While fieme has worked perfectly up until now, there is a small chance that a bug damages your databses.<br />
-> YOU must install the correct .dlls that include the functions we need. Please read the documentation, currently on the release thread on Kryptodev.
</div>
<br />
<div style=\"border: #000 thin solid\">
<div style=\"font-size: 90%; color: #009900\">You can pretty much leave thease default, unless you know you changed something during the installing of the server.</div>
<table cellspacing=\"0\" cellpadding=\"0\" style=\"width: 80%; margin: 0px auto 0px auto;\">
<tr" . @$e0 . "><td width=\"50%\">Your Server Name</td><td width=\"50%\"><input name='srv_name' value='$_POST[srv_name]'></td></tr>
<tr" . @$e1 . "><td>MsSQL Host</td><td><input name='db_host' value='$_POST[db_host]'></td></tr>
<tr" . @$e2 . "><td>Account Database</td><td><input name='db_account' value='$_POST[db_account]'></td></tr>
<tr" . @$e3 . "><td>Character Database</td><td><input name='db_char' value='$_POST[db_char]'></td></tr></table>
</div>
<br />
<div style=\"border: #000 thin solid\">
<div style=\"font-size: 90%; color: #009900\">The following are used to check the server status, and are unique to your sever.<br />
If they are incorrectly inputted, or you need more profound edits, they must be done manually in /includes/cfg.php<br />
<strong>No checks are done to make sure that your input is correct!</strong></div>
<table cellspacing=\"0\" cellpadding=\"0\" style=\"width: 80%; margin: 0px auto 0px auto;\">
<tr><td width=\"50%\">Game server IP</td><td width=\"50%\"><input name='game_srv_ip' value='$_POST[game_srv_ip]'></td></tr></table>
</div>
<br />
<div style=\"border: #000 thin solid\">
<div style=\"font-size: 90%; color: #009900\">FiemeCP settings. These are vital to make fiemeCP's core run properly.<br />
You can edit all the things at a later stage from the Administrator Panel - but these are vital!</strong></div>
<table cellspacing=\"0\" cellpadding=\"0\" style=\"width: 80%; margin: 0px auto 0px auto;\">
<tr><td width=\"50%\">Php.exe Location</td><td width=\"50%\"><input name='php_loc' value='$_POST[php_loc]'></td></tr>
<tr><td colspan='2'><div style=\"font-size: 90%; color: #353535\">So, now we chose the language to install. Currently, only English (en) is available - however, if you've decided to translate the minimal stuff that's there, feel free to do so. The language code is the name of the folder in which the language files are included.</div></td></tr>
<tr><td>Language</td><td><input name='lang' value='$_POST[lang]'></td></tr>
</table>
</div>
<br />
<div style=\"border: #000 thin solid\">
<div style=\"font-size: 90%; color: #009900\"><b>OPTIONAL</b><br />A fiemeCP serial is only given out to closed-revision testers. You may request one from me, but it's not vital. In furutre revisions, the serial will acts a gateway between fieme and the public content such as skins and plugins - allowing you to easily access a bundle of content.</div>
<table cellspacing=\"0\" cellpadding=\"0\" style=\"width: 80%; margin: 0px auto 0px auto;\">
<tr><td width=\"50%\">fieme Serial</td><td width=\"50%\"><input name='serial' value='$_POST[serial]'></td></tr>
</table>
</div>
<br />
By continuing, you agree to <a href=\"../LICENCE\" target=\"_blank\">fieme's licence</a>, and agree that you have not modified it.<br />
<div style=\"text-align: right; margin-right: 20px;\"><input type=\"hidden\" name=\"step\" value=\"1\"><input type=\"image\" src=\"next.png\" /></form></div>";
}
elseif ($_POST['step'] == 1)
{
	echo "<h2>I'm finished!</h2>
		Wasn't that fun?<br />
		<br />
		<strong>I bet you didn't watch that video. Meenie</strong><br />
		(I don't blame you)<br />
		<br />
		<br />
		Then watch this. Is nothing like bluewaffle.<br />
		<br />
		<iframe width=\"640\" height=\"390\" src=\"http://www.youtube.com/embed/hQusVIPRZdI\" frameborder=\"0\" allowfullscreen></iframe>
		<hr />
		<br />
		Everything ran successfully, and you're ready to start! Install file locked. Click <a href='../'>here</a> to play with your new copy of fiemeCP!";
}






echo "</div>
<div id=\"footer\"><a href=\"http://www.kryptodev.com/showthread.php?tid=12729\">fiemeCP</a> installer, theme, and the program itself are &copy;2011xDario. All Rights Reserved. <br />
Do not distribute, or use for any other purpose than written for, unless prior written consent by xDario.</div>
</body>

</html>";

function trim_value(&$value) 
{ 
	$value = trim($value); 
}