<?php
//////////////////////////////////////////////////////////////////////
//     			Multi Forums Pro Host for phpBB v1.0				//
//					 sebflipper Copyright 2004     					//
//                   http://www.sebflipper.com                      //
//                        Main Script File                          //
//                                                                  //
// Please DO NOT edit this file unless you know what you are doing  //
//                                                                  //
//        By using this script you agree to the Licence             //
//                                                                  //
//////////////////////////////////////////////////////////////////////

//Starting script exe timer
$ss_timing_start_times = explode(' ', microtime());

// For getting post and get stuff for newer versions of PHP
 if ( phpversion() >= "4.2.0")
    {
    extract($_POST);
    extract($_GET);
    } 

// Loading configuration file for the rest of the modules use
// dirname(__FILE__) is a command use to get the location of the script (eg C:\Program Files\EasyPHP\www or /user/bin/hostname/etc)
if(is_file(dirname(__FILE__)."/config/multiforums.config.inc.php"))
{ 
	// If is does then load it into the script
	require dirname(__FILE__)."/config/multiforums.config.inc.php";
}
else
{
	header("Location: config");
	exit;
}

// Check if the system is offline
if ($multiforums_setting[master_offline] == true)
{
        header("Location: $multiforums_setting[offline_error_url]");
        exit;
}

