<?php
	define('WikyBlog_Installing',true);
	//set_error_handler('installErrors');
	//$wbInstallErrorBuffer = array();
	
	
	//	ConfigData
	//
	$configData = array();
	
	
	//__FILE__ does not always contain the absolute path!
	//  would $_SERVER['PATH_TRANSLATED'] be better? .. after virtual-to-real mapping! .. no longer set in Apache 2 SAPI
	//		or $_SERVER['SCRIPT_FILENAME']  .. could contain a relative path!
	//
	//replace \ with / because windows will give both sometimes
	
	if( empty($_POST['configData'])){
		//check the files
		$temp = str_replace('\\','/',dirname(dirname(__FILE__)));
		$wikiFile = $temp.'/wiki.php';
		if( !is_file($wikiFile) ){
			$temp = str_replace('\\','/',dirname(dirname($_SERVER['PATH_TRANSLATED']))); //try with PATH_TRANSLATED IF __FILE__ doesn't work
		}
		
		
		$rootDir = $configData['rootDir'] = $temp;
		$includeDir = $configData['includeDir'] = str_replace('\\','/',$configData['rootDir'].'/include');
		$configData['wbDirPrefix'] = dirname(dirname($_SERVER['REQUEST_URI']));//Thanks to Chris Weiss @ sourceforge
		$configData['wbDirPrefix'] = str_replace('\\','/',$configData['wbDirPrefix']);
		if( $configData['wbDirPrefix'] == '/' ){
			$configData['wbDirPrefix'] = '';
		}
	}
	
	if( isset($_POST['configData']) ){
		$temp = unHtmlspecialchars($_POST['configData']);
		
		//must do this here!
		if( get_magic_quotes_gpc() ){
			$temp = stripslashes($temp);
		}
		$configData = unserialize($temp);
	}
		
	//not saved in wiki.php yet
	$rootDir =& $configData['rootDir'];
	$includeDir =& 	$configData['includeDir'];
	$hostname =& $configData['hostname'];
	$dbname =& $configData['dbname'];
	$dbpword =& $configData['dbpword'];
	$dbuname =& $configData['dbuname'];
	$wbTablePrefix =& $configData['wbTablePrefix'];
	$wbDirPrefix =& $configData['wbDirPrefix'];
	$wbAdminUser =& $configData['wbAdminUser'];
	$wbDefaultTitle =& $configData['wbDefaultTitle'];
	$wbWritable =& $configData['wbWritable'];


	$autoStart = false;
	require_once('../wiki.php');  //have to do this to check for the new version of the wiki.php file
	require_once('wiki2.php');
	
	error_reporting(E_ALL);//development
	@ini_set( "display_errors", true ); //overwrite
	restore_error_handler();


	global $installFunctions,$desc,$wbInstallSafeMode;
	$installFunctions = array();
	$desc = array();
	$installAction = '';
	
	$wbInstallSafeMode = ini_get('safe_mode');
	// $wbInstallSafeMode = true; //for testing
	
	//1
	$installFunctions[] = 'checkEnvironment';
	$desc[] = 'Environment Check';
	$skip[] = false;
	
	//hmm
	$installFunctions[] = 'fileWrite';
	$desc[] = 'Access > Files';
	$skip[] = true;
	
	//2
	$installFunctions[] = 'serverAccess';
	//$desc[] = 'File and Database Access';
	//$desc[] = 'Passwords';
	//$desc[] = 'Database > Connect';
	$desc[] = 'Access > SQL Server';
	$skip[] = false;
	
	
	//3
	$installFunctions[] = 'selectDatabase';
	$desc[] = 'Database > Select Database';
	$skip[] = false;
	
	//4
	$installFunctions[] = 'createTables';
	$desc[] = 'Database > Create Tables';
	$skip[] = false;
	
	//5
	$installFunctions[] = 'copyTemporary1';
	$desc[] = 'Save Data > Files';
	$skip[] = false;
	
	//6
	$installFunctions[] = 'setDefaultConfig';
	$desc[] = 'Save Data > Package Configuration';
	$skip[] = false;
	
	//7
	$installFunctions[] = 'registerAdminUser';
	$desc[] = 'Save Data > Defaults';
	$skip[] = false;
	
	//8
	$installFunctions[] = 'createWikiFile';
	$desc[] = 'Finalize Installation';
	$skip[] = false;
	
	
	$templateTitle = 'WikyBlog Installation';
	
	ob_start();
	if ( defined('WikyBlog_Installed') ){
		displaySteps(0);
		finishedNotice();
	}else{
		runInstall();
	}
	
	echo '<input type="hidden" name="configData" value="'.wbHtmlspecialchars(serialize($configData), ENT_QUOTES).'" />';
	$pageContent = wb::get_clean();
	
	
