<?php
//////////////////////////////////////////////////////////////////////
//     Multi Forums Pro Host v1.3 - sebflipper Copyright 2003       //
//                   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__)."/conf_global/multiforums.config.inc.php")) { 
	// If is does then load it into the script
	require dirname(__FILE__)."/conf_global/multiforums.config.inc.php";
}
else
{
	header("Location: conf_global");
	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);
		
		// 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;
		}

		////////////////////////////		
		// 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
		if (eregi("@", $adminemail)) {
		}
		else
		{
			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 = "conf_global/".$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
		//define the path as relative
		$path = dirname(__FILE__)."/conf_global/";
		//using the opendir function
		$dir_handle = @opendir($path) or die("Unable to open $path");
		//running the while loop
		while ($file = readdir($dir_handle)) {
			if($file != '..' && $file !='.' && $file !=''){ 
				if (eregi("-bak", $file) OR eregi("index", $file) OR eregi("config.inc", $file)) {
				}
				else
				{
					// start
						
					$forums_count++;
					// open file
					include dirname(__FILE__)."/conf_global/$file";
					if ($adminemail == $INFO[adminemail_in]) {
						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;											
					}
					
					// end
				}
			}
		}
		//closing the directory
		closedir($dir_handle);
		
		////////////////////////////
		// check for cookie and stop spam accounts
		if ($FreeForumsMakeCookie == true) {
			echo "<html><body><script language=javascript1.1>alert('Sorry you can only make one forum per session, please try again later'); 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();	
			
			$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("ibf_", "$prefix", $data_buffer);
					$data_buffer = str_replace("default_admin_name", "$adminname", $data_buffer);
					$data_buffer = str_replace("default_md5_password_search_replace", "$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);										
				
					// 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);
					}
	
	
					$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__)."/conf_global_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("via IBForums", "via IBForums: $mf_url/?mforum=$board_access_name", $contents);
			$contents = str_replace("default_admin_email", "$adminemail", $contents);	
			$contents = str_replace("Invision Power Board", "$board_name", $contents);
			$contents = str_replace("IBForums", "$board_name", $contents);
			$contents = str_replace("default_time_stamp", "$current_time_stamp", $contents);
			$contents = str_replace("default_url", "$mf_url", $contents);
			$contents = str_replace("default_path", "$mf_path", $contents);
			$contents = str_replace("default_sql_host", "$server", $contents);
			$contents = str_replace("default_sql_user", "$db_user", $contents);
			$contents = str_replace("default_sql_pass", "$db_pass", $contents);
			$contents = str_replace("default_sql_database", "$database", $contents);						
			
			$prefix = $board_access_name."_";
			$contents = str_replace("ibf_", "$prefix", $contents);
						
			// save file			
			$filename = dirname(__FILE__)."/conf_global/".$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 upload folder
				include $filename;
				if (! is_dir($INFO['upload_dir']) )
				{
				 mkdir($INFO['upload_dir'], 0777);
				}
				@chmod($INFO['upload_dir'], 0777);
				unset($INFO);
								
			} 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`) VALUES ('', '$sql_board_access_name', '$sql_current_time_stamp', '$sql_board_name', '$sql_cat', '$sql_adminemail', '1', '');";
			$insertsql_result = mysql_query($insertsql);
			
			$to = "$adminemail";
			$subject = "Free Invision Power Board Setup"; 
			$message = "Your free Invision Power Board has been setup for you at:\n\n$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: $mf_url";
			$extra = "From: $email\r\nReply-To: $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 ($email_new == "yes") {
				$to = $email;
				$subject = "Free Invision Power Board Setup ($board_access_name)"; 
				$message = "A free Invision Power Board has been setup at:\n\n$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: $email\r\nReply-To: $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='$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 ($top_10=="yes") {
		if ($ViewCookie==false) {
			$fp=@fopen("http://www.ffhut.co.uk/~sebflipper/script_counters/multiforums.php?url=http://$SERVER_NAME$PHP_SELF", "r");
			setcookie ("ViewCookie", "true",time()+60*60*24*30*12);
		}
	}
	
	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='$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;			
	}
?>

<html>
		          <head><title>Invision Power Board Set Up :: Set Up form </title>
		          <style type='text/css'>
		          	
		          	BODY		          	
		          	{
		          		font-size: 11px;
		          		font-family: Verdana, Arial;
		          		color: #000;
		          		margin: 0px;
		          		padding: 0px;
		          		background-image: url(html/sys-img/fadebg.jpg);
		          		background-repeat: no-repeat;
		          		background-position: right bottom;
		          	}
		          	
		          	TABLE, TR, TD     { font-family:Verdana, Arial;font-size: 11px; color:#000 }
					
					a:link, a:visited, a:active  { color:#000055 }
					a:hover                      { color:#333377;text-decoration:underline }
					
					.centerbox { margin-right:10%;margin-left:10%;text-align:left }
					
					.warnbox {
							   border:1px solid #F00;
							   background: #FFE0E0;
							   padding:6px;
							   margin-right:10%;margin-left:10%;text-align:left;
							 }
					
					.tablepad    { background-color:#F5F9FD;padding:6px }

					.pformstrip { background-color: #D1DCEB; color:#3A4F6C;font-weight:bold;padding:7px;margin-top:1px;text-align:left }
					.pformleftw { background-color: #F5F9FD; padding:6px; margin-top:1px;width:40%; border-top:1px solid #C2CFDF; border-right:1px solid #C2CFDF; }
					.pformright { background-color: #F5F9FD; padding:6px; margin-top:1px;border-top:1px solid #C2CFDF; }

					.tableborder { border:1px solid #345487;background-color:#FFF; padding:0px; margin:0px; width:100% }

					.maintitle { text-align:left;vertical-align:middle;font-weight:bold; color:#FFF; letter-spacing:1px; padding:8px 0px 8px 5px; background-image: url(html/sys-img/tile_back.gif) }
					.maintitle a:link, .maintitle  a:visited, .maintitle  a:active { text-decoration: none; color: #FFF }
					.maintitle a:hover { text-decoration: underline }
					
					#copy { font-size:10px }
										
					#button   { background-color: #4C77B6; color: #FFFFFF; font-family:Verdana, Arial; font-size:11px }
					
					#textinput { background-color: #EEEEEE; color:#000000; font-family:Verdana, Arial; font-size:10px; width:100% }
					
					#dropdown { background-color: #EEEEEE; color:#000000; font-family:Verdana, Arial; font-size:10px }
					
					#multitext { background-color: #EEEEEE; color:#000000; font-family:Courier, Verdana, Arial; font-size:10px }
					
					#logostrip {
								 padding: 0px;
								 margin: 0px;
								 background: #7AA3D0;
							   }
							   
					.fade					
					{
						background-image: url(html/sys-img/fade.jpg);
						background-repeat: repeat-x;
					}					
				  </style>
				  </head>
				 <body marginheight='0' marginwidth='0' leftmargin='0' topmargin='0' bgcolor='#FFFFFF'>
				 			 
				 <div id='logostrip'><img src='html/sys-img/title.gif' border='0' alt='Invision Power Board Installer' /></div>
				 <div class='fade'>&nbsp;</div>
				 <br />
				 
	<script language="JavaScript">
	<!--
	function submitForm()
	{
				document.makeforum.submit();
	}
	//-->
	</script>

	
	<form name="makeforum" action='new_forum.php?act=make' method='POST'>
	<div class='centerbox'>
	
	<div class='tableborder'>
	  <div class='maintitle'>Your Board Details</div>
      <div class='pformstrip'>This section requires you to enter details for your 
        board.</div>
	<table width='100%' cellspacing='1'>
	<tr>
	      <td class='pformleftw'><p><b>Access name</b><br>
              This is the access name of your board (no spaces)<font size="1"> 
              </font></p>
            </td>
	  <td class='pformright'><input type='text' id='textinput' name='board_access_name'></td>
	</tr>
	<tr>
	      <td class='pformleftw'><b>The forum name</b><br>
            This is the name of your forum</td>
	  <td class='pformright'><input type='text' id='textinput' name='board_name'></td>
	</tr>
	<tr>
	      <td class='pformleftw'><b>Forum Category</b><br>
            Select a category for your forum</td>
	  <td class='pformright'>
	  <?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>	
	</table>
	</div>
	<div class='fade'>&nbsp;</div>
	
	<br />
	
	<div class='tableborder'>
	<div class='maintitle'>Your Admin Account</div>
	<div class='pformstrip'>This section requires information to create your administration account. Please enter the data carefully!</div>
	  <table width='100%' cellspacing='1'>
        <tr> 
          <td class='pformleftw'><b>Username</b></td>
          <td class='pformright'><input type='text' id='textinput' name='adminname' value=''></td>
        </tr>
        <tr> 
          <td class='pformleftw'><b>Email Address<br>
            </b>Your password will be sent via Email</td>
          <td class='pformright'><input type='text' id='textinput' name='adminemail' value=''></td>
        </tr>
      </table>
	<div align='center' class='pformstrip'  style='text-align:center'>
        <input onClick="JavaScript: Submit.disabled=true; Submit.value='Please wait...'; submitForm(); return true" type="submit" name="Submit" value="Make Forum">
      </div>
	</div>
	<div class='fade'>&nbsp;</div>
	</div>
	</form>   
				 
				 <br><br><br><center><span id='copy'><a href='http://www.invisionboard.com' target="_blank">Invision Power Board</a> &copy; 2003 <a href='http://www.invisionpower.com' target="_blank">Invision Power Services, Inc.</a><br>
  <?php
  	if ($copyright == "yes") {
		echo "<font size=1 face='Arial, Helvetica, sans-serif'>Powered by <a href=http://www.sebflipper.com target=_blank>Multi-Forums</a> $version (import code borrowed from <a href=http://www.ipbsupport.com/index.php?p=downloads&fileid=9 target=_blank>MySQL Tool</a>)";
	}
	else
	{
		echo "<!--Powered by Multi-Forums $version - http://www.sebflipper.com-->";
	}
	
	echo "</span></body></html>";
}
?>