if ($act=="make")
{
	// check if the form is filled in
	if ($board_access_name==true AND $board_name==true AND $cat==true AND $adminname==true AND $adminemail==true)
	{
		echo "<html><head><title>Setup in Progress...</title></head><body><center><h1>Please wait...</h1></center><style type=text/css><!-- a {	color: #FFFFFF; } --></style><font color=#FFFFFF>";
		////////////////////////////
		// Removing any symbols and spaces etc only allowing a-Z 0-9
		$board_access_name = preg_replace('/[^a-zA-Z0-9]/','',$board_access_name); 
		$board_name = preg_replace('/[^a-zA-Z0-9]/','',$board_name);
		$cat = preg_replace('/[^a-zA-Z0-9]/','',$cat);
		$adminname = preg_replace('/[^a-zA-Z0-9]/','',$adminname);						
		
		// Converting any HTML to standard text in the user data
		$adminemail = htmlspecialchars($adminemail);
					
		// Triming blank spaces at the start and end of the user data
		$board_access_name = trim($board_access_name);
		$board_name = trim($board_name);
		$cat = trim($cat);
		$adminname = trim($adminname);
		$adminemail = trim($adminemail);

		////////////////////////////		
		// check for spaces and remove
		$board_access_name = ereg_replace(' ', '', $board_access_name);

		// Convert UPPERCASE to lowercase
		$board_access_name = strtolower($board_access_name);
		$board_name = strtolower($board_name);

		// check if the access name is too long and trim to 15 letters long
		$board_access_name = substr("$board_access_name", 0, 15);
		
		// check to see if they are trying to make a forum with the same name as the settings!
		$find_this = 'multiforums';
		$pos = strpos($board_access_name, $find_this);

		if ($pos === false) 
		{
			$ok = "ok";
		} else {
			echo "<html><body><script language=javascript1.1>alert('Please correct your forum access name'); window.location='javascript:history.back()';</script><noscript>Your browser doesn't support JavaScript 1.1 or it's turned off in your browsers preferences.</noscript></body></html>";
			exit;
		}
		
		// once all the above has been exe'ed it might leave us with nothing! making a '.php' file
		if ($board_access_name == false OR $board_name == false) 
		{
			echo "<html><body><script language=javascript1.1>alert('Please correct your forum access name, only use standard letters'); window.location='javascript:history.back()';</script><noscript>Your browser doesn't support JavaScript 1.1 or it's turned off in your browsers preferences.</noscript></body></html>";
			exit;
		}
		
		// check for illegal names
		// add www and gallery to the list of banned names
		$illegal_names = "www,gallery,$multiforums_setting[illegal_names]";
		$illegal_names_array = explode(",", $illegal_names);
		$illegal_names_array = array_unique ($illegal_names_array);

		$illegal_names_array_count = 0;
		while($check_ban = each($illegal_names_array))
		{	
			if ($board_access_name == $illegal_names_array[$illegal_names_count]) {
				echo "<html><body><script language=javascript1.1>alert('This access name is banned, please choose another name'); window.location='javascript:history.back()';</script><noscript>Your browser doesn't support JavaScript 1.1 or it's turned off in your browsers preferences.</noscript></body></html>";
				exit;
			}
			$illegal_names_count++;
		}					

		////////////////////////////		
		// make random password
		$salt = "abchefghjkmnpqrstuvwxyz0123456789"; 
		srand((double)microtime()*1000000); 
		$i = 0; 
		while ($i <= 7) 
		{ 
			$num = rand() % 33; 
			$tmp = substr($salt, $num, 1); 
			$pass = $pass . $tmp; 
			$i++; 
		} 
		
		$adminpassword_adminemail = $pass;
		$adminpassword = md5($pass);
		
		////////////////////////////
		// check adminemail address
		function checkEmail($email) 
		{
		   if(eregi("^[a-zA-Z0-9_]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]", $email)) 
		   {
			  return FALSE;
		   }
		
		   list($Username, $Domain) = split("@",$email);
		
		   if(getmxrr($Domain, $MXHost)) 
		   {
			  return TRUE;
		   }
		   else 
		   {
			  if(fsockopen($Domain, 25, $errno, $errstr, 30)) 
			  {
				 return TRUE; 
			  }
			  else 
			  {
				 return FALSE; 
			  }
		   }
		}

		if(checkEmail($adminemail) == FALSE)
		{
			echo "<html><body><script language=javascript1.1>alert('Please enter a real email address'); javascript:history.back();</script><noscript>Your browser doesn't support JavaScript 1.1 or it's turned off in your browsers preferences.</noscript></body></html>";
			exit;
		} 
		
		////////////////////////////
		// check if this board access name has been taken or not
		$config_file = "config/".$board_access_name.".php";
		if(is_file("$config_file"))
		{ 
			// If is does then error
			echo "<html><body><script language=javascript1.1>alert('Sorry this board access name is in use, please choose a different one'); javascript:history.back();</script><noscript>Your browser doesn't support JavaScript 1.1 or it's turned off in your browsers preferences.</noscript></body></html>";
			exit;
		}
		
		////////////////////////////
		// check if they have an account already
		$email_check_resultlink = mysql_query("SELECT `admin_email` FROM `multiforums_forums` WHERE 1 AND `admin_email` = '$adminemail' LIMIT 0 , 1");
		$email_check_result = mysql_fetch_array($email_check_resultlink);
		
		if ($adminemail == $email_check_result[admin_email])
		{
			echo "<html><body><script language=javascript1.1>alert('Sorry you can only have one forum'); javascript:history.back();</script><noscript>Your browser doesn't support JavaScript 1.1 or it's turned off in your browsers preferences.</noscript></body></html>";
			exit;
		}
		
		////////////////////////////
		// check for cookie and stop spam accounts
		if ($FreeForumsMakeCookie == true)
		{
			echo "<html><body><script language=javascript1.1>alert('Sorry you can only have one forum'); javascript:history.back();</script><noscript>Your browser doesn't support JavaScript 1.1 or it's turned off in your browsers preferences.</noscript></body></html>";
			exit;
		}
		
		////////////////////////////		
		// all ok make database
		$current_time_stamp = mktime();	
		$avatar_folder = "images/avatars/".$board_access_name;
		
			$filename = dirname(__FILE__)."/multiforums_default_db.sql";
	
			$filesize       = filesize($filename);
			$file_position  = isset($HTTP_GET_VARS['pos']) ? $HTTP_GET_VARS['pos'] : 0;
			$errors         = isset($HTTP_GET_VARS['ignore_errors']) ? 0 : 1;
	
			if (!$fp = fopen($filename,'rb')) 
			{
				echo "Unable to open file $filename";
			}
			

			$buffer = '';
			$inside_quote = 0;
			$quote_inside = '';
			$started_query = 0;
	
			$data_buffer = '';
	
			$last_char = "\n";
	
			// Sets file position indicator
			fseek($fp,$file_position);
	
			while ((!feof($fp) || strlen($buffer))) 
			{
				do 
				{
					// Deals with the length of the buffer
					if (!strlen($buffer)) 
					{
						$buffer .= fread ($fp,1024);
					}
	
					// Fiddle around with the buffers
					$current_char = $buffer[0];
					$buffer = substr($buffer, 1);
	
	
					if ($started_query)
					{
						$data_buffer .= $current_char;
					} 
					elseif (preg_match("/[A-Za-z]/i",$current_char) && $last_char == "\n") 
					{
						$started_query = 1;
						$data_buffer = $current_char;
					} 
					else 
					{
						$last_char = $current_char;
					}
				} while (!$started_query && (!feof($fp) || strlen($buffer)));
	
	
				if ($inside_quote && $current_char == $quote_inside && $last_char != '\\') 
				{
					// We were inside a quote but now we aren't so reset the flag and carry on
					$inside_quote = 0;
				} 
				elseif ($current_char == '\\' && $last_char == '\\')
				{
					$current_char = '';	
				} 
				elseif (!$inside_quote && ($current_char == '"' || $current_char == '`' || $current_char == '\''))
				{
					// We have just entered a new quote
					$inside_quote = 1;
					$quote_inside = $current_char;
				} 
				elseif (!$inside_quote && $current_char == ';') 
				{
					
					// edit database
					$prefix = $board_access_name."_";
					$data_buffer = str_replace("phpbb_", "$prefix", $data_buffer);
					$data_buffer = str_replace("%default_admin_name%", "$adminname", $data_buffer);
					$data_buffer = str_replace("%default_md5_password%", "$adminpassword", $data_buffer);					
					$data_buffer = str_replace("%default_admin_email%", "$adminemail", $data_buffer);					
					$data_buffer = str_replace("%default_time_stamp%", "$current_time_stamp", $data_buffer);
					$data_buffer = str_replace("%board_name%", "$board_name", $data_buffer);
					$data_buffer = str_replace("%phpbb2cookie%", "phpbb_$board_access_name", $data_buffer);
					$data_buffer = str_replace("%server_name%", "$multiforums_setting[server_name]", $data_buffer);
					$data_buffer = str_replace("%script_path%", "$multiforums_setting[script_path]", $data_buffer);										
					$data_buffer = str_replace("images/avatars", "$avatar_folder", $data_buffer);
				
					// End of query so execute query, clear data buffer and advance counter
					mysql_query($data_buffer);
	
					if ($errors && mysql_errno())
					{
						//$new_position = ftell($fp) - strlen($buffer);
						//return $this->restore_error($data_buffer, $new_position);
						echo "<font color=red>There has been a MySQL error, check error message below for details, if this doesn't help check that your connection details are correct, and the MySQL server is stable and running.<br><br><b>MySQL Error Details:</b><br>".mysql_errno().": ".mysql_error()."</font>";
						exit;
					}
	
	
					$data_buffer = '';
					$last_char = "\n";
					$started_query = 0;
				}
	
				$last_char = $current_char;
			}
	
	
			$new_position = ftell($fp) - strlen($buffer) - strlen($data_buffer);
	
			fclose($fp);
			
			////////////////////////////
			// make config file
			// get default contents of a file into a string
			$filename = dirname(__FILE__)."/config_default.php";
			$handle = fopen ($filename, "r");
			$contents = fread ($handle, filesize ($filename));
			fclose ($handle);
			
			// edit file
			$contents = str_replace("%default_board_access_name%", "$board_access_name", $contents);
			$contents = str_replace("%default_board_cat%", "$cat", $contents);	
			$contents = str_replace("%default_sql_host%", "$multiforums_mysql[server]", $contents);
			$contents = str_replace("%default_sql_database%", "$multiforums_mysql[database]", $contents);
			$contents = str_replace("%default_sql_user%", "$multiforums_mysql[db_user]", $contents);
			$contents = str_replace("%default_sql_pass%", "$multiforums_mysql[db_pass]", $contents);
			
			$prefix = $board_access_name."_";
			$contents = str_replace("%prefix%", "$prefix", $contents);
						
			// save file			
			$filename = dirname(__FILE__)."/config/".$board_access_name.".php";
			
			touch ($filename);
			@chmod($filename, 0777);
			
			
			// Let's make sure the file exists and is writable first.
			if (is_writable($filename)) 
			{
			
				// In our example we're opening $filename in append mode.
				// The file pointer is at the bottom of the file hence 
				// that's where $somecontent will go when we fwrite() it.
				if (!$handle = fopen($filename, 'a'))
				{
					 print "Cannot open file ($filename)";
					 exit;
				}
			
				// Write $somecontent to our opened file.
				if (!fwrite($handle, $contents))
				{
					print "Cannot write to file ($filename)";
					exit;
				}
				
				fclose($handle);		
				
				// Making user avatar folder
				if (! is_dir($avatar_folder) )
				{
				 mkdir($avatar_folder, 0777);
				}
				@chmod($avatar_folder, 0777);
								
			}
			else
			{
				print "The file $filename is not writable";
			}

			////////////////////////////			
			// all done set cookie, email them and show form has been setup message and redirect to new forum
			setcookie ("FreeForumsMakeCookie", "true");
			
			$sql_board_access_name = addslashes($board_access_name);
			$sql_current_time_stamp = addslashes($current_time_stamp);
			$sql_board_name = addslashes($board_name);
			$sql_adminemail = addslashes($adminemail);
			$sql_cat = addslashes($cat);			
		
			$insertsql = "INSERT INTO `multiforums_forums` ( `id` , `access_name` , `board_start` , `forum_name` , `cat` , `admin_email` , `online` , `normal_admin_pw`, `c_posts`, `c_members`) VALUES ('', '$sql_board_access_name', '$sql_current_time_stamp', '$sql_board_name', '$sql_cat', '$sql_adminemail', '1', '', '1', '1');";
			$insertsql_result = mysql_query($insertsql);
			
			$to = "$adminemail";
			$subject = "Free phpBB forum Setup"; 
			$message = "Your free phpBB forum has been setup for you at:\n\n$multiforums_setting[mf_url]/?mforum=$board_access_name\n\nYour admin account details: \nUsername: $adminname \nPassword: $adminpassword_adminemail (please change your password when you login)\n\n\n\nThis message was sent from: $multiforums_setting[mf_url]";
			$extra = "From: $multiforums_setting[email]\r\nReply-To: $multiforums_setting[email]\r\n";
			mail("$to", "$subject", "$message", "$extra");
			
			////////////////////////////			
			// email admin with stats
					
			// add an extra one to number of forums (as its just been made!)
			$forums_count++;
		
			//Getting script exe time
			if (!isset($ss_timing_start_times)) 
			{
				
			}
			if (!isset($ss_timing_stop_times))
			{
				$stop_time = explode(' ', microtime());
			}
			else
			{
				$stop_time = $ss_timing_stop_times;
			}
			// do the big numbers first so the small ones aren't lost
			$current = $stop_time[1] - $ss_timing_start_times[1];
			$current += $stop_time[0] - $ss_timing_start_times[0];
			$exec_time = round($current,4);
			
			if ($multiforums_setting[email_new] == "yes")
			{
				$to = $multiforums_setting[email];
				$subject = "Free phpBB forum Setup ($board_access_name)"; 
				$message = "A free phpBB forum has been setup at:\n\n$multiforums_setting[mf_url]/?mforum=$board_access_name\n\nThere are now $forums_count forums. \n\n\n\n($PHP_SELF execution time: $exec_time)";
				$extra = "From: $multiforums_setting[email]\r\nReply-To: $multiforums_setting[email]\r\n";
				mail("$to", "$subject", "$message", "$extra");
			}
			
			if ($FreeForumsMakeCookie==true)
			{
				echo "<html><body><script language=javascript1.1>alert('Success your forum has been setup! Please check your email for your password'); window.location='$multiforums_setting[mf_url]/?mforum=$board_access_name';</script><noscript>Your browser doesn't support JavaScript 1.1 or it's turned off in your browsers preferences.</noscript></body></html>";
				exit;			
			}
			else
			{
				echo "<html><body><script language=javascript1.1>window.location='$PHP_SELF?go=$board_access_name';</script><noscript>Your browser doesn't support JavaScript 1.1 or it's turned off in your browsers preferences.</noscript></body></html>";
			}
	}
	else
	{
		echo "<html><body><script language=javascript1.1>alert('Please fill in the form'); javascript:history.back();</script><noscript>Your browser doesn't support JavaScript 1.1 or it's turned off in your browsers preferences.</noscript></body></html>";
		exit;
	}
}
else
{

	
	if ($go==true)
	{
		setcookie ("FreeForumsMakeCookie", "true");
		echo "<html><body><script language=javascript1.1>alert('Success your forum has been setup! Please check your email for your password'); window.location='$multiforums_setting[mf_url]/?mforum=$go';</script><noscript>Your browser doesn't support JavaScript 1.1 or it's turned off in your browsers preferences.</noscript></body></html>";
		exit;			
	}
}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<title>Welcome to phpBB 2 Installation :: Set Up form</title>
<link rel="stylesheet" href="templates/subSilver/subSilver.css" type="text/css">
<style type="text/css">
<!--
th			{ background-image: url('templates/subSilver/images/cellpic3.gif') }
td.cat		{ background-image: url('templates/subSilver/images/cellpic1.gif') }
td.rowpic	{ background-image: url('templates/subSilver/images/cellpic2.jpg'); background-repeat: repeat-y }
td.catHead,td.catSides,td.catLeft,td.catRight,td.catBottom { background-image: url('templates/subSilver/images/cellpic1.gif') }