// 	if( count($wbInstallErrorBuffer) > 0 ){
// 		$errors = implode("\n\n---------\n\n",$wbInstallErrorBuffer);
// 		$link = 'mailto:installerrors@wikyblog.com';
// 		$message = 'Oops, an error occurred while executing the installation script. We\'d appreciate it if you <a style="display:inline !important" href="'.$link.'">sent us a copy of the error report</a> so we can fix the problem. <em>Note:</em> We will never sell/share/abuse your email address. ';
// 		$message .= '<br/><textarea style="width:100%">'.htmlspecialchars($errors).'</textarea>';
// 		message($message);
// 	}

	require_once('installTemplate.php');

	
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//		runInstall
	//		
	///
	
	function runInstall(){
		global $installFunctions, $desc, $pageContent, $pageTitle,$skip;
		global $installAction;
		$howMany = count($installFunctions);
		
		$_POST += array( 'new_step' => 0, 'cmd' => '' );
		$step = $_POST['new_step'];
		$action = $_POST['cmd'];
		
		$currFunc = $installFunctions[$step];
		$pageTitle= 'Step '.($step+1);
		$bool = call_user_func($currFunc,$action);
		
	
		// if the function returns true, show the <input> for the next function
		//	or show finished if function doesn't exist
		if( $bool === true ){
			echo '<p> - Step '.($step+1).' done.</p>';
			echo ' <p> </p>';
			
			if( isset($installFunctions[(int)($step+1)]) ){
				if( (int)$step === ($howMany-2) ){
					echo '<input type="hidden" name="new_step" value="'.($step+1).'" />';
					$installAction = '<input type="submit" class="submit"  name="cmd" value="Finalize" /> ';
				}else{
					echo '<input type="hidden" name="new_step" value="'.($step+1).'" />';
					$installAction = '<input type="submit" class="submit"  name="cmd" value="Step '.($step+2).'" /> ';
				}
			}else{
				echo finishedNotice();
			}
			
		}else{
			echo '<p> </p> ';
			echo '<input type="hidden" name="new_step" value="'.($step).'" />';
			$installAction = '<input type="submit" class="submit"  name="cmd" value="Continue" /> ';
			
			if( $skip[$step] ){
				$installAction .= ' <input type="submit" class="submit"  name="cmd" value="Skip" /> ';
			}
		}
		
		displaySteps($step);
		
	}
	
	//
	//Steps
	//
	
	function displaySteps($step){
		global $pageSteps,$desc,$installAction;
		ob_start();
		echo '<table class="steps">';
		echo '<tr class="stepHead"><th>Installation Step By Step</th></tr>';
		$class = ' class="stepDone"';
		
		foreach($desc as $i => $text){
			if( ($i == $step) && !defined('WikyBlog_Installed') ){
				echo '<tr class="stepAt"><td class="stepNum"><b>Step '.($i+1).' &gt; ';
				echo $text.'</b></td></tr>';
				$class = ' class="stepToDo"';
			}else{
				echo '<tr'.$class.'><td class="stepNum">Step '.($i+1).' &gt; ';
				echo $text.'</td></tr>';
			}
			$i++;
		}
		
		if( !empty($installAction) ){
			echo '<tr class="stepFoot">';
			echo '<td>';
			echo $installAction;
			echo '</td>';
			echo '</tr>';
		}
		
		echo '<tr class="stepFoot"><td>';
		echo 'See /_install.txt for more information about installation';
		echo '</td></tr>';
		echo '</table>';
		$pageSteps = wb::get_clean();
	}
	
	
	//
	//try to use ftp to make things writable.. ftp is not always available..
	//
	function fileWrite($action){
		global $configData,$rootDir,$wbInstallSafeMode;
		
		$wikiFile = $configData['rootDir'].'/wiki.php';
		$_POST += array('ftp_server'=> '', 'ftp_username'=>'', 'ftp_password'=>'');
		
		//try to get the ftp_server
		if( empty($_POST['ftp_server']) && function_exists('ftp_connect') && !empty($_SERVER['HTTP_HOST']) ){
			$conn_id = @ftp_connect($_SERVER['HTTP_HOST'],21,6);
			if( $conn_id ){
				$_POST['ftp_server'] = $_SERVER['HTTP_HOST'];
				@ftp_quit($conn_id);
			}
		}
			
			
		
		if($action == 'Skip'){
			wbInstall::showFileStatus();
			echo '<p>Skipping this step. Some of WikyBlog\'s features will be unavailable.</p>';
			$configData['wbWritable'] = false;
			return true;
		}

			
			
		///// Check directories
		if( strpos($_SERVER["SERVER_SOFTWARE"],"IIS") !== FALSE) {
		
			if( is_writable($configData['rootDir'].'templates') && is_writable($configData['rootDir'].'userfiles')){
				//echo '<p>The templates and userfiles directories are writable.</p>';
				//return true;
			}else{

				$mess = '<b>IIS Installation:</b> <p>Since you are running IIS, in order to enable templates and file ';
				$mess .= 'uploads you may need to manually create the <b>templates</b> and <b>userfiles</b> folders.</p>';
				$mess .= '<p>The user account which the server process runs under will need write access to these folders.</p>';
				$mess .= '<p>If this server is using share level access control you will not have access to the security ';
				$mess .= 'settings tab of the folder properties. The following commands can be run from the command line: </p>';
				$mess .= 'cd '.$configData['rootDir'].'<br/>';
				$mess .= 'mkdir templates <br/>';
				$mess .= 'mkdir userfiles <br/>';
				$mess .= 'cacls templates /E /G IUSR_<i>server_name</i>:F <br/>';
				$mess .= 'cacls userfiles /E /G IUSR_<i>server_name</i>:F <br/>';
				$mess .= 'cacls templates /E /G IWAM_<i>server_name</i>:F <br/>';
				$mess .= 'cacls userfiles /E /G IWAM_<i>server_name</i>:F <br/></p>';
				message($mess);
			}
		}
		
		
		//Files are writable! let's move on
		if( is_writable($configData['rootDir']) && is_writable($wikiFile) ){
			wbInstall::showFileStatus();
			echo '<p>The installation directory and /wiki.php file are writable.</p>';
			return true;
		}
		
		
		
		//php 4.2+ with FTP enabled
		if( !function_exists('ftp_set_option') ){
			wbInstall::showFileStatus();
			
			if( $wbInstallSafeMode ){
				echo '<p>Since PHP is running in SAFE MODE and FTP functions are unavailable, there are certain features that will be unavailable to this installation.';
				echo 'These include file uploading and custom user templates.';
				$configData['wbWritable'] = false;
				return true;
			}
			
			echo '<p>To enable certain features, WikyBlog needs to be able to write to your server.</p>';
			echo '<p>You may manually make the files writable by changing their modes or you may skip this step to continue with the installation.</p>';
			
			echo '<blockquote>';
			echo '<h3>Manual Steps</h3>';
			echo '<p>You\'ll need to change the modes of the installation directory and the /wiki.php file.</p>';
			
			echo '<p>If you have FTP access, this can be done by changing the mode to 777 for the installation directory and 666 for /wiki.php.</p>';
			
			//chmod a+w file
			echo '<p>Otherwise, if you are using Unix/Linux, you can use the function <em>chmod.</em>';
			
			echo '<p>For security purposes, you should restore the modes once installation has completed.</p>';
			echo '</blockquote>';
			
			return false;
		}
		
		
		//
		//	Connect to FTP and get ftp_root
		//		ftp_root is the root file directory as identified via ftp
		//			ex: $ftp_root = "/public_html" where $rootDir = "/home/root/public_html"
		//
		if( $action == 'Continue'){
			
			$ftpResult = wbInstall::writableWithFTP();
			if( $ftpResult != false ){
				wbInstall::showFileStatus();
				echo $ftpResult;
				return true;
			}
		}
		
		
		wbInstall::showFileStatus();

		?>
		<script>
		function show(showId,hideId){
			var a = window.document.getElementById(showId);
			a.style.display="block";
			
			var b = window.document.getElementById(hideId);
			b.style.display="none";
		}
		
		</script>
		
	
		
		<p>To continue, the installer needs to be able to write to the installation directory and the /wiki.php file. </p>

				
		<div id="manually" style="display:none">
		<p>You may do this with <a href="javascript:show('withftp','manually');">FTP</a> or <a>manually</a>.</p>
		
		<h3>Continue Manually</h3>
		<p>If you have FTP access, this can be done by changing the mode to 777 for the installation directory and 666 for /wiki.php.</p>
			
		<p>Otherwise, if you are using Unix/Linux, you can use the function <em>chmod</em>.</p>
		<p> Once you have changed the modes, click "Continue" below.</p>
		
		
		<h3><a href="javascript:show('withftp','manually');">Continue With FTP...</a></h3>
		</div>
		
		<div id="withftp">
		
		<p>You may do this with <a>FTP</a> or <a href="javascript:show('manually','withftp');">manually</a>.</p>
		
		<h3>Continue With FTP</h3>
		<table>
		<tr>
			<td align="left"><b>FTP Server:</b></td><td>
			<input style="width:10em" type="text" size="20" name="ftp_server" value="<?php echo $_POST['ftp_server'] ?>">
			</td><td class="about"></td>
			</tr>
			
		<tr>
			<td align="left"><b>FTP Username:</b></td><td>
			<input style="width:10em" type="text" size="20" name="ftp_username" value="<?php echo $_POST['ftp_username'] ?>">
			</td><td class="about"></td>
			</tr>
			
		<tr>
			<td align="left"><b>FTP Password:</b></td><td>
			<input style="width:10em" type="password" size="20" name="ftp_password" value="">
			</td><td class="about"></td>
			</tr>
			
		<tr>
			<td align="left"></td><td>
			<input style="width:10em" type="submit" size="20" name="cmd" value="Continue">
			</td><td class="about"></td>
			</tr>
			
		</table>
		
		<br/>
		
		<h3><a href="javascript:show('manually','withftp');">Continue Manually...</a></h3>
		</div>
		

		<?php
		return false;

	}

	
	
	
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//		serverAccess
	//			I would like to do this, because 
	///
	function serverAccess($action){
		$done = false;
		//database select
		// $hostname = "localhost";
		// $dbuname = "root";
		// $dbpword = "";
		//mysql_connect($hostname,$dbuname,$dbpword);
		
		// $dbname = "wikyblog3";

		$_POST += array('hostname'=>'localhost','dbuname'=>'','dbpword'=>'','dbname'=>'');
		
		if($action == 'Continue'){
			$done = true;
			if( empty($_POST['hostname']) ){
				$done = false;
				message('Missing hostname');
			}
			if( empty($_POST['dbuname']) ){
				$done = false;
				message('Missing username');
			}
			if( empty($_POST['dbpword']) ){
				//$done = false;
				$mess = 'Missing password';
				if( $done ){
					$mess .= '... <br/> &nbsp; ... we will still attempt to connect to the database...';
				}
				message($mess);
			}
			
		}
		
		if( $done ){
			$done = @mysql_connect($_POST['hostname'],$_POST['dbuname'],$_POST['dbpword']);
			if(!$done){
				message('Could not connect to the database using the suppliled values');
			}else{
				global $configData;
				$configData['hostname'] = $_POST['hostname'];
				$configData['dbuname'] = $_POST['dbuname'];
				$configData['dbpword'] = $_POST['dbpword'];
				message('Connection made using the supplied values');
				
				$query = 'SHOW VARIABLES LIKE "VERSION";';
				$result = wbDB::runQuery($query);
				$row = mysql_fetch_assoc($result);
				
				if( !array_key_exists('Value',$row) || version_compare('4.0',$row['Value'],'>') ){
					message('Please make sure you have MySQL version 4.0 or greater before continuing.');
				}
				
				return true;
			}
		}
		
		?>
		These values will be used to connect to MySQL
		<table>
		
		<tr>
			<td class="left"><b>Database Server Hostname:</b></td><td>
			<input style="width:10em" type="text" size="20" name="hostname" value="<?php echo $_POST['hostname'] ?>">
			</td>
			</tr>
		
		<tr>
			<td class="left"><b>Database Username:</b></td><td>
			<input style="width:10em" type="text" size="20" name="dbuname" value="<?php echo $_POST['dbuname'] ?>">
			</td>
			</tr>
		
		<tr>
			<td class="left"><b>Database Password:</b></td><td>
			<input style="width:10em" type="password" size="20" name="dbpword" value="">
			</td>
			</tr>
			
		<tr>
			<td class="left"></td><td>
			<input style="width:10em" type="submit" size="20" name="cmd" value="Continue">
			</td>
			</tr>
						

		
		</table>
		
		<?php
		return false;
	}
	
	function selectDatabase($action){
		global $configData;
		$_POST += array('wbTablePrefix'=>'wb_','dbname'=>'');
		
		if( $action !== 'Continue' && !empty($configData['wbDirPrefix']) ){
			//
			$_POST['wbTablePrefix'] = $configData['wbDirPrefix'];
			if( $_POST['wbTablePrefix']{0} == '/' ){
				$_POST['wbTablePrefix'] = substr($_POST['wbTablePrefix'],1);
			}
			
			$_POST['wbTablePrefix'] = wbStr_replace('.','_',$_POST['wbTablePrefix']);
			$_POST['wbTablePrefix'] = wbStr_replace('/','_',$_POST['wbTablePrefix']).'_';
			$_POST['wbTablePrefix'] = wbStrtolower($_POST['wbTablePrefix']);
		}
		
		
		if(empty($_POST['dbname'])){
			$connection = mysql_connect($configData['hostname'],$configData['dbuname'],$configData['dbpword']);
			
			$query = 'SHOW DATABASES';
			$result = @mysql_query( $query );
			if( $result ){
				$possible = array();
				while($row = mysql_fetch_assoc($result)){
					$possible[$row['Database']] = $row['Database'];
				}
				asort($possible);
			}
			echo '<table>';
			echo '<tr><td><b>Database Name:</b></td><td>';
			if( isset($possible) ){
				echo formSelect('dbname',$possible,$_POST['dbname']);
				echo '</td><td class="about">Select from an existing database.</td>';
			}else{
				echo '<input type="text" name="dbname" value="'.$_POST['dbname'].'" />';
				echo '</td><td class="about">Type the name of an existing database.</td>';
			}
			echo '</tr>';
			
			echo '<tr><td><b>Table Prefix:</b></td><td>';
			echo '<input type="text" name="wbTablePrefix" value="'.$_POST['wbTablePrefix'].'" />';
			echo '</td><td class="about">This can be useful if the selected database is used for other database applications. It can be left blank.</td>';
			echo '</tr>';
			
			echo '<tr><td></td><td>';
			echo '<input type="submit" name="cmd" value="Continue" />';
			echo '</td>';
			echo '</tr>';
			
			echo '</table>';
			return false;
		}
				
		
		$configData['dbname'] = $_POST['dbname'];
		$configData['wbTablePrefix'] = wbStrtolower($_POST['wbTablePrefix']);
		return true;
	}
	
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//		checkEnvironment
	//			checkEnvironment and set some initial $configData values
	//
	
	function checkEnvironment(){
		global $configData,$pageTitle, $wbInstallSafeMode;
		
		//Some of the following is from mediawiki's
		$pageTitle = 'Checking Environment';
		
		$fatal = false;
		echo '<ul>';
		if( !function_exists('version_compare') || (version_compare(phpversion(),"4.1") < 0)){
			$fatal = true;
			
			?><li><strong style="color:red">Fatal: Minimum of PHP 4.1 Needed .</strong>
			<?php
		}else{
			?><li>PHP version >= 4.1.0</li><?php
		}
		
		if( $wbInstallSafeMode ){
			
			if( ini_get('safe_mode_gid') ){
				//only available since PHP4.1
				echo '<li><strong>Warning:</strong> It appears PHP is running in SAFE MODE with GID checking enabled. Some features may not be available.';
				echo '</li>';
			}else{
				echo '<li><strong>Warning:</strong> It appears PHP is running in SAFE MODE with UID checking enabled. Some features may not be available.';
				echo '</li>';
			}
		}
		
		/// IIS check
		if( strpos($_SERVER["SERVER_SOFTWARE"],'IIS') !== FALSE) {
				echo '<li>Running under IIS: You will need administrator access to complete the installation';
				echo '</li>';
		}		
		
		if( !function_exists('mysql_query') ){
			$fatal = true;
			?><li><strong style="color:red">Fatal: MySQL support is required.</strong>
			<?php
		}else{
			?><li>MySQL Support found</li><?php
		}
		
		//check the files
		$wikiFile = $configData['rootDir'].'/wiki.php';
		if( !is_file($wikiFile) ){
			$fatal = true;
			
			?><li><strong style="color:red">Fatal: Could not find /wiki.php.</strong>
			<p>WikyBlog could not find the /wiki.php file.</p>
			</li>
			<?php
		}
		
		if( ini_get( "magic_quotes_runtime" ) ) {
			$fatal = true;
			?><li><strong style="color:red">Fatal: <a href='http://www.php.net/manual/en/ref.info.php#ini.magic-quotes-runtime'>magic_quotes_runtime</a> is active!</strong>
			<p>This option corrupts data input unpredictably; you cannot install or use
			WikyBlog unless this option is disabled.</p>
			</li>
			<?php
			return;
		}else{
			?><li>Magic Quotes Runtime is off.</li><?php
		}
		
		if( ini_get( "magic_quotes_sybase" ) ) {
			$fatal = true;
			?><li><strong style="color:red">Fatal: <a href='http://www.php.net/manual/en/ref.sybase.php#ini.magic-quotes-sybase'>magic_quotes_sybase</a> is active!</strong>
			<p>This option corrupts data input unpredictably; you cannot install or use
			WikyBlog unless this option is disabled.</p>
			</li>
			<?php
		}else{
			?><li>Magic Quotes Sybase is off.</li><?php
		}
		
		if( !function_exists('xml_parser_create') ){
			$fatal = true;
			?><li><strong style="color:red">Fatal:<a href="http://www.php.net/manual/en/ref.xml.php">XML Parser Functions were not found</a>.</strong>
			<p>"These functions are enabled by default" according to the php documentation and are required 
			for WikyBlog to function properly.</p>
			</li>
			<?php
		}else{
			?><li>XML support found.</li><?php
		}
		
		
		if( ini_get("register_globals") ){
			?>
			<li><b>Warning:</b> <strong>PHP's <tt><a href="http://php.net/register_globals">register_globals</a></tt> option is enabled.</strong>
			<p> WikyBlog will work correctly, but this setting
			increases your exposure to potential security vulnerabilities in PHP-based
			software running on your server. <strong>You should disable it if you are able.</strong></p>
			</li>
			<?php
		}else{
			?><li>Register Globals is off.</li><?php
		}
		
		if( !function_exists('mb_convert_case') ){
			?><li><strong>Warning: <a href='http://www.php.net/manual/en/ref.mbstring.php'>Multibyte strings</a> are not supported.</strong>
			<p>For multibyte character support, a minimum of PHP version 4.3 with the mbstring PHP extension is needed.</p>
			<p>Without the mbstring extension WikyBlog is unable to split multibyte character set strings correctly.
			If user input will include mulitbyte characters (like ç ö ü ý þ), you may see unexpected results.</p>
			</li>
			<?php
		}else{
			?><li>Multibyte String Support.</li><?php
			
			if(@extension_loaded('mbstring') && @ini_get('mbstring.func_overload') == 1){
				?><li><strong>Warning: <a href='http://www.php.net/manual/en/ref.mbstring.php'>mbstring.func_overload</a> is activated.</strong>
				<p>mbstring.func_overload is enabled in your PHP configuration. 
				This option may result in the corruption of user data
				<?php
			}else{
				?><li>Multibyte String Overload is off.</li><?php
			}
			
		}
		
			
		
		$configData['wbUniq'] = uniqid('');
		
		if(  str_replace('\\','/',dirname(__FILE__)) !== $configData['includeDir']){
			$fatal = true;
			?><li><strong style="color:red">Fatal: Incorrect File Paths</strong>
			<p>Software folders must not be rearranged/renamed when they are uploaded to your server<p>
			</li>
			<?php
		}
		
		
		if( $configData['wbDirPrefix'] !== '' ){
			?>
			<li><b>Installation in SubDirectory: <?php echo $configData['wbDirPrefix'] ?></b>
			<p>
			It appears this software is not being installed on the server document root.
			Links will automatically be prepended with this value to make them valid.
			</p>
			</li>
			<?php
		}
		
// 		includeFile('admin/checkInstallation.php',false);
// 		$temp = new checkInstallation();
// 		echo '<li>'.$temp->message.'</li>';
		
		
		
		if( $fatal ) {
			echo '</ul>';
			return false;
		}
		echo '<li>Environment ok... </li>';
		echo '</ul>';

		return true;
	}
	

	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//		createWikiFile
	//
	function createWikiFile($action){
		global $configData,$packageVersion;
		
		
		//set the special links
		wbDB::connect();
		includeFile('admin/ConfigLinks.php',false);
		ConfigLinks::setDefaults();
		
		
		$wroteWikiFile = false;
		
		$text[] = '<'.'?'.'php';
		$text[] = "//";
		$text[] = "//\tWikyBlog Generated File";
		$text[] = "//\t***********************************";
		$text[] = "//\tDon't change anything in this file!";
		$text[] = "//\tThis file was created ";
		$text[] = "//\t\t on ".date("l, F j, Y");
		$text[] = "//\t\t by WikyBlog Package ".$packageVersion;
		$text[] = "//";
		$text[] = '';
		$text[] = '';
		$text[] = '//define(\'wbDebug\',true); //Uncomment to debug .. should not be used with a public installation';
		$text[] = '//define(\'wbCache\',false); //Uncomment to disable browser caching';
		$text[] = 'define(\'WikyBlog_Installed\', true);';
		$text[] = '';
		$text[] = '';
		$text[] = '//$wbCookieDomain = \'\'; //can set to .yoursite.com or subdir.yoursite.com';
		$text[] = '//$wbDisableFeatures = true; //disable features available in the admin account that allow database modifications';
		$text[] = '//$wbNofollowUnchecked = true; //files edited by untrusted users are flagged and unchecked, links in such files will be given the nofollow attribute when true';
		$text[] = '';
		$text[] = '';
		$text[] = '$wbUniq = \''. addcslashes($configData['wbUniq'],"\'") .'\';';
		$text[] = '$wbAdminUser = \''. addcslashes($configData['wbAdminUser'],"\'") .'\';';
		$text[] = '';
		$text[] = '';
		$text[] = '$hostname = \''. addcslashes($configData['hostname'],"\'") .'\';';
		$text[] = '$dbuname = \''. addcslashes($configData['dbuname'],"\'") .'\';';
		$text[] = '$dbpword = \''. addcslashes($configData['dbpword'],"\'") .'\';';
		$text[] = '$dbname = \''. addcslashes($configData['dbname'],"\'") .'\';';
		$text[] = '';
		$text[] = '';
		$text[] = '$wbTablePrefix = \''. addcslashes($configData['wbTablePrefix'],"\'") .'\';';
		$text[] = '$wbDefaultTitle = \''. addcslashes(toStorage($configData['wbDefaultTitle']),"\'") .'\';';
		$text[] = '';
		$text[] = '';
		$text[] = '$rootDir = \''. addcslashes($configData['rootDir'],"\'") .'\';';
		$text[] = '$includeDir = \''. addcslashes($configData['includeDir'],"\'") .'\';';
		$text[] = '$wbDirPrefix = \''. addcslashes($configData['wbDirPrefix'],"\'") .'\';';
		$text[] = '';
		
		if( isset($configData['wbWritable']) && $configData['wbWritable'] === false){
			$text[] = '';
			$text[] = '$wbWritable = false;';
			$text[] = '';
		}
		if( isset($configData['ftp_use']) && $configData['ftp_use'] === true){
			$text[] = '';
			$text[] = '$wbFTP = array();';
			$text[] = '$wbFTP[\'use\'] = true;';
			$text[] = '$wbFTP[\'root\'] = \''. addcslashes($configData['ftp_root'],"\'") .'\';';
			$text[] = '$wbFTP[\'server\'] = \''. addcslashes($configData['ftp_server'],"\'") .'\';';
			$text[] = '$wbFTP[\'user\'] = \''. addcslashes($configData['ftp_username'] ,"\'") .'\';';
			$text[] = '$wbFTP[\'pass\'] = \''. addcslashes($configData['ftp_password'],"\'") .'\';';
			$text[] = '';
		}
								
		$text[] = '';
		$text[] = 'if( !isset($autoStart) || $autoStart !== false){';
		$text[] = "\trequire(\$includeDir.'/wiki2.php');";
		$text[] = "\tdoWikiThing();";
		$text[] = '}';
				
		$wikiFileContents = implode("\n",$text);
		//message('<pre>'.wbHtmlspecialchars($wikiFileContents).'</pre>');
		
		$wikiLocation = $configData['rootDir'].'/wiki.php';
		
		////	manual
			if( isset($configData['wbWritable']) && $configData['wbWritable'] === false){
				manualWikiFile($wikiFileContents);
				return true;
			}

		
		////	Write wiki.php
			if( is_writable($configData['rootDir']) ){
				if($fp = @fopen($wikiLocation,'w')){
					if( @fwrite($fp,$wikiFileContents) ){
						$wroteWikiFile = true;
					}
					fclose($fp);
				}
			}
			
		////	FTP
			if( isset($configData['ftp_root'])){
				$conn_id = @ftp_connect($configData['ftp_server'],21,6);
				$login_result = @ftp_login($conn_id, $configData['ftp_username'], $configData['ftp_password']);
				
				//Write wiki.php
				if(!$wroteWikiFile){
					if($fp = tmpfile()){
						if( fwrite($fp,$wikiFileContents) ){
							rewind($fp);
							if( ftp_fput($conn_id,$configData['ftp_root'].'/wiki.php',$fp, FTP_ASCII)){
								$wroteWikiFile = true;
							}
						}
						fclose($fp);
					}
				}
				
				@ftp_site($conn_id, 'CHMOD 0755 '. $configData['ftp_root']);
				@ftp_site($conn_id, 'CHMOD 0644 '. $configData['ftp_root'].'/wiki.php');
				@ftp_quit($conn_id);
			}
			
			
			if( !$wroteWikiFile ){
				manualWikiFile($wikiFileContents);
				return true;
			}
		return true;
	}
	function manualWikiFile($contents){
		global $configData;
		?>
		<p>To finalize installation, you'll need to manually edit your /wiki.php file.</p>
		<ol>
		<li> Open the "<tt>wiki.php</tt>" file in your "<tt><?php echo $configData['rootDir'] ?></tt>" directory.</li>
		<li>Delete the text in "<tt>wiki.php</tt>", then paste in the following text:
		<br/> &nbsp; <textarea rows="15" cols="60" wrap="off"><?php echo wbHtmlspecialchars($contents) ?></textarea></li>
		</ol>
		<?php
	}
	
	
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//		createTables
	//

	function createTables($action){
		global $dbname,$configData;
		require_once('installSQL.php');
		
		
		$connection = mysql_connect($configData['hostname'],$configData['dbuname'],$configData['dbpword']);
		if( !$connection ){
			die('The database configuration data is no longer valid, please try again');
		}
		if(!mysql_select_db($configData['dbname'],$connection)){
			die('The database configuration data is no longer valid, please try again');
		}

		
		ob_start();
		echo '<p></p>This script will run the following queries on the database "' .$configData['dbname'].'".';
		
		
		//	Existing Tables
		$query = 'SHOW TABLES';
		if( !empty($configData['wbTablePrefix']) ){
			$query .= ' LIKE "'.wbDB::like($configData['wbTablePrefix']).'%"';
		}
		//message($query);
		$result = wbDB::runQuery($query);
		while($row = mysql_fetch_assoc($result)){
			$tables[array_pop($row)] = 1;
		}
		
		$newDB = unserialize($dbData);
		//echo showArray($newDB);
		echo '<blockquote style="font-size:smaller">';
		foreach( $newDB as $tableName => $info){
			if( isset($tables[$configData['wbTablePrefix'].$tableName]) ){
				echo '<p><b>Table "'.$configData['wbTablePrefix'].$tableName.'" already exists</b><br/>';
				echo 'Continuing will modify the table and could result in loss of data.</p>';
				
			}else{
				echo '<P>CREATE TABLE `'.$configData['wbTablePrefix'].$tableName.'` ...</P>';
			}
		}
		
		if( $action === 'Continue'){
			$done = true;
		}else{
			$done = false;
		}
		
		if( $action === 'Continue'){
			require_once('installDB.php');
			$alterDb = new dbAlter();
			$alterDb->go($configData['wbTablePrefix']);
			$messages = returnMessages(false);
			message('Queries and Results: '.$messages);
		}
		
		echo '</blockquote>';		
		
		
		if( $done ){
			wb::get_clean();
			return true;
		}
		echo wb::get_clean();
		return false;
	}
	
	
	
	
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//		registerAdminUser
	//
	//		Insert Database Information
	//			- default template

	function registerAdminUser($action){
		global $configData,$wbTables;
		
		
		ob_start();
		
		wbDB::connect();
		wbData::getConfig();
		
		//to set the "g" cookie
		wbLang::getFile('SPEC');
		includeFile('tool/session.php');
	
		
		//check default user
		$query = 'SELECT `username` FROM '.$wbTables['users'].' WHERE `user_id` = 1; ';
		$result = wbDB::runQuery($query);
		$num = mysql_num_rows($result);
		$newUser = false;
		
		if( $num !== 0 ){
			$newUser = true;
			$row = mysql_fetch_assoc($result);
			$configData['wbAdminUser'] = $row['username'];
			
		}elseif( ($num === 0) && ($action==='Continue') ){
			$reservedWords = array();
			
			
			
			includeFile('tool/sessionRegister.php');
			$regObject = new registerUser();
			$newUser = $regObject->register(true);
			
			
			if(!$newUser){
				//echo returnMessages(false);
			}else{
				$_SESSION['adminConfirmed'] = mktime();
				$configData['wbAdminUser'] = $_POST['username'];
				
				//Admin Flag
				$query = 'UPDATE '.$wbTables['users'];
				$query .= ' SET ';
				$query .= ' `flags` = "admin" ';
				$query .= ' , `modified` = `modified` ';
				$query .= ' WHERE `user_id` = 1; ';
				wbDB::runQuery($query);
				
			}
		}
		
		if(!$newUser){
				$_POST += array('email'=>'','username'=>'Main');

				
				if( isset($_SERVER['HTTP_HOST']) ){
					$displayServer = 'http://'.$_SERVER['HTTP_HOST'].$configData['wbDirPrefix'];
				}else{
					$displayServer = 'http://YourServer'.$configData['wbDirPrefix'];
				}
				
				?>
					<p>This will create the default/administrator user account using the following information.</p>
					<ul>
					<li>This user name will be used as the default name space.</li>
					<li>All of the administrative features will be accessible through this user account.</li>
					</ul>
					
					<h3>Account Name</h3>
					<table cellpadding="5" style="margin-left:2em">
					<tr><td>
					<?php
					
						echo $displayServer;
						echo '/<input style="width:10em" type="text" size="20" name="username" value="'. wbHtmlspecialchars($_POST['username']).'" maxlength="20" />';
					?>
					</td></tr></table>
					
					<h3>Account Access</h3>
					
					
					<table cellpadding="5" style="margin-left:2em">
					<tr>
						<td align="left"><b> Password:</b></td><td>
						<input style="width:10em" type="password" size="20" name="password" value="" /><br/>
						</td><td class="about">	Must be between 5 and 8 characters long.
						</td></tr>
					
					<tr>
						<td align="left"><b>
						Confirm Password:</b></td><td>
						<input style="width:10em" type="password" size="20" name="password2" value="" /><br/>
						</td><td class="about">
						Must be the same as above.
						</td></tr>
						
					<tr>
						<td align="left" style="width:8em"><b>
						Email:</b></td><td>
						<input style="width:10em" type="text" size="20" name="email" value="<?php echo wbHtmlspecialchars($_POST['email']) ?>" /><br/>
						</td><td class="about">Optional but useful if you forget your password.</td>
						</tr>
					
					<tr>
						<td align="left" style="width:8em">
						</td><td>
						<input style="width:10em" type="submit" size="20" name="cmd" value="Continue" />
						</td>
						</tr>

					</table>
					
				<?php
		}else{
			wb::get_clean();
			return true;
		}
		echo wb::get_clean();
		return false;
	}
	
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//		setDefaultConfig
	//			insert into the config table
	
	function setDefaultConfig($action){
		global $packageVersion,$wbTables,$configData,$wbTablePrefix;
		
		wbDB::connect();
		$query = 'SELECT `data`, `version` FROM '.$wbTables['config'].' ORDER BY `revision` DESC LIMIT 1';
		//message($query);
		$result = wbDB::runQuery($query);
		$num = mysql_num_rows($result);
		if( $num !== 0 ){
			$row = mysql_fetch_assoc($result);
			if( !empty($row['version']) ){
				message('Configuration exists.');
				return true;
			}
			//
			$query = 'DELETE FROM '.$wbTables['config'].' ';
			$result = wbDB::runQuery($query);
		}
		
		
		//check default title
		if( empty($_POST['wbDefaultTitle']) ){
			$_POST['wbDefaultTitle'] = 'Home';
		}	
			
		$chars = array('<','>','%3e','%3c','&lt;','&gt;','?');
		$passed = true;
		foreach($chars as $char){
			if( wbStrpos($_POST['wbDefaultTitle'],$char) !== false ){
				$passed = false;
			}
		}
		if( $passed ){
			$configData['wbDefaultTitle'] = $_POST['wbDefaultTitle'];
		}else{
			message('The default title contained illegal characters, please try again.');
			$action = ''; // don't continue;
		}
		
		//try saving
		if( $action == 'Continue'){
			
			
			//set configuration array			
			$array = array();
			$array['wbConfig']['version'] = $packageVersion;
			$array['wbConfig']['floodInterval'] = '30';
			$array['wbConfig']['search'] = true;
			$array['wbConfig']['createNew'] = array('page'=>1,);
			if( function_exists('imagecreatetruecolor') ){
				$array['wbConfig']['thumbs'] = 'On';
			}
			
			if( function_exists('tidy_parse_string') ){
				$array['wbConfig']['tidy'] = 'On';
			}
			
			
// 			$array['serverName1'] = 'WikyBlog';
// 			$array['serverName2'] = 'www.wikyblog.com';
// 			$array['serverName3'] = 'http://'.$array['serverName2'];
			$array['userLanguage'] = 'en';
			$array['reservedWords'] = "'webmaster', 'master', 'BillyJoe'";

			
			$iniMax = ini_get('upload_max_filesize');
			$iniMax = getByteValue($iniMax);
			if( empty($iniMax) ){
				$array['max_upload'] = 180000;
			}else{
				$array['max_upload'] = min($iniMax,180000);
			}
			
			$array['maxErrorFileSize'] = '';
			$array['errorEmail'] = '';
			
			$array['dbInfo']['page']['class'] = 'CLASSpage';
			$array['dbInfo']['page']['dbTable'] = "`{$wbTablePrefix}pages`";
			$array['dbInfo']['page']['uniqLink'] = ' CONCAT("/", `'.$wbTablePrefix.'pages`.owner, "/", `'.$wbTablePrefix.'pages`.title) ';
			$array['dbInfo']['page']['dTitle'] = array(' `'.$wbTablePrefix.'pages`.title'=>0);
			$array['dbInfo']['page']['searchTitle'] = array('title');
			$array['dbInfo']['page']['searchContent'] = array('content');
				
			$array['dbInfo']['comment']['class'] = 'CLASScomment';
			$array['dbInfo']['comment']['dbTable'] = "`{$wbTablePrefix}comments`";
			$array['dbInfo']['comment']['uniqLink'] = ' CONCAT("/Comment/", `'.$wbTablePrefix.'comments`.prefix, `'.$wbTablePrefix.'comments`.owner,"/", `'.$wbTablePrefix.'comments`.title,"/", `'.$wbTablePrefix.'comments`.subject) ';
			$array['dbInfo']['comment']['keys'] = array('prefix'=>1,'owner'=>1,'title'=>1,'subject'=>1);
			$array['dbInfo']['comment']['dTitle'] = array('`'.$wbTablePrefix.'comments`.prefix'=>0,'`'.$wbTablePrefix.'comments`.title'=>0,'" > "'=>0,'talk'=>1,'" >  "'=>0,'`'.$wbTablePrefix.'comments`.subject'=>0);
			$array['dbInfo']['comment']['searchTitle'] = array('title','subject');
			$array['dbInfo']['comment']['searchContent'] = array('content');
				
			$array['dbInfo']['map']['class'] = 'CLASSmap';
			$array['dbInfo']['map']['dbTable'] = "`{$wbTablePrefix}maps`";
			$array['dbInfo']['map']['searchTitle'] = array('title');
			$array['dbInfo']['map']['searchContent'] = array('content');
			
			if( !isset($configData['wbWritable']) || $configData['wbWritable'] === true){
				$array['dbInfo']['theme']['class'] = 'CLASStemplate';
				$array['dbInfo']['theme']['dbTable'] = "`{$wbTablePrefix}templates`";
				$array['dbInfo']['theme']['xmlHTTP'] = 0;
				
				$array['dbInfo']['attach']['class'] = 'CLASSattachment';
				$array['dbInfo']['attach']['dbTable'] = "`{$wbTablePrefix}attachments`";
				$array['dbInfo']['attach']['dTitle'] = array("`{$wbTablePrefix}attachments`.`title` "=>0);
				//set keys to disable createNew even though it's the same
				$array['dbInfo']['attach']['keys'] = array('owner'=>1,'title'=>1);
			}
			
			//specialized datatypes
			// scripts will check for ['dbTable'] to verify which datatype is being handled
			$array['dbInfo']['talk']['class'] = 'searchTalk';
			$array['dbInfo']['special']['class'] = 'SPEC';
			$array['dbInfo']['admin']['class'] = 'ADMIN';
			
			
			
			///RESET some values differently
			if( isset($_SERVER['HTTP_HOST']) ){
				$array['serverName1'] = $array['serverName2'] = $_SERVER['HTTP_HOST'];
			}else{
				$array['serverName1'] = $array['serverName2'] = $_SERVER['SERVER_NAME'];
			}
			$array['serverName3'] = 'http://'.$array['serverName2'];
			//make a little effort to make serverName1 a little cleaner
			if( strpos($array['serverName1'],'www.') === 0){
				$array['serverName1'] = wbSubstr($array['serverName1'],4,0);
			}
			$array['serverName3'] .= $configData['wbDirPrefix'];
			
			$insert['data'] = serialize($array);
			$insert['summary'] = 'Created during software installation.';
			$insert['username'] = '';
			$insert['version'] = $packageVersion;
			
			$query = 'INSERT INTO '.$wbTables['config'].' SET ';
			$query .= wbDB::toSet($insert,true);
			
			$num = wbDB::runQuery($query,true);
			if( $num < 1){
				message('<b>Warning</b> The package configuration was not saved.');
				
			}else{
				message('The package configuration has been saved.');
				return true;
			}
		}
		
		echo '<p>Set default values for your installation.';
		echo ' </p> ';
		echo ' <br/> ';
		echo '<table cellpadding="5" style="margin-left:2em">';
		
		echo '<tr>';
			echo '<td align="left" style="width:8em"><b>';
			echo '<b>Default Title</b>';
			echo '</td><td>';
			echo '<input style="width:10em" type="text" size="20" name="wbDefaultTitle" value="'. wbHtmlspecialchars($_POST['wbDefaultTitle']).'" maxlength="20" />';
			echo '</td><td class="about">The default title for all files if one is not given.</td>';
			echo '</tr>';
		
		echo '<tr>';
			echo '<td align="left" style="width:8em">';
			echo '</td><td>';
			echo '<input style="width:10em" type="submit" size="20" name="cmd" value="Continue" />';
			echo '</td>';
			echo '</tr>';
		
		echo '</table>';		
	}
	function getByteValue($value){
		if( empty($value) ){
			return 0;
		}
		if( is_numeric($value) ){
			return (int)$value;
		}
		
		$lastChar = $value{strlen($value)-1};
		$num = (int)substr($value,0,-1);
		
		switch(strtolower($lastChar)){
			
			case 'g':
				$num *= 1024;
			case 'm':
				$num *= 1024;
			case 'k':
				$num *= 1024;
			break;
		}
		return $num;
	}	
	
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//
	//		copyTemporary1
	//
	//		File System Setup

	function copyTemporary1($action){
		global $rootDir,$configData;
		
		if( isset($configData['wbWritable']) && $configData['wbWritable'] === false){
			echo '<p>Nothing needs to be done with this step.</p>';
			return true;
		}
		
		if( $action !== 'Continue'){
			echo 'This will make sure necessary files can be found and have the correct mode.';
			return false;
		}
		
		//////////////////////////////////////////////////////////////////////////////////////////
		//
		//			Copy Temporary to rootDir
		//
		
		if( isset($configData['ftp_use']) && $configData['ftp_use'] === true){
			$conn_id = @ftp_connect($configData['ftp_server'],21,6);
			$login_result = @ftp_login($conn_id, $configData['ftp_username'], $configData['ftp_password']);
			if( !$login_result ){
				message('<b>Error:</b>FTP login failed.');
				@ftp_quit($conn_id);
				return false;
			}
			
			$tempDir = '/temporary';
			if( copyTemporaryFTP($tempDir,$configData['ftp_root'],$conn_id) ){
				@ftp_quit($conn_id);
				return true;
			}
			@ftp_quit($conn_id);
			
		}else{
			$tempRoot = $rootDir.'/temporary';
			if( copyTemporary($tempRoot,$rootDir) ){
				return true;
			}
		}
		return false;
	}
	
	function copyTemporaryFTP($from,$to,&$conn_id){
		global $rootDir,$configData;
		$avoid['.'] = true;
		$avoid['..'] = true;
		
		$done = true; //were the files copied
		
		if( $to !== $configData['ftp_root'] ){
			message('FTP: Create Directory: <tt>'.$to.'</tt>.');
			if( !is_dir($to) && !ftp_mkdir($conn_id,$to) ){
				message('<b>Error:</b> Could not create the directory: <tt>'.$to.'</tt>.');
				return false;
			}
		}
		$list = ftp_nlist($conn_id,$configData['ftp_root'].$from);
		if( !is_array($list) ){
			return true;
		}
		
		foreach($list as $file){
			$file = basename($file); //because some ftp programs will return the absolute paths
			if( isset($avoid[$file]) ){
				continue;
			}
			$fromNew = $from.'/'.$file;
			$toNew = $to.'/'.$file;
			
			if( @ftp_chdir($conn_id, $configData['ftp_root'].$fromNew) ){
				$result = copyTemporaryFTP($fromNew,$toNew,$conn_id);
				$done = $done && $result;
				
			}else{
				message('FTP: Copy file to <tt>'.$toNew.'</tt>');				
				
				if( !ftp_put($conn_id, $toNew, $rootDir.$fromNew, FTP_ASCII) ){
					$done = false;
					message('FTP: Could not write contents of <tt>'.$rootDir.$fromNew.'</tt> to <tt>'.$configData['ftp_root'].$toNew.'</tt>.');
				}
			}
		}
		return $done;
	}
	
	function copyTemporary($from,$to){
		global $rootDir;
		$avoid['.'] = true;
		$avoid['..'] = true;
		$avoid['.svn'] = true; //just in case
		
		$done = true; //were the files copied
		
		
		//Make the directory
		if( $to !== $rootDir ){
			message('Create Directory: <tt>'.$to.'</tt>.');
			
			if( !is_dir($to) && !mkDir($to,0777) ){
				message('<b>Error:</b> Could not create the directory: <tt>'.$to.'</tt>.');
				return false;
			}
			
			if( !is_writable($to) ){
				if( !@chmod($to,0777) ){
					message('<b>Error:</b> Could not change the mode for directory: <tt>'.$to.'</tt>.');
					return false;
				}
			}
		}
		
		
		if ($dh = @opendir($from)) {
			while (($file = readdir($dh)) !== false) {
				if( isset($avoid[$file]) ){
					continue;
				}
				$fromNew = $from.'/'.$file;
				$toNew = $to.'/'.$file;
				
				if( is_dir($fromNew) ){
					
					$result = copyTemporary($fromNew,$toNew);
					$done = $done && $result;
					
					
				}else{
					message('Copy file to <tt>'.$toNew.'</tt>');
					
					//New
					$contents = file_get_contents($fromNew);
					$handle = fopen($toNew,'w');
					if( !is_writable($toNew) ){
						if(!chmod($toNew,0666) ){
							$done = false;
							message('<tt>'.$toNew.'</tt> was not writable and we could not change it\'s mode.');
						}
					}else{
						if( fwrite($handle, $contents) === FALSE ) {
							$done = false;
							message('Could not write contents of <tt>'.$fromNew.'</tt> to <tt>'.$toNew.'</tt>.');
						}
					}
				}
			}
			closedir($dh);
		}else{
			$done = false;
			message('Could not open the temporary directory: <tt>'.$from.'</tt>.');
		}
		return $done;
	}
