<?php

/********************************************************************************
	- MemHT Portal -
	
	Copyright (C) 2007-2008 by Miltenovik Manojlo
	http://www.memht.com
	
	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your opinion) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License along
	with this program; if not, see <http://www.gnu.org/licenses/> (GPLv2)
	or write to the Free Software Foundation, Inc., 51 Franklin Street,
	Fifth Floor, Boston, MA02110-1301, USA.
		
********************************************************************************/

require("template.php");
echo "<script type='text/javascript' src='boxover.js'></script>\n";

if (isSet($_POST['step'])) { $step = intval($_POST['step']); } else { $step = 1; }
$success = true;

template_header($step);

	switch($step) {
		default:
		case 1: license(); break;
		case 2: requirements(); break;
		case 3: dbconfig(); break;
		case 4: siteinfo(); break;
		case 5: configure(); break;
		case 6: account(); break;
		case 7: import(); break;
		case 8: finish(); break;
	}

template_footer();

function license() {
	if (file_exists("../inc/inc_config.php")) {
		echo "<div class='error' align='center'><b>The configuration file already exists, the installation cannot proceed!</b><br>If you want to reinstall your portal, delete the inc/inc_config.php file</div>";
	} else {
		?>
		<form id='form' name='form' method='post' action='install_safe.php'>
		<div class='title'>License</div>
		<div class='spacer'></div>
		<div><iframe src="license.html" frameborder="0" scrolling="auto" class="license"></iframe></div>
		<div class='spacer'></div>
		<div align="right"><input type='submit' name='Submit' value='Accept' class='button'></div>
		<input type='hidden' name='step' value='2'>
		</form>
		<?php
	}
}

function requirements() {
	if (file_exists("../inc/inc_config.php")) {
		echo "<div class='error' align='center'><b>The configuration file already exists, the installation cannot proceed!</b><br>If you want to reinstall your portal, delete the inc/inc_config.php file</div>";
	} else {
		$dir = pathinfo($_SERVER['SCRIPT_NAME']); $dir = $dir['dirname'];
		$dir = str_replace("/install","",$dir);
		if ($dir=="/") { $dir = ""; }
		$path = $host.$dir;
		//HTACCESS i
		if ($content = @file_get_contents(".htaccess")) {
			$content = str_replace("RewriteBase /install/","RewriteBase {$dir}/install/",$content);
			if (is_writable(".htaccess")) {
				$continue = true;	
			} else {
				if (@chmod(".htaccess",0755)) {
					$continue = true;
				} else {
					$continue = false;
				}
			}
			if ($continue) {
				if ($handle = @fopen(".htaccess","w")) {
					@fwrite($handle,$content);
					@fclose($handle);
				}
				@chmod(".htaccess",0644);	
			}
		}
		//HTACCESS e
		//if (!eregi("localhost",$_SERVER['HTTP_HOST'])) {
			?>
			<script type="text/javascript">
				function getXMLHttpRequestObject() {
					var xmlobj;
					try {
						//Native support: Gecko,Opera,IE7,Safari etc
						xmlobj = new XMLHttpRequest();
					} catch(e) {
						try {
							//ActiveX support: IE6
							xmlobj = new ActiveXObject("Msxml2.XMLHTTP");
						} catch (e) {
							try {
								//ActiveX support: IE5.5,IE5
								xmlobj = new ActiveXObject("Microsoft.XMLHTTP");
							} catch (e) {
								//Ajax not supported
								xmlobj = null;
								return false;
							}
						}
					}
					return xmlobj;
				}
				
				//Request url content
				function requestContent(url) {
					xmlHttpRequest.open("GET",url,true);
					xmlHttpRequest.onreadystatechange = statusListener;
					xmlHttpRequest.send(null);
				}
				
				function statusListener() {
					if (xmlHttpRequest.readyState==4) {
						if (xmlHttpRequest.status==200) {
							document.getElementById('modrewcont').innerHTML = "<span class='yes'>Available</span";
							var today = new Date();
							var the_cookie_date = new Date(today.getTime() + (1000 * 60 * 60));
							var the_cookie = "modrew=true";
							var the_cookie = the_cookie + ";expires=" + the_cookie_date;
							document.cookie=the_cookie;
						} else {
							document.getElementById('modrewcont').innerHTML = "<span class='no'>Unavailable</span>";
							var today = new Date();
							var the_cookie_date = new Date(today.getTime() + (1000 * 60 * 60));
							var the_cookie = "modrew=false";
							var the_cookie = the_cookie + ";expires=" + the_cookie_date;
							document.cookie=the_cookie;
						}
					}
				}
				
				xmlHttpRequest = getXMLHttpRequestObject();
				document.onload = requestContent("modrewrite.test?nocache="+new Date().getTime());
			</script>
			<?php
		//}
		?>

		<form id='form' name='form' method='post' onSubmit='return gotodbconfig();'>
		<div class='title'>Required components</div>
		<div class='spacer'></div>
		
		<table width="100%" class="box" cellpadding="2" cellspacing="0">
			<tr>
				<td>PHP version (4.3.0 or higher)</td>
				<td align="right"><?php echo (phpversion()>="4.3.0") ? "<span class='yes'>Yes</span>" : "<span class='no'>No</span>" ; ?></td>
			</tr>
			<tr>
				<td class="dark">MySQL 4.1</td>
				<td align="right" class="dark"><?php echo (extension_loaded('mysql')) ? "<span class='yes'>Available</span>" : "<span class='no'>Unavailable</span>" ; ?></td>
			</tr>
			<tr>
				<td>Writable configuration folder</td>
				<td align="right"><?php echo (is_writable("../inc/")) ? "<span class='yes'>Writable</span>" : "<span class='no'>Unwritable</span>" ; ?></td>
			</tr>
		</table>
		<div class='spacer'></div>
		<div align="right"><input type='submit' name='Submit' value='Next' class='button'></div>
		<input type='hidden' name='step' value='3'>
		</form>
		<?php
	}
}

