<?php
session_start();
ini_set('display_errors','On');
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);

require_once('_includes/functions_file.inc.php');
require_once('_includes/functions_afb.inc.php');
require_once('_includes/magic_quotes.php');
require_once('_includes/adodb/adodb.inc.php');
require_once('_includes/function.dba.php');


if (isset($_SESSION['lang']) && is_file('_includes/lang/lang.'.stripslashes($_SESSION['lang']).'.php')){
	include('_includes/lang/lang.'.stripslashes($_SESSION['lang']).'.php');
	$step = 2;
}

?><!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>
	<title>Ajax File Browser Installation</title>
	<meta name="keywords" content="" />
	<meta name="description" content="" />
	<meta name="Copyright" content="jc21.com 2006" />
	<meta name="Robots" content="index, follow" />
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<style type="text/css">
		body {
			font-size:100%;
			background-color:#CCC;
			font-family:"Trebuchet MS", Arial, Verdana;
			color:#666;
		}
		#wrapper {
			width:760px;
			margin:0 auto 0 auto;
		}
		h1 {
			font-family:"Century Gothic", "Trebuchet MS", "Arial Narrow", Arial, sans-serif;
			font-size:30px;
			text-transform:uppercase;
			font-weight:normal;
			margin:0;
			padding:0;
			padding-top:5px;
			color:#3399CC;
			margin-bottom:10px;
			text-align:left;
		}
		h2 {
			font-family:"Century Gothic", "Trebuchet MS", "Arial Narrow", Arial, sans-serif;
			font-size:15px;
			text-transform:uppercase;
			text-align:left;
			font-weight:normal;
			margin:0;
			padding:0;
			color:#336699;
			border-bottom:1px solid #336699;
		}
		#main {
			border:1px solid #336699;
			background-color:#CBDCF8;
			padding:10px;
			font-size:14px;
		}
		.error {
			color:#f00;
			text-align:center;
		}
		table {
			margin:10px auto 10px auto;
		}
		.button {
			border:1px solid #336699;
			background-color:#CCC;
			color:#3399CC;
		}
	</style>
</head>

