<?php
/**
 * Installer
 *
 * Create database, tables and config file
 *
 * @package SetUp PHP Competition System
 * @author  Eric GALLENE <okrome@free.fr>
 * @link	http://www.phpcompet.com
 * @version $Id: install.php,v 1.30 2006/12/20 18:43:57 andig2 Exp $
 */

require_once './../core/compatibility.php';
require_once 'installfunctions.php';
require_once './../config.inc.php';
require_once './../core/constants.php';


// required files
$upgrade_file	= './doc/updatedb.sql';

// button definitions
$button_next    = '&nbsp;&nbsp; Next &nbsp;&nbsp;>>';
$button_prev    = '<<&nbsp;&nbsp; Previous &nbsp;&nbsp;';
$button_upgrade = 'Upgrade';


// extract request parameters and disable warnings
#error_reporting (E_ERROR + E_PARSE);
error_reporting (E_ALL ^ E_NOTICE);
extract($_REQUEST, EXTR_OVERWRITE);

// set default
$upgrading = false;

// stepping back?
if (isset($formPrevious))
{

    $step -= 2;
}

// upgrading?
elseif (isset($action) && stristr($action, 'upgrade'))
{
    $upgrading = true;

    // load configuration
    include_once(CONFIG_FILE);

    // begin of upgrade?
	if (empty($step))
    {
        // set initial step for upgrading
        $step = 2;

        // set default db configuration
        if (empty($db_server))
        {
            extract($config, EXTR_OVERWRITE, 'db_');
        }


        // remove files from previous version
        foreach(array(
            'imdb.php', 'amazon.php', 'engines.php', 'functions.php',
            'setupfunctions.php', 'compatibility.php', 'template.php',
            'queryparser.php', 'genres.php', 'output.php',
            'session.php')
            as $file)
        {
            if (file_exists($file)) @rename($file, $file.'.old');
        }


        // remove old smarty cache
        delete_files('cache/smarty');
    }
}

// or first installation step?
elseif (empty($step))
{
    $step = 1;
	
	if (file_exists('install.lock')) {
		error("Install.lock exist in this directory<br />Delete this file if you want re-install");
		$step = 10;
	}
}



?>

<html>
<head>
	<title>PHP Competition System - Installation</title>
	<link rel="stylesheet" href="stylesheet.css" type="text/css" />
<!--
	<script language="JavaScript" type="text/JavaScript">
	function validate_check()
    {
		if(!document.form1.backedup.checked) {
			alert("Please confirm you have backed up your Database by checking the checkbox");
			return false;
		} else {
			return true;
		}
	}
	</script>
-->
</head>

<body>
<!--
<table width="100%" height="100%">
<tr align="center" valign="middle"><td>
-->
<table width="960" cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="white" style="margin-top: 40px">
<tr>
	<td colspan="4">
		<table width="100%" cellspacing="0" cellpadding="0" border="0">
			<tr>
				<td><img src="images/topbar.gif" width="588" height="37" border="0"></td>
				<td valign="bottom"><img src="images/logo.gif" width="372" height="26" border="0"></td>
			</tr>		
		</table>
	</td>
</tr>
<tr>
	<td id="left">&nbsp;</td>
	<td colspan="2">&nbsp;</td>
	<td id="right">&nbsp;</td>
</tr>
<tr>
	<td id="left">&nbsp;</td>
	<td colspan="2" class="tablemenu">Installer for <span class='logo'>PHP Competition System -- Step : <?=$step?></span></td>
	<td id="right">&nbsp;</td>
</tr>
<tr>
	<td id="left">&nbsp;</td>
	<td colspan="2">
		<table>
		<tr><td>


<?


// no messages yet
$message = '';