function dbconfig() {
	if (file_exists("../inc/inc_config.php")) {
		echo "<div class='error' align='center'><b>The configuration file already exists, the installation cannot proceed!</b><br>If you want to reinstall your portal, delete the inc/inc_config.php file</div>";
	} else {
		?>
		<form id='form' name='form' method='post' action='install_safe.php' onSubmit='return validate();'>
		<div class='title'>Database configuration</div>
		<div class='spacer'></div>
		
		<table width="100%" class="box" cellpadding="2" cellspacing="0">
			<tr>
				<td>Database host <img src="images/info.gif" align="absbottom" title="header=[Database host] body=[Insert the database host address<br><b>Example:</b> '<i>localhost</i>' or '<i>123.123.123.123</i>']"></td>
				<td align="right"><input name='dbhost' type='text' class='input'></td>
			</tr>
			<tr>
				<td class="dark">Database username <img src="images/info.gif" align="absbottom" title="header=[Database username] body=[Insert your database username<br><b>Example:</b> '<i>root</i>']"></td>
				<td align="right" class="dark"><input name='dbuser' type='text' class='input'></td>
			</tr>
			<tr>
				<td>Database password <img src="images/info.gif" align="absbottom" title="header=[Database password] body=[Insert your database password]" /></td>
				<td align="right"><input name='dbpass' type='text' class='input'></td>
			</tr>
			<tr>
				<td class="dark">Database name <img src="images/info.gif" align="absbottom" title="header=[Database name] body=[Insert the database name<br>If the specified database cannot be found, the installer will try to create it<br><b>Example:</b> '<i>memht</i>']"></td>
				<td align="right" class="dark"><input name='dbname' type='text' class='input'></td>
			</tr>
			<tr>
				<td>Clean the database before installing new tables <img src="images/info.gif" align="absbottom" title="header=[Warning] body=[This option will delete <b>all</b> tables present into the selected database!]"></td>
				<td align="right"><input name='dbclean' type='checkbox' class='input_nob' checked></td>
			</tr>	
		</table>
		
		<div class='spacer'></div>
		<div align="right"><input type='submit' name='Submit' value='Next' class='button'></div>
		<input type='hidden' name='step' value='4'>
		<input type='hidden' name='install' value='true'>
		</form>
		<?php
	}
}