<body id="body">
	<div id="wrapper">
		<h1>AjaxFB <?php echo htmlentities(getLangTerm('installation',false)); ?></h1>
		<div id="main">
			<?php
			
			//check for config file.
			if (file_exists('_includes/config.inc.php')) {
				//bad
				echo '<h2>Error</h2><p class="error">It appears installation is already complete. If you are experiencing problems, delete <strong>/includes/config.inc.php</strong> and then refresh this page.</p>';
				exit();
			}
			
			//now that all is well, continue...
			//clear file structure cache.
			clearstatcache();
			//check if includes is writable.
			if (!is_writable('_includes/')) {
				//not writable.
				echo '<h2>Error</h2><p class="error">I do not have writable permissions for the <strong>includes</strong> directory!</p>';
				//check if we're running on windows or linux...
				if (strpos(strtolower($_SERVER['SERVER_SOFTWARE']),"win") !== false) {
					//windows
					echo '<p>You need to allow the IIS user, or Service user full permissions to this directory.</p>';
				} else {
					//linux
					echo '<p>I need to have 777 permissions for this directory, if you are the server administrator, you should know how to do this.
					If you\'re just the site administrator, login to this site via FTP and use your client to change the permissions.</p>';
				}
				exit();
			}
			
			
			//check steps:
			// 1 ---------------------------------------------------------------------------------------
			if (isset($_POST['submit_step1'])) {
				
				$lang_file = stripslashes($_POST['lang']);
				if (is_file('_includes/lang/lang.'.$lang_file.'.php')){
					$_SESSION['lang'] = $lang_file;
					include('_includes/lang/lang.'.$lang_file.'.php');
				}
				$step = 2;
			
			// 2 ---------------------------------------------------------------------------------------
			}elseif (isset($_POST['submit_step2'])) {
				//check if database settings are correct
				$db = NewADOConnection('mysql');
				if ($db->Connect(trim(stripslashes($_POST['db_hostname'])), trim(stripslashes($_POST['db_username'])), trim(stripslashes($_POST['db_password'])), trim(stripslashes($_POST['db_database'])))) {

					//check that passwords match
					if ($_POST['admin_pass'] == $_POST['admin_pass2']) {
						if (strlen(trim($_POST['admin_pass'])) == 0) {
							$error = 'Password cannot be blank';
						} else {

							//ok, start making things happen!
					
							//determine baseurl
							$self = GetFilename($_SERVER['PHP_SELF']);
							if (strpos($_SERVER['REQUEST_URI'],'?') === false) {
								$baseurl = trim($_SERVER['REQUEST_URI'],$self);
							} else {
								$baseurl = trim(substr($_SERVER['REQUEST_URI'],0,strpos($_SERVER['REQUEST_URI'],'?')-1),$self);
							}
							if (strlen($baseurl) == 0) {
								$baseurl = '/';
							}
							//end determine baseurl
							$keys = array(
								'[db_hostname]'=>trim(stripslashes($_POST['db_hostname'])),
								'[db_username]'=>trim(stripslashes($_POST['db_username'])),
								'[db_password]'=>trim(stripslashes($_POST['db_password'])),
								'[db_database]'=>trim(stripslashes($_POST['db_database'])),
								'[prefix]'=>trim(stripslashes($_POST['db_prefix'])),
								'[baseurl]'=>$baseurl,
								'[admin_user]'=>stripslashes($_POST['admin_user']),
								'[admin_pass]'=>stripslashes($_POST['admin_pass']),
								'[install_id]'=>md5(time()),
								'[timezone]'=>$_POST['timezone'],
								'[lang]'=>$_SESSION['lang']
							);
						
							//save config.inc.php
							if (file_exists('_includes/install/config.inc.php.tpl')) {
								$config = readfile_chunked('_includes/install/config.inc.php.tpl');
								$config = ApplyWildcards($config,$keys);
								//save file
								if (!$handle = fopen('_includes/config.inc.php', 'a')) {
										$error = 'Could not write to <strong>_includes/config.inc.php</strong>';
								} else {
									// Write $somecontent to our opened file.
									if (fwrite($handle, $config) === FALSE) {
										echo "Cannot write to file '_includes/config.inc.php'";
										exit;
									}								 
								  fclose($handle);
								
						
									//ok
									//now execute sql
									$errors = array();
									if (file_exists('_includes/install/afb.xml')) {
										
										$xml = readfile_chunked('_includes/install/afb.xml');
										//GET TABLES
										preg_match_all ("'<table>(.*?)</table>'si", $xml, $tables);  //find the ITEMS, and put them into an array
										$tables = $tables[1]; //set the array
					
										for ($y=0;$y<count($tables);$y++) {
											//EACH TABLE
											preg_match_all ("'<name>(.*?)</name>'si", $tables[$y], $name);
											preg_match_all ("'<test_sql>(.*?)</test_sql>'si", $tables[$y], $test_sql);
											preg_match_all ("'<table_sql>(.*?)</table_sql>'si", $tables[$y], $table_sql);
											preg_match_all ("'<table_data>(.*?)</table_data>'si", $tables[$y], $table_data);
											preg_match_all ("'<update_sql>(.*?)</update_sql>'si", $tables[$y], $update_sql);
											//set the arrays
											$name = ApplyWildcards(trim($name[1][0]),$keys);
											$test_sql = ApplyWildcards(trim($test_sql[1][0]),$keys);
											$table_sql = ApplyWildcards(trim($table_sql[1][0]),$keys);
											$table_data = ApplyWildcards($table_data[1],$keys);
											$update_sql = ApplyWildcards($update_sql[1],$keys);
											
											//TEST TABLE
											if (strlen($test_sql) > 0) {
												$result = $db->Execute($test_sql);
												if ($result) {
													$success[] = 'Found <strong>' . $name . '</strong>';
													//apply updates to existing table...
													for ($z=0;$z<count($update_sql);$z++) {
														if (strlen(trim($update_sql[$z])) > 0) {
															$result = $db->Execute($update_sql[$z]);
															if ($result) {
																$updates[] = 'Update ' . $z . ' applied to <strong>' . $name . '</strong> &nbsp; <em>' . $update_sql[$z] . '</em>';
															} else {
																$updates[] = 'Update ' . $z . ' already applied to <strong>' . $name . '</strong> &nbsp; <em>' . $update_sql[$z] . '</em>';
															}
														}
													}
									
												} else {
													//CREATE TABLE
													if (strlen($table_sql) > 0) {
														$result = $db->Execute($table_sql);
														if ($result) {
															$success[] = 'Created <strong>' . $name . '</strong>';
															//ADD DATA
															for ($z=0;$z<count($table_data);$z++) {
																if (strlen(trim($table_data[$z])) > 0) {
																	$result = $db->Execute($table_data[$z]);
																	if ($result) {
																		$success[] = 'Added data to <strong>' . $name . '</strong>';
																	} else {
																		$errors[] = getLangTerm('insert-data-err',false).': '.$name.'<br />'.$db->ErrorMsg();
																	}
																}
															}
														} else {
															$errors[] = getLangTerm('create-table-err',false).': '.$name.'<br />'.$db->ErrorMsg();
														}
													}
												}
											}							
											//END EACH TABLE
										}	
										
								
										
										if (count($errors) == 0) {
						
											//ok!!
											$step = 3;
										} else {
											$error = '<ul><li>'.implode('</li><li>',$errors) . '</li></ul>';
											unlink('_includes/config.inc.php');
										}
										
									} else {
										$error = getLangTerm('install-err-3',false);
										unlink('_includes/config.inc.php');
									}
									
								}
								
							} else {
								$error = getLangTerm('install-err-2',false);
							}
							
						
							
						}
					} else {
						$error = getLangTerm('password-mismatch',false);
					}

				} else {
					$step = 2;
					$error = getLangTerm('install-err-1',false).'<br />'.$db->ErrorMsg();
				}
				
			} //end if submit check
			

			
			switch ($step){
				
				//----------------------------------------------------------------------------------------
				//Step 2
				case 2:
					
					?>						
					<h2><?php echo htmlentities(getLangTerm('mysql-details',false)); ?></h2>
					<?php
						if (strlen($error) > 0) {
							?>
							<p class="error"><?php echo $error; ?></p>
							<?php
						}
					?>
					<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="step1">
						
						<table border="0" align="center" width="450">
							<tr>
								<td width="250">
									<label for="db_hostname"><?php echo htmlentities(getLangTerm('db-host',false)); ?>:</label>
								</td>
								<td width="200">
									<input type="text" name="db_hostname" id="db_hostname" value="<?php if (isset($_POST['db_hostname'])) { echo stripslashes($_POST['db_hostname']); } else { echo 'localhost'; } ?>" style="width:200px;" />
								</td>
							</tr>
							<tr>
								<td width="250">
									<label for="db_database"><?php echo htmlentities(getLangTerm('db-name',false)); ?>:</label>
								</td>
								<td width="200">
									<input type="text" name="db_database" id="db_database" value="<?php if (isset($_POST['db_database'])) { echo stripslashes($_POST['db_database']); } else { echo 'ajaxfb'; } ?>" style="width:200px;" />
								</td>
							</tr>
							<tr>
								<td width="250">
									<label for="db_username"><?php echo htmlentities(getLangTerm('db-un',false)); ?>:</label>
								</td>
								<td width="200">
									<input type="text" name="db_username" id="db_username" value="<?php if (isset($_POST['db_username'])) { echo stripslashes($_POST['db_username']); } else { echo 'root'; } ?>" style="width:200px;" />
								</td>
							</tr>
							<tr>
								<td width="250">
									<label for="db_password"><?php echo htmlentities(getLangTerm('db-pw',false)); ?>:</label>
								</td>
								<td width="200">
									<input type="text" name="db_password" id="db_password" value="<?php if (isset($_POST['db_password'])) { echo stripslashes($_POST['db_password']); } ?>" style="width:200px;" />
								</td>
							</tr>
							<tr>
								<td width="250">
									<label for="db_prefix"><?php echo htmlentities(getLangTerm('table-prefix',false)); ?>:</label>
								</td>
								<td width="200">
									<input type="text" name="db_prefix" id="db_prefix" value="<?php if (isset($_POST['db_prefix'])) { echo stripslashes($_POST['db_prefix']); } else { echo 'afb_'; } ?>" style="width:200px;" />
								</td>
							</tr>
						</table>
						
						<h2><?php echo htmlentities(getLangTerm('admin-account',false)); ?></h2>
						<table border="0" align="center" width="450">
							<tr>
								<td width="250">
									<label for="admin_user"><?php echo htmlentities(getLangTerm('administrator',false)); ?> <?php echo getLangTerm('username',false); ?>:</label>
								</td>
								<td width="200">
									<input type="text" name="admin_user" id="admin_user" value="<?php if (isset($_POST['admin_user'])) { echo stripslashes($_POST['admin_user']); } else { echo 'admin'; } ?>" style="width:200px;" />
								</td>
							</tr>
							<tr>
								<td width="250">
									<label for="admin_pass"><?php echo htmlentities(getLangTerm('password',false)); ?>:</label>
								</td>
								<td width="200">
									<input type="password" name="admin_pass" id="admin_pass" value="<?php if (isset($_POST['admin_pass'])) { echo stripslashes($_POST['admin_pass']); } ?>" style="width:200px;" />
								</td>
							</tr>
							<tr>
								<td width="250">
									<label for="admin_pass2"><?php echo htmlentities(getLangTerm('confirm',false)); ?>:</label>
								</td>
								<td width="200">
									<input type="password" name="admin_pass2" id="admin_pass2" value="<?php if (isset($_POST['admin_pass2'])) { echo stripslashes($_POST['admin_pass2']); } ?>" style="width:200px;" />
								</td>
							</tr>
						</table>
						
						<h2><?php echo htmlentities(getLangTerm('localisation',false)); ?></h2>
						<table border="0" align="center" width="450">
							<tr>
								<td width="250">
									<label for="timezone"><?php echo htmlentities(getLangTerm('timezone',false)); ?></label>
								</td>
								<td width="200">
									<select name="timezone" style="width:200px;">
										<?php
										//get default
										$thisoffset = date("Z");
										for ($x=-12;$x<14;$x++) {
											$s = '';
											if ((isset($_POST['timezone']) && $_POST['timezone'] == ($x*60*60)) || (!isset($_POST['timezone']) && $thisoffset == ($x*60*60))) {
												$s = ' selected="selected"';
											}
											
											$tz = 'GMT ';
											if ($x<0) {
												$tz .= '-';
											} elseif ($x>0) {
												$tz .= '+';
											}
											if (strlen($x) == 1) {
												$tz .= '0';
											}
											$tz.=$x.':00';
											
											?>
											<option value="<?php echo ($x*60*60); ?>"<?php echo $s; ?>><?php echo $tz; ?></option>
											<?php
										}
										?>
									</select>
								</td>
							</tr>
							<tr>
								<td>&nbsp;
									
								</td>
							</tr>
							<tr>
								<td align="right" colspan="2">
									<input type="submit" name="submit_step2" value="<?php echo htmlentities(getLangTerm('continue','"')); ?> &raquo;" class="button" />
								</td>
							</tr>
							
						</table>
						
					</form>
					<?php
					break;
					
				//----------------------------------------------------------------------------------------
				//Step 3
				case 3:
					?>
					<h2><?php echo htmlentities(getLangTerm('congratulations',false)); ?></h2>
					<p><?php echo htmlentities(getLangTerm('app-installed',false)); ?></p>
					<ul>
						<li><a href="index.php"><?php echo htmlentities(getLangTerm('begin-using',false)); ?></a></li>
					</ul>
					<?php
					break;
				
				//----------------------------------------------------------------------------------------
				//Step 1
				default:
					
					//get languages
					$lang_path = '_includes/lang/';
					
					$files = array();
					$filedir = $lang_path;
					if (is_dir($filedir)) {
						$handle=opendir($filedir); 
						while (false !== ($file = readdir($handle))) {
							//echo $file . '<br />';
							if ($file != "." && $file != "..") { 	
								$tempext = strtolower(substr($file, -3, 3));
								if ($tempext == "php") {
									//is script
									$files[] = array('file'=>$file);
								}
							} 
						}
						closedir($handle); 
					}
					
					for ($x=0;$x<count($files);$x++) {
						$tempname = $files[$x]['file'];
						
						//open each file
						$contents = readfile_chunked($lang_path.$files[$x]['file']);
						//check for <name> tags
						preg_match("'<name>(.*?)</name>'si", $contents,$titles);  //find the TITLE from the ITEM, and put them into an array
						$title = trim($titles[1]);
						if (strlen($title) > 0) {
							$files[$x]['name'] = $title;
						}
						//check for <abbrev> tags
						preg_match("'<abbrev>(.*?)</abbrev>'si", $contents,$abbrev);  //find the TITLE from the ITEM, and put them into an array
						$abbrev = trim($abbrev[1]);
						if (strlen($abbrev) > 0) {
							$files[$x]['abbrev'] = $abbrev;
						}
					}
					
					
					?>
					
					<h2>Step 1 of 2</h2>
					<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="step1">
						
						<table border="0" align="center" width="450">
							<tr>
								<td width="250">
									<label for="lang">Language:</label>
								</td>
								<td width="200">
									<select name="lang" style="width:200px;">
										<?php
										for ($x=0;$x<count($files);$x++){
											$s = '';
											if ($files[$x]['abbrev'] == 'en'){
												$s = ' selected="selected"';
											}
											?>
											<option value="<?php echo $files[$x]['abbrev']; ?>"<?php echo $s; ?>><?php echo htmlentities($files[$x]['name']); ?></option>
											<?php
										}
										?>
									</select>
								</td>
							</tr>
							<tr>
								<td>&nbsp;
									
								</td>
							</tr>
							<tr>
								<td width="250">&nbsp;
									
								</td>
								<td align="right" width="200">
									<input type="submit" name="submit_step1" value="Continue &raquo;" class="button" />
								</td>
							</tr>
							
						</table>
					</form>
					
					<p>Cookies must be enabled to complete installation</p>
					<?php
					
					break;
					
			}
			?>
		</div>
	</div>
</body>
</html>