//
//		Misc Functions
//	
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//		Install Class (building)
//	
	

	class wbInstall{
		
		
		function writableWithFTP(){
			global $configData,$rootDir,$wbInstallSafeMode;
			
			$wikiFile = $configData['rootDir'].'/wiki.php';
			$conn_id = $ftp_root = false;
			
			//ftp connections will need at least the server
			if( empty($_POST['ftp_server']) ){
				message('Please supply the necessary FTP values or make the permission changes manually.');
				return false;
			}
			
			//Try to connect
			$conn_id = @ftp_connect($_POST['ftp_server'],21,6);
			if( !$conn_id ){
				message('FTP connection has failed <br/>Attempted to connect to <tt>'.$_POST['ftp_server'].'</tt> for user <tt>'.$_POST['ftp_username'].'</tt>');				
				return false;
			}
			
			
			// login with username and password
			$login_result = @ftp_login($conn_id, $_POST['ftp_username'], $_POST['ftp_password']);
			if( !$login_result ){
				message('FTP connection has failed <br/>Attempted to connect to <tt>'.$_POST['ftp_server'].'</tt> for user <tt>'.$_POST['ftp_username'].'</tt>');
				return false;
			}
			
			
			//attempt to find the ftp_root			
			$array = ftp_nlist( $conn_id, '.');
			foreach($array as $file){
				if( $ftp_root ){
					continue;
				}
				
				//is the $file within the $rootDir.. not the best test..
				$pos = strpos($rootDir,$file);
				if( $pos === false ){
					continue;
				}
				
				$possible = '/'.substr($rootDir,$pos);
				
				$modFile = ftp_mdtm($conn_id, $possible.'/wiki.php'); //not all servers support ftp_mdtm ..see following message
				if( $modFile > 0 ){
					$ftp_root = $possible;
					break;
				}
			}
			if( !$ftp_root ){
				$modFile = ftp_mdtm($conn_id,'/wiki.php');
				if( $modFile > 0 ){
					$ftp_root = '';
				}else{
					message('<strong>Warning:</strong> Your sever may not support the necessary ftp functions. Please continue manually.'); // Could not detect the ftp root.
					return false;
				}
			}
			
			
			//We've got all the ftp info, store it and move on
			$configData['ftp_root'] = $ftp_root;
			$configData['ftp_server'] = $_POST['ftp_server'];
			$configData['ftp_username'] = $_POST['ftp_username'];
			$configData['ftp_password'] = $_POST['ftp_password'];
		
		
		//
		//	Now CHMOD our two files
		//
			//chmod
			$modDir = $modFile = false;
			$modDir = ftp_site($conn_id, 'CHMOD 0777 '. $ftp_root ); //from 0755
			$modFile = ftp_site($conn_id, 'CHMOD 0666 '. $ftp_root.'/wiki.php' ); //from 0644
			
			//CHMOD and not SAFE_MODE
			if( $modDir && $modFile && !$wbInstallSafeMode ){
				@ftp_quit($conn_id);	
				return 'The FTP connection was made and commands were executed successfully. (1)';
			}
			
			//Try writing to a temporary file that could be used to ~upload with FTP
			if( $fp = tmpfile() ){
				if( fwrite($fp,'test contents') ){
					$configData['ftp_use'] = true;
					@ftp_quit($conn_id);	
					return 'The FTP connection was made and commands were executed successfully. (2)';
				}
				@fclose($fp);
			}
			message('<strong>Warning:</strong> The FTP connection was made but the installer was unable to make certain modifications. Check your FTP values, continue manually or skip this step to continue with a few features disabled.');
				
			@ftp_quit($conn_id);
			return false;
		}
		
		
		function showFileStatus(){
			global $configData;
			
			//show status
			echo '<div style="position:relative;float:right;border:1px solid #ccc;background-color:white;margin:0 0 2em 2em;">';
			echo '<table cellpadding="7">';
			echo '<tr>';
			echo '<th>File</th>';
			echo '<th>Status</th>';
			echo '</tr>';
			echo '<tr>';
			echo '<td>';
			echo '<em>';
			echo $configData['rootDir'];
			echo '</em>';
			echo '</td>';
			echo '<td>';
			if( is_writable($configData['rootDir']) ){
				echo '<span style="color:green;font-weight:bold">Writable</span>';
			}else{
				echo '<span style="color:red;font-weight:bold">Not Writable</span>';
			}
			echo '</td>';
			
			echo '</tr><tr>';
			echo '<td>';
			echo '<em>';
			$wikiFile = $configData['rootDir'].'/wiki.php';
			echo $wikiFile;
			echo '</em>';
			echo '</td>';
			echo '<td>';
			if( is_writable($wikiFile) ){
				echo '<span style="color:green;font-weight:bold">Writable</span>';
			}else{
				echo '<span style="color:red;font-weight:bold">Not Writable</span>';
			}
			echo '</td>';
			echo '</tr>';
			echo '</table>';
			echo '</div>';		
		}		
	}