// handle installation step
switch ($step)
{

    case 3:     /*
                 * database parameters have been collected, start actual installation
                 */

                // connect to database server
                $dbh = @mysql_connect($db_server, $db_user, $db_password);
				if (!$dbh) {
					error("Can't connect: ".mysql_error(),1);
					$step--;
					break;
				}
				
				
				
                // check database existance
				if (mysql_select_db($db_database, $dbh))
                {
					error("DB already exists: ".$db_database,1);
				}
                else
                {
                    // database doesn't exist, create it
					info("Creating database...");

                    // try to create the database..
					if (!@mysql_query("CREATE DATABASE `".$db_database."`", $dbh))
                    {
						error("Can't create database: ".mysql_error($dbh),1);
						$step--;
						continue;
					}
                    else
                    {
                        // ..and select it
						if (!mysql_select_db($db_database, $dbh))
                        {
							error("Can't select database: ".mysql_error($dbh),1);
							$step--;
							continue;
						}
					}
				}
				
                // check if tables with this prefix already exist
                global $db_prefix;
				$rs = mysql_query("SHOW TABLES FROM `".$db_database."` LIKE '".$db_prefix."%'" ) or trigger_error("Can't execute: ".mysql_error($dbh), E_USER_ERROR);
				if (mysql_num_rows($rs) > 0)
                {
					error("DB has already tables with this prefix!",1);
					break;
				}

                // add root user warning
                if ($db_user == 'root')
                {
                    warn("You've used 'root' as database username. Root is often the master administration account.
                          For security reasons it is recommended that you choose a different username after
                          the installation.",1);
                }
				
                // continue with table installation
				//$step++;
				break;
				

    case 4:     /*
                 * continue installation by upgrading or installing tables and (re)moving files (upgrade only)
                 */

                if ($upgrading)
                {
					// re-connect if not continued from step 3
					if (!isset($dbh))
                    {
						$dbh = @mysql_connect($db_server, $db_user, $db_password) or trigger_error("Can't connect: ".mysql_error(), E_USER_ERROR);
						mysql_select_db($db_database, $dbh) or trigger_error("Can't select database: ".mysql_error($dbh), E_USER_ERROR);
					}

					// get version
					$sql = "SELECT value FROM {$db_prefix}config WHERE opt = 'dbversion'";
					$rs = mysql_query($sql, $dbh);
					if ($rs) list($version) = mysql_fetch_row($rs);

                    // successfully retrieved installed version?
					if (!($rs && $version))
                    {
						error("Error getting DB version, try full install instead of upgrade: ".mysql_error($dbh));
						error("<br/><br/><pre>$sql</pre>");
						$step--;
						break;
					}
					
                    // already correct db version? this might happen if just the username/ password were wrong
                    //if ($config['dbneeded'] == DB_REQUIRED)
                    //{
                    //    info("No database upgrade needed");
                    //    break;
                    //}

					// upgrade
					info("<br/>Upgrading tables...");
					info("Old database version: $version");
					
					// perform actual upgrade
					$upgrades = parse_upgrades();
					if (empty($upgrades[$version+1]))
                    {
						error("The required target version is not available.");					
						$step--;
						break;
					}
					else
                    {
						$sql_array = array();
						// select the relevant upgrades (> current version)
						foreach ($upgrades as $ver => $value)
                        {
							if ($ver > $version) $sql_array["$ver"] = $value;
						}

                        // upgrades successful?
                        $version = db_upgrade($sql_array);
						if (is_numeric($version))
                        {
                            info("New database version: $version");
                        }
                        else
                        {
                            // error
                            $step--;
                        }
						// create install.lock
						info("<br/>Writing lock file...");
						$locked = array('install' => 'ok');

                        if (!file_put_contents('./install.lock', $locked))
                        {
                            error('<br/>Could not write lock file install.lock!<br/><br/>', 1);
						}
					}
				}
				else
				{
					// install
					info("<br/>Installing tables...");

					// re-connect if not continued from step 3
					if (!$dbh) {
						$dbh = @mysql_connect($db_server, $db_user, $db_password) or trigger_error("Can't connect: ".mysql_error(), E_USER_ERROR);
						mysql_select_db($db_database, $dbh) or trigger_error("Can't select database: ".mysql_error($dbh), E_USER_ERROR);
					}

					// open SQL script from doc directory
					$sql = file_get_contents('doc/createtables.sql');
					if (!$sql) trigger_error('Couldn\'t open SQL file: doc/createtables.sql', E_USER_ERROR);

                    if (runSQL($sql, $dbh) === false) {
						error('Error creating tables: '.mysql_error($dbh));
						error('<br/><br/><pre>'.$sql.'</pre>');
						$step--;
					}
					else
                    {
						// create config file
						info("<br/>Writing config file...");
						$config = parse_config(array(
							'db_server'		=> $db_server,
							'db_user'		=> $db_user,
							'db_password'	=> $db_password,
                            'db_database'   => $db_database,
                            'db_prefix'     => $db_prefix), true);

                        if (!file_put_contents('../config.inc.php', $config))
                        {
                            error('<br/>Could not write config file ../config.inc.php !
									   <br/>Please make sure your config file contains the following lines:<br/><br/>'.
									   highlight_string($config, 1));
						}
						// create install.lock
						info("<br/>Writing lock file...");
						$locked = array('install' => 'ok');

                        if (!file_put_contents('./install.lock', $locked))
                        {
                            error('<br/>Could not write lock file install.lock!<br/><br/>', 1);
						}
					}
				}

				break;
				
}


// determine next installation step
switch ($step)
{

    case 4:     // start PHP Compet
                $action_target = '../index.php';
                break;
    default:    // continue installation
                $action_target = 'install_en.php';
}


?>
            <form name='form1' method='post' action='<?=$action_target?>'>
            <table>
<?

if ($upgrading)
{

    echo "<input type='hidden' name='action' value='upgrade'/>";
}

switch ($step)
{
case 10:		// PHP Compet already installed


?>				<tr><td colspan="2">
                    <?=$message?>
					<b>Error</b><br/><br/>
					PHP Competition System is already installed on this server<br/>
					<br/>
                    
				</td></tr>

				<tr><td colspan="2">
					<input class="button" type="button" name="back" value="<< &nbsp;&nbsp; Back" id="back" onClick="javascript:history.go(-1);"/>
				</td></tr>
<?				break;

	case 4:		// start PHP Compet
                $installed = ($upgrading) ? 'upgraded' : 'installed';

?>				<tr><td colspan="2">
                    <?=$message?>
					<b>Installation successful!</b><br/><br/>
					PHP Competition System database and tables have been successfully <?=$installed?>.<br/>
					<br/>
                    <?
                        // different settings than config file specified?
                        if (($db_server     != $config['db_server']) ||
                            ($db_database   != $config['db_database']) ||
                            ($db_user       != $config['db_user']) ||
                            ($db_password   != $config['db_password']) ||
                            ($db_prefix     != $config['db_prefix']))
                        {
                            warn('Your username/ password chosen for this upgrade do not match your config file. Please make sure
                                  to update the config file.', true);
                        }

                        warn('For security reasons this file (install.php) should be deleted after the installation.
                              You can later adjust the database settings by modifying the '.CONFIG_FILE.' file.', true);
                    ?>
					Click <b>Start</b> to begin using <b>PHP Competition System</b>...<br/>
					<br/>
				</td></tr>

				<tr><td colspan="2">
					<input type="hidden" name="step" value="<?=$step?>"/>
					<input class="button" type="submit" name="submit" value="Start &nbsp;&nbsp;>>" id="focus"/>
					<script language='JavaScript'>form1.focus.focus();</script>
				</td></tr>
<?				break;

	case 3:		// confirm installation if tables exist
                $install = ($upgrading) ? 'Installing' : 'Upgrading';
				
                if ($upgrading)
                {
?>
                    <tr><td colspan="2">
                        <br/><b><?=$install?> database and tables.</b><br/><br/>
                        <?=$message?>
                        <br/>
                    </td></tr>
<?
                } else {
?>
                    <tr><td colspan="2">
                        <br/><b><?=$install?> database and tables.</b><br/><br/>
                        <?=$message?>
                        You have selected a <b>non-empty</b> database. Installing into a non-empty database might lead to data loss and is only recommended for experienced users.
                        <br/>
                    </td></tr>

                    <tr><td colspan="2">
                        <br/>
                        Choose <b>Upgrade</b> to upgrade the existing installation (recommended).
                        Before upgrading, please make sure to backup your database!<br/>
                        <br/>
                    </td></tr>

                    <tr><td colspan="2">
                        <input class="button" type="submit" name="action" value="<?=$button_upgrade?>" id="focus"/>
                        <br/>
                    </td></tr>

                    <tr><td colspan="2">
                        <br/>
                        Click <b>Next</b> to install the tables into the existing <b>non-empty</b> database...<br/>
                        <br/>
                    </td></tr>
<?
                }
?>
				<tr><td colspan="2">
					<input type="hidden" name="db_server" value="<?=$db_server?>"/>
					<input type="hidden" name="db_user" value="<?=$db_user?>"/>
					<input type="hidden" name="db_password" value="<?=$db_password?>"/>
					<input type="hidden" name="db_database" value="<?=$db_database?>"/>
					<input type="hidden" name="db_prefix" value="<?=$db_prefix?>"/>
					<input type="hidden" name="step" value="<?=$step+1?>"/>
					<input class="button" type="submit" name="formPrevious" value="<?=$button_prev?>"/>
					<input class="button" type="submit" name="submit" value="<?=$button_next?>"/>
					<script language='JavaScript'>form1.focus.focus();</script>
				</td></tr>
<?				break;

	case 2:		// get setup parameters
                $install = ($upgrading) ? 'upgrade' : 'install';

				if (empty($db_server))  $db_server	= 'localhost';
				if (empty($db_user))	$db_user	= 'root';
				if (empty($db_password)) $db_password = '';
				if (empty($db_database)) $db_database = 'phpcompetition';
				if (empty($db_prefix)) $db_prefix = 'pcs_';
?>
                <tr><td colspan="2">
<?
                    if ($upgrading)
                    {
                        // skip the database creation step
                        $step++;
?>
                        <br/><b>Database Upgrade</b><br/>
                        <br/>Your database does not match the current version of PHP Competition System and needs to be upgraded.<br/>
                        <br/>
                        <? warn("Please make sure to backup your database before proceeding!", true); ?>
                        <b>Select database and user.</b><br/>
                        <br/>
<?
                    } else {
?>
                        <br/><b>Select database and user.</b><br/>
                        <br/>
                        <b>Note:</b> unless you're installing into an existing database, the database login must have <b>'Create Database'</b> rights.
                        <br/><br/>
<?
                    }
?>
                    <?=$message?>
				</td></tr>

				<tr><td>Server:</td><td><input type="text" name="db_server" value="<?=$db_server?>" id="focus"/></td></tr>
				<tr><td>User:</td><td><input type="text" name="db_user" value="<?=$db_user?>"/></td></tr>
				<tr><td>Password:</td><td><input type="password" name="db_password" value="<?=$db_password?>"/></td></tr>
                <tr><td>Database:</td><td><input type="text" name="db_database" value="<?=$db_database?>"/></td></tr>
                <tr><td>Table prefix:</td><td><input type="text" name="db_prefix" value="<?=$db_prefix?>"/> (only required for new installations)</td></tr>

				<tr><td colspan="2">
					<br/>
                    Click <b>Next</b> to <?=$install?> database and tables...<br/>
					<br/>
				</td></tr>

				<tr><td colspan="2">
					<input type="hidden" name="step" value="<?=$step+1?>"/>
					<input class="button" type="submit" name="formPrevious" value="<?=$button_prev?>"/>
					<input class="button" type="submit" name="submit" value="<?=$button_next?>"/>
					<script language='JavaScript'>form1.focus.focus();form1.focus.select();</script>
				</td></tr>
<?				break;

	case 1:		
	default:	// start setup

?>				<tr><td colspan="2">
					<br/>This is the installer for <span style="font-weight:bold;"><a style="color:#333399" href="http://phpcompet.free.fr">PHP Competition System</a></span>. You will require:
					<ol>
						<li><b>PHP &gt;= 4.2.0</b> with GD library and session support configured.</li><br/><br/>
						<li>A <b>MySQL database</b>, login (username and password) with create/drop table rights.</li><br/><br/>
						<li>If you want this installer to create the config file for you, it needs permission to write to web server's the PHP Competition System <b>root directory</b>.</li><br/><br/>
					</ol>
					The installer will create a database in your MySQL installation, create and populate the required tables, and generate the PHP Competition System configuration file.<br/><br/>
<!--
					<input type="checkbox" name="backedup"> <b>I have backed up my database incase of a problem with this upgrade.</b><br/><br/>
-->
					Click <b>Next</b> to setup the database connection...<br/><br/>

					<input type="hidden" name="step" value="<?=$step+1?>"/>
					<input class="button" type="submit" name="submit" value="<?=$button_next?>" id="focus"/>
					<script language='JavaScript'>form1.focus.focus();</script>
				</td></tr>
<?
}

?>
            </table>
            </form>

			<br/><font size="1" color="#CCCCCC">Step: <?=$step?></font>
		</td>
		</tr>
		</table>
	</td>
	<td id="right">&nbsp;</td>
</tr>
<tr>
	<td id="left">&nbsp;</td>
	<td colspan="2">
		<table width="100%" cellspacing="0" cellpadding="0" border="0">
			<tr>
				<td align="center" valign="middle"><a href="http://www.mysql.com" target="_blank"><img src="../images/mysql.gif" width="100" height="52" border="0"></a></td>
				<td align="center" valign="middle"><a href="http://smarty.php.net" target="_blank"><img src="../images/smarty.gif" width="88" height="31" border="0"></a></td>
				<td align="center" valign="middle"><a href="http://www.php.net" target="_blank"><img src="../images/php.gif" width="69" height="36" border="0"></a></td>
			</tr>		
		</table>
	</td>
	<td id="right">&nbsp;</td>
</tr>
<tr>
	<td colspan="4">
		<table width="100%" cellspacing="0" cellpadding="0" border="0">
			<tr>
				<td valign="top"><img src="images/bottomlogo.gif" width="372" height="26" border="0"></td>
				<td><img src="images/bottombar.gif" width="588" height="37" border="0"></td>
			</tr>		
		</table>
	</td>
</tr>

</table>

</body>
</html>