function siteinfo() {
	if (file_exists("../inc/inc_config.php")) {
		echo "<div class='error' align='center'><b>The configuration file already exists, the installation cannot proceed!</b><br>If you want to reinstall your portal, delete the inc/inc_config.php file</div>";
	} else {
		$dbhost = (isset($_POST['dbhost'])) ? $_POST['dbhost'] : "" ;
		$dbuser = (isset($_POST['dbuser'])) ? $_POST['dbuser'] : "" ;
		$dbpass = (isset($_POST['dbpass'])) ? $_POST['dbpass'] : "" ; 
		$dbname = (isset($_POST['dbname'])) ? $_POST['dbname'] : "" ;
		$dbclean = (isset($_POST['dbclean'])) ? $_POST['dbclean'] : "" ;
		
		if ($db = @mysql_connect("$dbhost","$dbuser","$dbpass")) {
			if (@mysql_select_db("$dbname")) {
				if ($dbclean) {
					$result = mysql_list_tables($dbname);
					$i = 0;
					$delete = array();
					while ($i < mysql_num_rows($result)) {
						$name_table = mysql_table_name($result, $i);
						$delete[] = "`".$name_table."`";
						$i++;
					}
					$sql = "DROP TABLE IF EXISTS ".implode(",",$delete);
					if ($result_set = @mysql_query($sql)) {
						$proceed = true;
					} else {
						$proceed = false;
						$error = "Cannot clean the database";
					}
				}
				$proceed = true;
			} else {
				if (@mysql_query("CREATE DATABASE `$dbname`;")) {
					mysql_select_db("$dbname");
					$proceed = true;
				} else {
					$proceed = false;
					$error = "Cannot create the database";
				}
			}
		} else {
			$proceed = false;
			$error = "Cannot connect to the database";
		}
			
		if ($proceed) {
			$success = true;
			require("functions.php");
			parse_mysql_dump("sql/structure.sql");
			if ($success) { writeConfigFile($dbhost,$dbuser,$dbpass,$dbname); }
			mysql_close($db);
			$host = "http://".$_SERVER['HTTP_HOST'];
			$dir = pathinfo($_SERVER['SCRIPT_NAME']); $dir = $dir['dirname'];
			$dir = str_replace("/install","",$dir);
			if ($dir=="/") { $dir = ""; }
			$path = $host.$dir;
			//HTACCESS i
			if ($content = @file_get_contents("../.htaccess")) {
				if (!stristr($content,"RewriteBase {$dir}/")) {
					$content = str_replace("RewriteBase /","RewriteBase {$dir}/",$content);
					$content = str_replace("ErrorDocument 500 /index","ErrorDocument 500 {$dir}/index",$content);
					$content = str_replace("ErrorDocument 404 /index","ErrorDocument 404 {$dir}/index",$content);
					$content = str_replace("ErrorDocument 403 /index","ErrorDocument 403 {$dir}/index",$content);
					$content = str_replace("ErrorDocument 401 /index","ErrorDocument 401 {$dir}/index",$content);
					$content = str_replace("ErrorDocument 400 /index","ErrorDocument 400 {$dir}/index",$content);
					if (is_writable("../.htaccess")) {
						$continue = true;	
					} else {
						if (@chmod("../.htaccess",0755)) {
							$continue = true;
						} else {
							$continue = false;
						}
					}
					if ($continue) {
						if ($handle = @fopen("../.htaccess","w")) {
							@fwrite($handle,$content);
							@fclose($handle);
						}
						@chmod("../.htaccess",0644);	
					}
				}
			}
			//HTACCESS e
			?>
			<form id='form' name='form' method='post' action='install_safe.php' onSubmit='return validate_siteinfo();'>
			<div class='title'>Site informations</div>
			<div class='spacer'></div>
			
			<table width="100%" class="box" cellpadding="2" cellspacing="0">
				<tr>
					<td>Site name</td>
					<td align="right"><input name='name' value='MemHT Portal' type='text' class='input'></td>
				</tr>
				<tr>
					<td class="dark">Site url <img src="images/info.gif" align="absbottom" title="header=[Warning] body=[The installer will try to detect automatically the site url. Check it before continuing, it's very important that is correct!]"></td>
					<td align="right" class="dark"><input name='url' type='text' value='<?php echo $path; ?>' class='input'></td>
				</tr>
				<tr>
					<td>Webmaster mail</td>
					<td align="right"><input name='email' type='text' class='input'></td>
				</tr>
			</table>
			
			<div class='spacer'></div>
			<div align="right"><input type='submit' name='Submit' value='Next' class='button'></div>
			<input type='hidden' name='step' value='5'>
			<input type='hidden' name='insert' value='true'>
			</form>
			<?php
		} else {
			?>
			<div class='title'>Error</div>
			<div class='spacer'></div>
			<?php
			echo "<div class='box'><b>$error</b></div>";
			?>
			<div class='spacer'></div>
			<form id='form' name='form' method='post' action='install_safe.php'>
			<div><input type='submit' name='Submit' value='Back' class='button'></div>
			<input type='hidden' name='step' value='3'>
			
			<input type='hidden' name='dbhost' value='<?php echo $dbhost; ?>'>
			<input type='hidden' name='dbuser' value='<?php echo $dbuser; ?>'>
			<input type='hidden' name='dbpass' value='<?php echo $dbpass; ?>'>
			<input type='hidden' name='dbname' value='<?php echo $dbname; ?>'>
			<input type='hidden' name='dbclean' value='<?php echo $dbclean; ?>'>
			</form>
			<?php
		}
	}
}

