<?
if (isset($_GET['download_sql'])) {
	$emptySqlFile = gluePath($sys['root'], "/system/data/sql/afian.sql");
	$filesize = filesize($emptySqlFile);
	$filename = "DatabaseSetup.sql";
	header("Content-Type: application/download");
	header("Content-Length: ".$filesize);
	header("Content-Disposition: attachment; filename=".$filename."");
	readfile($emptySqlFile);
	exit();
} else {
	$mustHaveTables['auth_tablename'] 			= $settings->config['auth_tablename'];
	$mustHaveTables['interauth_tablename'] 		= $settings->config['interauth_tablename'];
	$mustHaveTables['users_tablename'] 			= $settings->config['users_tablename'];
	$mustHaveTables['groups_tablename'] 		= $settings->config['groups_tablename'];
	$mustHaveTables['activity_logs_tablename']	= $settings->config['activity_logs_tablename'];
	$mustHaveTables['flags_tablename'] 			= $settings->config['flags_tablename'];
	$mustHaveTables['filetypes_tablename'] 		= $settings->config['filetypes_tablename'];
	$mustHaveTables['last_uploads_tablename'] 	= $settings->config['last_uploads_tablename'];
	$mustHaveTables['permvars_tablename'] 		= $settings->config['permvars_tablename'];
	$mustHaveTables['settings_tablename'] 		= $settings->config['settings_tablename'];
	$mustHaveTables['share_info_tablename'] 	= $settings->config['share_info_tablename'];
	$mustHaveTables['trash_tablename'] 			= $settings->config['trash_tablename'];
	$mustHaveTables['optinfo_tablename'] 		= $settings->config['optinfo_tablename'];
	$mustHaveTables['history_tablename'] 		= $settings->config['history_tablename'];
	
	if ($_POST['submit']) {
		if ($_GET['step'] == "1") {
			if (strlen($_POST['host']) == 0) {
				$msg .= "Please enter the MySQL server.";
			} elseif (!@mysql_connect($_POST['host'], $_POST['user'], $_POST['pass'])) {
				$msg .= $lang->get("Could not connect to MySQL server with the provided information.<br>MySQL: %1", array(mysql_error()));
			}  else {
			
			$databaseSelected = false;
				if (!@mysql_select_db($_POST['dbname'])) {
					//try to create
					if (!@mysql_query("CREATE DATABASE `".$_POST['dbname']."`")) {
						//try fails
						$msg .= $lang->get("Could not automaticaly create database \"".$_POST['dbname']."\".<br>MySQL: %1", array(mysql_error()));
						$databaseSelected = false;
					} else {
						//db created
						if (!@mysql_select_db($_POST['dbname'])) {
							//failed to select created database
							$msg .= $lang->get("Could not access newly created database \"".$_POST['dbname']."\".<br>MySQL: %1", array(mysql_error()));
							$databaseSelected = false;
						} else {
							//db created and selected
							$databaseSelected = true;
						}
					}
				} else {
					$databaseSelected = true;
				}
				
				
				if ($databaseSelected) {
					if ($_POST['db_creation_method'] == "auto") {
						require_once($sys['root']."/system/includes/setup/autoimport.inc");
					}
				
					$result = mysql_query("SHOW TABLES");
					while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
						$tables[] = $row[0];
					}
					foreach ($mustHaveTables as $key => $value) {
						if (!@in_array($value, $tables)) {
							$msg .= $lang->get("Table \"%1\" is missing.", array($value))."<br>";
							$missingTable = $value;
						}
					}
					if ($missingTable) {
						if ($_POST['db_creation_method'] == "auto") {
							$msg .= "<br>".$lang->get("Most probably the MySQL user doesn't have enough permissions.");
						}
					} else {
						$settings->set("server", $_POST['host']);
						$settings->set("dbname", $_POST['dbname']);
						$settings->set("dbuser", $_POST['user']);
						$settings->set("dbpass", $_POST['pass']);
						foreach ($mustHaveTables as $key => $value) {
							$settings->set($key, $value);
						}
						if (!$settings->update()) {
							$msg .= $lang->get("Failed to write to setup file.")."<br>".$lang->get("Check permissions of user \"%1\" (uid: %2)\" on file \"%3\".", array(get_current_user(), getmyuid(), $settings->dbFilePath));
						} else {
							header("Location: ?step=2");
						}
					}
				}
			}
		} elseif ($_GET['step'] == "2") {
			$path = cleanPath($str->fromHTML($_POST['defaultHomeFolder']));
			$trashOk = true;
			
			if (strlen($path) == 0) {
				$msg .= $lang->get("Please enter the path for \"default\" group.");
			} elseif (!isCleanPath($path)) {
				$msg .= $lang->get("Please enter an absolute path (do not use \"/../\"). Example: /home/users/auser/afian/documents/");
			} elseif (!is_dir($path)) {
				$msg .= $lang->get("The path doesn't point to an existing folder.");
			} elseif (!is_readable($path)) {
				$msg .= $lang->get("The folder you specify is not readable. Check permissions.");
			} elseif (!is_writeable($path)) {
				$msg .= $lang->get("The folder you specify is not writeable.");
				if (eregi("win", strtolower(php_uname()))) {
					$msg .= $lang->get("Make sure that is not \"readonly\".");
				} else {
					$msg .= $lang->get("Check folder's permissions.");
				}
			} else {

				if ($_POST['customTrashFolder']) {
					$trashFolder = cleanPath($str->fromHTML($_POST['trashFolder']));
					$trashOk = false;
					if (strlen($trashFolder) == 0) {
						$msg .= $lang->get("Please enter Trash folder location.");
					} elseif (!isCleanPath($trashFolder)) {
						$msg .= $lang->get("Please enter an absolute path for Trash folder (do not use \"/../\"). Example: /home/users/auser/afian/documents/");
					} elseif (!is_dir($trashFolder)) {
						$msg .= $lang->get("The Trash's path doesn't point to an existing folder.");
					} elseif (!is_readable($trashFolder)) {
						$msg .= $lang->get("The folder you specify for Trash is not readable. Check permissions.");
					} elseif (!is_writeable($trashFolder)) {
						$msg .= $lang->get("The folder you specify for Trash is not writeable.");
						if (eregi("win", strtolower(php_uname()))) {
							$msg .= $lang->get("Make sure that Trash folder is not \"readonly\".");
						} else {
							$msg .= $lang->get("Check Trash folder's permissions.");
						}
					} else {
						$trashOk = true;
					}
				} else {
					$trashFolder = gluePath($sys['root'],"/system/data/trash");
				}
				
				

				if ($trashOk) {

					$tempFolder = gluePath($sys['root'],"/system/data/temp");
					$adodbcacheFolder = gluePath($sys['root'],"/system/data/temp/adodbcache");

					if (!is_readable($trashFolder)) {
						$msg .= $lang->get("Folder %1 not readable. Chmod 777.", array($trashFolder));
					} elseif (!is_writeable($trashFolder)) {
						$msg .= $lang->get("Folder %1 not writeable. Chmod 777.", array($trashFolder));
					} elseif (!is_readable($tempFolder)) {
						$msg .= $lang->get("Folder %1 not readable. Chmod 777.", array($tempFolder));
					} elseif (!is_writeable($tempFolder)) {
						$msg .= $lang->get("Folder %1 not writeable. Chmod 777.", array($tempFolder));
					} elseif (!is_readable($adodbcacheFolder)) {
						$msg .= $lang->get("Folder %1 not readable. Chmod 777.", array($adodbcacheFolder));
					} elseif (!is_writeable($adodbcacheFolder)) {
						$msg .= $lang->get("Folder %1 not writeable. Chmod 777.", array($adodbcacheFolder));
					} else {
						if (!@mysql_connect($settings->config['server'], $settings->config['dbuser'], $settings->config['dbpass'])) {
							$msg = $lang->get("MySQL: %1", array(mysql_error()));
						} elseif (!@mysql_select_db($settings->config['dbname'])) {
							$msg = $lang->get("MySQL: %1", array(mysql_error()));
						} else {
							$adminTrashOk = true;
							if (!is_dir($trashFolder."/admin")) {
								if (!@mkdir($trashFolder."/admin")) {
								$msg = $lang->get("Failed to create trash folder for default user \"admin\".");
								$adminTrashOk = false;
								} else {
								$adminTrashOk = true;
								}
							}
							
							if ($adminTrashOk) {
								if ($_POST['customTrashFolder']) {
									$settings->set("trashpath", $trashFolder);
								}
							if (!$settings->update()) {
								$msg = $lang->get("Failed to write to setup file. Please check permissions on /path_to_afian/system/data/setup.dat");
							} else {
								
							/* connected ok, update default user and group */
							$query = mysql_query("UPDATE ".$settings->config['optinfo_tablename']." SET  firstname='".$sys['license']['registeredTo']['firstname']."', lastname='".$sys['license']['registeredTo']['lastname']."', email='".$sys['license']['registeredTo']['email']."', company='".$sys['license']['registeredTo']['company']."' WHERE uid='1'");
							if (!$query) {
								$errors[] = $lang->get("Invalid query: %1", array(mysql_error()));
							}
							/* update default group path*/
							$query = mysql_query("UPDATE ".$settings->config['groups_tablename']." SET path='".$str->safeSQL($path)."' WHERE id='1'");
							if (!$query) {
								$errors[] = $lang->get("Invalid query: %1", array(mysql_error()));
							}
							$query = mysql_query("UPDATE ".$settings->config['permvars_tablename']." set `val`='".time()."' WHERE `var`='flagsMonthlyCleanUpDate'");
							if (!$query) {
								$errors[] = $lang->get("Invalid query: %1", array(mysql_error()));
							}
							if (sizeof($errors) > 0) {
								foreach ($errors as $value) {
									echo $value;
									echo "<br>";
								}
							} else {
								header("Location: ?step=finish");
							}
							}
							}
						}
					}
				}
			}
		}
	}