//
//		Install Class
//	
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//		Misc Functions
//

function finishedNotice(){
	global $pageTitle,$configData,$wbAdminUser;
	
	$pageTitle = 'Installation is Complete... What Now?';
	echo '<p>';
	echo '<strong>Quick Links</strong>';
	echo '<ul>';
	echo '<li>This is <a href="../" target="_blank">your site\'s homepage</a>.';
	echo '<li>Choose from <a href="../?wbRedir=true&root=/Special/'.$wbAdminUser.'/Templates" target="_blank">a selection of themes</a> to use or customize.</li>';
	echo '<li>If you want maps, you\'ll need to <a href="../?wbRedir=true&root=/Admin/'.$wbAdminUser.'/EnableMaps" target="_blank">get a key from Google</a>.</li>';
	echo '</ul>';
	echo '</p>';
	
	echo '<br/>';
	
	echo '<p>';
	echo '<strong>More Options</strong>';
	echo '<ul>';
	echo '<li>Get prettier url\'s by adding an <a href="../?wbRedir=true&root=/Admin/'.$wbAdminUser.'/htaccess" target="_blank">.htaccess file</a>.</li>';
	echo '<li><a href="http://www.wikyblog.com/Main/Plugins" target="_blank">Download plugins</a> from WikyBlog.com to add more features.</li>';
	echo '<li>For more configurable options take a look at your <a href="../?wbRedir=true&root=/Special/'.$wbAdminUser.'/ControlPanel" target="_blank">Control Panel</a>.</li>';

	echo '</ul>';
	echo '</p>';
	
	?>
	
	<br/> <p> Thanks for using WikyBlog,</p>
	<p style="padding-left:3em">
	- Josh Schmidt
	<br/>
	&nbsp;
	<br/>
	Help Promote WikyBlog
	<br/>
	&nbsp;
	<br/>
	<a href="http://freshmeat.net/subscribe/60214/?url=%2Fprojects%2Fwikyblog%2F">Subscribe to</a> and <a href="http://freshmeat.net/rate/60214/">Rate</a> WikyBlog at Freshmeat.net.
	</p>
	<?php
}