function configure() {
	require("../inc/inc_config.php");
	require("functions.php");
	$db = mysql_connect("$db_host","$db_user","$db_pass");
	mysql_select_db("$db_name");
	
	if (isset($_POST['insert'])) {
		$modrew = ($_COOKIE['modrew']=="true") ? 1 : 0 ;
		$name = (isset($_POST['name'])) ? $_POST['name'] : "" ;
		$url = (isset($_POST['url'])) ? $_POST['url'] : "" ;
		$email = (isset($_POST['email'])) ? $_POST['email'] : "" ;
		
		$url = (eregi("/",$url{strlen($url)-1})) ? substr($url,0,strlen($url)-1) : $url ;
		
		mysql_query("TRUNCATE `memht_config`");
		mysql_query("INSERT INTO `memht_config` (nome,site_url,descrizione,metatags,lingua,email,modrewrite)
					VALUES ('".inCode($name)."','".inCode($url)."','Put here your site description','put,here,your,meta,tags,keywords,separated,by,comma','english','".inCode($email)."','$modrew')");
	}
	?>
	<form id='form' name='form' method='post' action='install_safe.php'>
		<div class='title'>Select your configuration</div>
		<div class='spacer'></div>
		<div class='info' style='margin-bottom:4px; font-size:9px;'>By chosing the initial configuration, the wizard will install the best combination of addons and blocks for your specific needs.<br>You'll be able to use all addons and customize the entire system in any time, indipendently of your choise</div>
		<table width="100%" class="box" cellpadding="2" cellspacing="0">
			<tr>
				<td width="1%" valign="top"><img src="images/cms.png" alt="CMS" title="Content Management System"/></td>
				<td width="49%" valign="top">
					<div style='color:#990000; margin-bottom:6px;'><b>Content Management System</b> <img src="images/view.gif" align="absbottom" title="header=[Content Management System] body=[<img src='images/screen_cms.png'>]"></div>
					<div style='font-size:9px;'>
						Default homepage: <i>News</i><br />
						Template: <i>Memht</i><br />
						Example site: <a href='http://www.memht.com' target='_blank' title='MemHT.com'><i>MemHT.com</i></a><br />
					</div>
				</td>
				<td width="1%" valign="top"><img src="images/blog.png" alt="Blog" title="Blog"/></td>
				<td width="49%" valign="top">
					<div style='color:#990000; margin-bottom:6px;'><b>Blog</b> <img src="images/view.gif" align="absbottom" title="header=[Blog] body=[<img src='images/screen_blog.png'>]"></div>
					<div style='font-size:9px;'>
						Default homepage: <i>Blog</i><br />
						Template: <i>MyBlog</i><br />
						Example site: <a href='http://www.scriptips.com' target='_blank' title='ScripTips'><i>ScripTips.com</i></a><br />
					</div>
				</td>
			</tr>
		</table>
		
		<div class='spacer'></div>
		<div align="right"><select name='configuration' class='button'><option value='cms'>CMS</option><option value='blog'>Blog</option></select> <input type='submit' name='Submit' value='Next' class='button'></div>
		<input type='hidden' name='step' value='6'>
		<input type='hidden' name='select' value='true'>
		<input type='hidden' name='email' value='<?php echo $email; ?>'>
	</form>
	<?php
}

function account() {
	require("../inc/inc_config.php");
	$db = mysql_connect("$db_host","$db_user","$db_pass");
	mysql_select_db("$db_name");
	$email = (isset($_POST['email'])) ? $_POST['email'] : "" ;
	
	if (isset($_POST['select'])) {
		$configuration = (isset($_POST['configuration'])) ? $_POST['configuration'] : "cms" ;
		$success = true;
		require("functions.php");
		parse_mysql_dump("sql/simpledata_{$configuration}.sql");
		if (!$success) {
			echo "<div class='warning' style='margin-bottom:4px; font-size:9px;'><b>Error in adding the simple data</b><br><span style='font-size:9px;'><i>The installation can continue, but the site will be empty, wuthout any simple information, article or post.</i></span></div>";
		}
		if ($configuration=="blog") {
			mysql_query("UPDATE `memht_config` SET template='myblog',defpage='blog'");
		}
	}

	?>
	<form id='form' name='form' method='post' action='install_safe.php' onSubmit='return validate_account();'>
		<div class='title'>Account</div>
		<div class='spacer'></div>
		
		<table width="100%" class="box" cellpadding="2" cellspacing="0">
			<tr>
				<td>Username</td>
				<td align="right"><input name='user' type='text' class='input'></td>
			</tr>
			<tr>
				<td class="dark">Password</td>
				<td align="right" class="dark"><input name='pass' type='text' class='input'></td>
			</tr>
		</table>
		
		<div class='spacer'></div>
		<div align="right"><input type='submit' name='Submit' value='Next' class='button' onClick="javascript:printAlert();"></div>
		<input type='hidden' name='step' value='7'>
		<input type='hidden' name='email' value='<?php echo $email; ?>'>
		</form>
		<script type="text/javascript">
			function printAlert() {
				alert("The next step could need some time to finish, do not stop the script execution");
			}
		</script>
	<?php
	mysql_close($db);
}

function import() {
	require("../inc/inc_config.php");
	require("functions.php");
	$db = mysql_connect("$db_host","$db_user","$db_pass");
	mysql_select_db("$db_name");
	
	$user = (isset($_POST['user'])) ? $_POST['user'] : "" ;
	$pass = (isset($_POST['pass'])) ? $_POST['pass'] : "" ;
	$email = (isset($_POST['email'])) ? $_POST['email'] : "" ;
	
	mysql_query("INSERT INTO `memht_utenti` (id,user,pass,email,regdate,post,title_enabled,title_text,rank,enabled)
				VALUES (null,'".inCode($user)."','".md5(inCode($pass))."','".inCode($email)."',NOW(),'1','1','Administrator','4','1')");
	
	mysql_query("UPDATE `memht_articoli` SET autore='$user',email='$email'");
	mysql_query("UPDATE `memht_blog_posts` SET author='$user'");
	mysql_query("UPDATE `memht_comments` SET name='$user',email='$email'");
	mysql_query("UPDATE `memht_download` SET autore='$user'");
	mysql_query("UPDATE `memht_forum_posts` SET author='$user'");
	mysql_query("UPDATE `memht_guide` SET autore='$user',email='$email'");
	mysql_query("UPDATE `memht_messaggi` SET autore='$user'");
	mysql_query("UPDATE `memht_mypage` SET author='$user'");
	mysql_query("UPDATE `memht_news` SET autore='$user',email='$email'");
	mysql_query("UPDATE `memht_messagebox` SET autore='$user',email='$email'");
	
	?>
	<div class='title'>Apply data</div>
	<div class='spacer'></div>
	<div class='spacer'></div>
	<form id='form' name='form' method='post' action='install_safe.php'>		
		<div align="right"><input type='submit' name='Submit' value='Next' class='button'></div>
		<input type='hidden' name='step' value='8'>
	</form>
	<?php
	mysql_close($db);
}

function finish() {		
	?>
	<div class='title'>MemHT Portal has been installed successfully!</div>
	<div class='spacer'></div>
	<div class='box'><b>Attention: Delete the installation folder and files!</b></div>
	<div class='spacer'></div>
	<div align="right"><input type='button' name='button' value='Site home' class='button' onClick="window.location='../index.php';"> <input type='button' name='button' value='Administration' class='button' onClick="window.location='../admin.php';"></div>
	<?php
}

?>