?>
<html>
<head>
<title><?
if ($sys['license']['unbranded']) {
	$lang->display("INSTALLING");
	echo " ".$sys['license']['unbranded'];
} else {
	$lang->display("INSTALLING AFIAN");
}
?></title>
<style>
body {
	font-family:verdana;
	font-size:11px;
	text-align:center;
	background-image:url(images/interface/bgpat.gif);
	background-repeat : repeat-x;
	margin:20px;
	padding:0px;
	background-color:#8C8C8C;
}

td {
	font-family:verdana;
	font-size:11px;
}

.title {
	letter-spacing:0;
	font-family:times new roman;
	font-size:19px;
	font-weight:normal;
	color:black;
}

table.bordered {
	background-color:silver;
}

table.bordered td {
	background-color:whitesmoke;
}
table.bordered tr.header td {
	background-color:#EBEBEB;
	font-weight:bold;
}
.comment {
	color:gray;
	font-size:10px
}
body {
	cursor:default;
}
</style>
<script src="js/language.js.php" type="text/javascript" language="JavaScript1.2"></script>
</head>
<body>
<!-- TITLE -->
<table cellpadding="0" cellspacing="0" border="0" width="474" style="margin-bottom:30px" align="center">
<tr>
	<td width="440" style="border-top:1px solid white;border-bottom:1px solid white;font-family:arial;color:white;font-size:19px;letter-spacing:1px;"><?
if ($sys['license']['unbranded']) {
	$lang->display("INSTALLING");
	echo " ".$sys['license']['unbranded'];
} else {
	$lang->display("INSTALLING AFIAN");
}
?></td>
	<td><img src="images/interface/afian-logo-no-text.gif" width="26" height="26" border="0" style="float:left;"></td>
</tr>
</table>
<!-- END TITLE -->
<?
if ($_GET['step'] == "requirement_review") {
	require_once($sys['root']."/system/includes/setup/req_review.inc");
} elseif ($_GET['step'] == "1") {
	require_once($sys['root']."/system/includes/setup/step1.inc");
} elseif ($_GET['step'] == "2") {
	require_once($sys['root']."/system/includes/setup/step2.inc");
} elseif ($_GET['step'] == "3") {
	require_once($sys['root']."/system/includes/setup/step3.inc");
} elseif ($_GET['step'] == "finish") {
	require_once($sys['root']."/system/includes/setup/finish.inc");
} else {
	require_once($sys['root']."/system/includes/setup/welcome.inc");
}
?>
</body>
</html>
<?
}
?>