// this function is in multiple files
// similar to functions in searchSearch.php, specPreferences.php
function formSelect($name,$possible,$value=null){
	$result = '<select name="'.$name.'">';
	foreach($possible as $optionKey => $optionValue){
		if($optionKey == $value){
			$focus = ' selected ';
		}else{
			$focus = '';
		}
		if( is_numeric($optionKey) ){
			$optionKey = '';
		}
		$result .= '<option value="'.wbHtmlspecialchars($optionKey).'" '.$focus.'>'.$optionValue.'</option>';
	}
	$result .= '</select>';
	return $result;
}

function unHtmlspecialchars($text){
	$search = 	array('&quot;',	'&gt;',	'&lt;',	'&#039;',	'&amp;');
	$repl = 	array('"',		'>', 	'<',	"'",		'&');
	return str_replace($search,$repl,$text);
}


//
//	Error Handling
//

// function installErrors($errno, $errmsg, $filename, $linenum, $vars){
// 	global $wbInstallErrorBuffer;
// 	
// 	// for functions prepended with @ symbol to suppress errors
// 	if($errno === 0){
// 		return;
// 	}
// 	
// 	//PHP5 E_STRICT
// 	if( !defined('E_STRICT')){
// 		define('E_STRICT',2048);
// 	}
// 	
// 	//don't report notices
// 	$excludeErrors = array(E_NOTICE,E_STRICT);
// 	if( in_array($errno, $excludeErrors) ){
// 		return;
// 	}
// 	
// 	$errortype = array (	E_ERROR				=> "Error",
// 							E_WARNING			=> "Warning",
// 							E_PARSE				=> "Parsing Error",
// 							E_NOTICE			=> "Notice",
// 							E_CORE_ERROR		=> "Core Error",
// 							E_CORE_WARNING		=> "Core Warning",
// 							E_COMPILE_ERROR		=> "Compile Error",
// 							E_COMPILE_WARNING	=> "Compile Warning",
// 							E_USER_ERROR		=> "User Error",
// 							E_USER_WARNING		=> "User Warning",
// 							E_USER_NOTICE	 	=> "User Notice",
// 							E_STRICT			=> "Runtime Notice"
// 							);
// 							
// 	$array['HTTP_HOST'] = $_SERVER['HTTP_HOST'];
// 	$array['User Request'] = $_SERVER['REQUEST_URI'];
// 	$array['ErrorType'] = $errortype[$errno] . ' :: ErrorNum '.$errno;;
// 	$array['ErrorMsg'] = $errmsg;
// 	$array['ScriptName'] = $filename;
// 	$array['ScriptLineNum'] = $linenum;
// 	if( mysql_errno() ){
// 		$array['Mysql Error '.mysql_errno()] = mysql_error();
// 	}
// 	
// 	$error = '';
// 	foreach($array as $key => $value){
// 		$error .= "\n".$key.': '.$value;
// 	}
// 	
// 	$wbInstallErrorBuffer[] = $error;
// }
// 	