/* Import the fancy styles for IE only (NS4.x doesn't use the @import function) */
@import url("templates/subSilver/formIE.css"); 
//-->
</style>
</head>
<body bgcolor="#E5E5E5" text="#000000" link="#006699" vlink="#5584AA">

<script language="JavaScript">
<!--
function submitForm()
{
	document.makeforum.submit();
}
//-->
</script>	
<form name="makeforum" action='<?php echo $PHP_SELF; ?>?act=make' method='POST'>

<table width="100%" border="0" cellspacing="0" cellpadding="10" align="center"> 
	<tr>
		<td class="bodyline" width="100%">

		<table width="100%" border="0" cellspacing="0" cellpadding="0">
			<tr>
				<td><table width="100%" border="0" cellspacing="0" cellpadding="0">
					<tr>
						<td><img src="templates/subSilver/images/logo_phpBB.gif" border="0" alt="Forum Home" vspace="1" /></td>
						<td align="center" width="100%" valign="middle"><span class="maintitle">Welcome to phpBB 2 Installation</span></td>
					</tr>
				</table></td>
			</tr>
			<tr>
				<td><br /><br /></td>
			</tr>
			<tr>
				<td colspan="2"><table width="90%" border="0" align="center" cellspacing="0" cellpadding="0">
					<tr>
						<td><span class="gen">Thank you for choosing phpBB 2. In order to complete this install please fill out the details requested below.</span></td>
					</tr>
				</table></td>
			</tr>
			<tr>
				<td><br /><br /></td>
			</tr>
			<tr>
				<td width="100%" valign="middle">
				<table width="100%" cellpadding="2" cellspacing="1" border="0" class="forumline"><form action="install.php" name="install" method="post">
					<tr>
						<th colspan="2">Basic Configuration</th>
					</tr>
					<tr>
						<td class="row1" align="right" width="35%"><span class="gen"><B>Access name:</B><BR>
					    This is the access name of your board (no spaces)</span></td>
						<td width="65%" valign="middle" class="row2"><input name="board_access_name" type="text" id="board_access_name" value="" /></td>
					</tr>
					<tr>
						<td class="row1" align="right"><span class="gen"><B>The forum name</B>:<BR>
					    This is the name of your forum</span></td>
						<td class="row2"><input name="board_name" type="text" id="board_name" value="" /></td>
					</tr>
					<tr>
						<td class="row1" align="right"><span class="gen"><B>Forum Category</B>:<BR>
					    Select a category for your forum</span></td>
						<td valign="middle" class="row2">
						
						<?php
						// diplay cat list
						$cat_diplay_sql = mysql_query("SELECT * FROM `multiforums_cats` WHERE 1 ORDER BY `name` ASC;");
						
						if ($cat_diplay_result = mysql_fetch_array($cat_diplay_sql))
						{
							echo "<select name='cat'>\n";
							do 
							{
								echo "<option value='$cat_diplay_result[id]'>$cat_diplay_result[name]</option>\n";	
							} while ($cat_diplay_result = mysql_fetch_array($cat_diplay_sql));
							echo "</select>\n";
						}
						?>
						
						</td>
					</tr>
					<tr>
						<th colspan="2">Admin Configuration</th>
					</tr>
					<tr>
					  <td class="row1" align="right"><span class="gen"><B>Username</B>:</span></td>
					  <td class="row2"><input name="adminname" type="text" id="adminname" value="" /></td>
				  </tr>
					<tr>
						<td class="row1" align="right"><span class="gen"><B>Email Address:<BR>
						</B>Your password will be sent via Email</span></td>
						<td valign="middle" class="row2"><input name="adminemail" type="text" id="adminemail" value="" /></td>
					</tr>
					<tr> 
					  <td class="catBottom" align="center" colspan="2"><input onClick="JavaScript: Submit.disabled=true; Submit.value='Please wait...'; submitForm(); return true" type="submit" name="Submit" value="Make Forum"></td>
					</tr>		
				</table>
				<table width="100%" border="0" cellpadding="0" cellspacing="0">
			<tr>
				<td colspan="2"><table width="90%" border="0" align="center" cellspacing="0" cellpadding="0">
					<tr>
						<td><br>
						
						<?php 
							if ($multiforums_setting[copyright] == "yes") {
								echo "<div align=center><font size=1 face='Arial, Helvetica, sans-serif'>Powered by <a href=sebflipper.com target=_blank>Multi-Forums</a> $multiforums_setting[version]</div>";
							}
							else
							{
								echo "<!--Powered by Multi-Forums $multiforums_setting[version] - sebflipper.com-->";
							}
						?>
						
						</td>
					</tr>
				</table></td>
			</tr>
		</table>
				</td>
			</tr>
		</table></td>
	</tr>
</table>
</form>	

</body>
</html>
