<?php
/**
* This file is part of the easy-CMS project.
* easy-CMS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* easy-CMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with easy-CMS; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
include_once('egConfig.inc.php');

// if the config file has already been generated redirect to index.php
if (is_file('config.inc.php')) {
 	$scriptPath = substr(dirname($_SERVER["PHP_SELF"]), 1);
	$location = "http://".$_SERVER["SERVER_NAME"];
	if(strlen($scriptPath)) {
    $location .= "/".$scriptPath;
	}
  $location .= '/index.php';
  header('Location: '.$location);
  exit(0);
}

if(strstr(get_include_path(), '\\')) {
	define('DIR_SEPARATOR', '\\');
	define('LINE_SEPARATOR', "\r\n");
}
else {
	define('DIR_SEPARATOR', '/');
	define('LINE_SEPARATOR', "\n");
}

define('DEBUG_LEVEL', 10);
define('MAX_LOG_SIZE', 2000000);

define('REPOSITORY_FOLDER', 'Repositories');
define('CACHE_FOLDER', 'Cache');
define('LOGS_FOLDER', 'Logs');
define('IMAGES_FOLDER', 'Images');
define('DOCUMENTS_FOLDER', 'Documents');
define('TEMPLATES_FOLDER', 'Templates');
define('STYLES_FOLDER', 'Styles');
define('VERSIONS_FOLDER', 'Versions');
define('CONTENTS_VERSIONS_FOLDER', 'Contents');


$DBMS_ARRAY = array('MySQL' => 'MYSQL');
$LANGS_ARRAY = array('english' => 'LANG_EN', 'francais' => 'LANG_FR' );

define('ASK_CREATE_NEW_DB', 1);
define('ASK_USE_EXISTING_DB', 2);


define('DB_UNRESOLVABLE_HOST_ERROR', 1);
define('DB_UNABLE_TO_CONNECT_ERROR', 2);
define('DB_UNKNOWN_DBMS_ERROR', 4);
define('DB_AUTHENTICATION_ERROR', 8);
define('DB_CREATION_ERROR', 16);
define('DB_ACCESS_DENIED_ERROR', 32);
define('DB_ALREADY_EXISTS_ERROR', 64);
define('DB_USER_ALREADY_EXISTS_ERROR', 128);
define('DB_USER_CREATION_ERROR', 256);
define('DBMS_ERROR', 512);
define('DB_NOT_FOUND', 1024);
define('DB_NOT_UPDATABLE', 2048);
define('SQL_SCHEMA_CORRUPT_ERROR', 4096);
define('HTACCESS_CREATION_ERROR', 8192);
define('REPOSITORIES_CREATION_ERROR', 16384);
define('CONFIG_CREATION_ERROR', 32768);



include_once('interface/egScript.class.php');
include_once('interface/egManager.class.php');
include_once('interface/egContainer.class.php');
include_once('interface/egMenuItem.class.php');
include_once('interface/egFrame.class.php');
include_once('interface/egToolTip.class.php');
include_once('interface/egRichText.class.php');
include_once('interface/egLink.class.php');
include_once('interface/egStatic.class.php');
include_once('interface/egEdit.class.php');
include_once('interface/egCheckBox.class.php');
include_once('interface/egRadioButton.class.php');
include_once('interface/egPressButton.class.php');
include_once('interface/egDropDownListBox.class.php');
include_once('interface/egPropertyList.class.php');
include_once('interface/egPropertySheet.class.php');
include_once('interface/egPropertyPage.class.php');
include_once('interface/egTreeNode.class.php');
include_once('interface/egTreeList.class.php');
include_once('interface/egSubWindow.class.php');


/**
 *
 *  Define our own error handler
 */
set_error_handler('errorHandler');
error_reporting(E_ALL);
function errorHandler($errno, $errstr, $errfile, $errline, $errcontext) {
}

/**
 *
 *  Function to make a recurse copy of a filesystem folder
 *
 */
function dircopy($srcdir, $dstdir) {
  if(!is_dir($dstdir)) {
		mkdir($dstdir, 0755);
	}
	if($curdir = opendir($srcdir)) {
		while($file = readdir($curdir)) {
      if($file[0] != '.') {
       $srcfile = $srcdir.DIR_SEPARATOR.$file;
       $dstfile = $dstdir.DIR_SEPARATOR.$file;
       if(is_file($srcfile)) {
         if(!copy($srcfile, $dstfile)) {
					return false;
         }
       }
       else if(is_dir($srcfile)) {
         if(!dircopy($srcfile, $dstfile)) {
					return false;
				 }
       }
     }
   }
   closedir($curdir);
  }
	else {
		return false;
	}
  return true;
}

/**
 *
 *  Function to get an IP address from a hostname
 *  returns false if the hostname cannot be resolved
 *
 */
function resolveHost($host) {
	$ip = gethostbyname($host);
	if ($ip != $host) {
		return $ip;
	}
	return false;
}

/**
 *
 *  Function to check the connectivity to a server
 *  returns false if the connection cannot be set up
 *
 */
function connectToServer($ip, $port) {
	if($fp = fsockopen($ip, $port, $errno, $errstr, 3)) {
		fclose($fp);
		return true;
	}
  // connection refused means that the server is alive
  if($errno == 111) {
    return true;
  }
	return false;
}



// init the session if necessary
if(strlen(session_id()) <= 0){
	session_start();
}

if(!isset($_POST['step'])) {
	if(!isset($_GET['step'])) {
  	$_POST['step'] = 1;
	}
	else {
  	$_POST['step'] = $_GET['step'];
	}
}

if(isset($_POST['action'])) {
	$_SESSION['action'] = $_POST['action'];
  $action = $_POST['action'];
}
else {
  if(isset($_SESSION['action'])) {
    $action = $_SESSION['action'];
  }
  else {
    $action = 1;
  }
}

$step = $_POST['step'];


$errorCode = 0;

if(isset($_POST['err_code'])){
  $errorCode = $_POST['err_code'];
}

switch($step) {
  case 1:
		processStep1();
    displayStep1($errorCode);
    break;
  case 2:
		if(!($errorCode = processStep2())) {
			if($action == ASK_USE_EXISTING_DB) {
	    	displayStep4();
				break;
			}
			else {
	    	displayStep3();
				break;
			}
		}
		displayStep2($errorCode);
		break;
  case 3:
		if(!($errorCode = processStep3())) {
    	displayStep5();
			break;
		}
    displayStep3($errorCode);
    break;
  case 4:
		if(!($errorCode = processStep4())) {
    	displayStep5();
			break;
		}
    displayStep4($errorCode);
    break;
  case 5:
		if(!($errorCode = processStep5())) {
      displayStep6();
      break;
    }
    displayStep5($errorCode);
    break;
  case 6:
		if(!($errorCode = processStep6())) {
      displayStep7();
			break;
    }
  	displayStep6($errorCode);
    break;
  default:
    die('invalid step index');
}


/**
 *
 * init all sessions vars
 *
 */
function processStep1() {
	session_destroy();
}

/**
 *
 * returns 0 if step has been sucessfully processed, -1 if form must be (re)displayed
 *
 */
function processStep2() {
	global $DBMS_ARRAY;
	$error = 0;

	if(!isset($_POST['dbms']) || !isset($_POST['host']) || !isset($_POST['port'])) {
		// first call : display the form
		return -1;
	}

	$dbms = $_POST['dbms'];
	$host = $_POST['host'];
	$port = $_POST['port'];

	if(!($ip = resolveHost($host))) {
		$error |= DB_UNRESOLVABLE_HOST_ERROR;
	}
	else {
		if(!connectToServer($ip, $port)) {
			$error |= DB_UNABLE_TO_CONNECT_ERROR;
		}
	}

	if(!in_array($dbms, $DBMS_ARRAY)) {
		$error |= DB_UNKNOWN_DBMS_ERROR;
	}

	if(!$error) {
		$_SESSION['dbms'] = $_POST['dbms'];
		$_SESSION['host'] = $_POST['host'];
		$_SESSION['port'] = $_POST['port'];
	}

	return $error;
}


/**
 *
 * returns 0 if step has been sucessfully processed, -1 if form must be (re)displayed
 *
 */
function processStep3() {
	$error = 0;

	if(!isset($_POST['admin_user']) || !isset($_POST['admin_password']) || !isset($_POST['db_name']) || !isset($_POST['db_user']) || !isset($_POST['db_password'])) {
		// first call : display the form
		return -1;
	}

	if(isset($_POST['admin_user'])) {
		$overwrite = (bool) $_POST['overwrite'];
	}
	else {
		$overwrite = false;
	}

	// retrieve required informations
	if(!isset($_SESSION['host']) || !isset($_SESSION['port']) || !isset($_SESSION['dbms'])) {
		die('missing session vars');
	}
	$host = $_SESSION['host'];
	$port = $_SESSION['port'];
	$dbms = $_SESSION['dbms'];

	$adminUser 		= $_POST['admin_user'];
	$adminPassword 	= $_POST['admin_password'];
	$dbName 		= $_POST['db_name'];
	$dbUser 		= $_POST['db_user'];
 	$dbPassword 	= $_POST['db_password'];

	switch($dbms) {
		case 'MYSQL' :
			if(!$sql_handler = mysql_connect($host.":".$port, $adminUser, $adminPassword)){
				$error |= DB_AUTHENTICATION_ERROR;
			}
			else {
				if (mysql_select_db('mysql')) {
					// already defined DB test 1
					$result = mysql_list_dbs();
					while ($row = mysql_fetch_object($result)) {
						if($row->Database == $dbName) {
							$error |= DB_ALREADY_EXISTS_ERROR;
							break;
						}
					}
					// already defined DB test 2
					$query = "select * from `db` where `Host` = '$host' and `Db` = '$dbName' and `User` = '$dbUser';";
					if($result = mysql_query($query)) {
						if($row = mysql_fetch_array($result)) {
							$error |= DB_ALREADY_EXISTS_ERROR;
						}
						else {

							$query = "select * from `user` where `Host` = '$host' and `User` = '$dbUser';";
							if($result = mysql_query($query)) {

								if($row = mysql_fetch_array($result)) {
									$error |= DB_USER_ALREADY_EXISTS_ERROR;
								}
								else {
									$query = "CREATE DATABASE $dbName;";
									if(!$result = mysql_query($query)) {
										$error |= DB_CREATION_ERROR;
										return $error;
									}

									$query = "INSERT INTO `user` (Host,User,Password) VALUES ('$host','$dbUser',PASSWORD('$dbPassword'));	";
									if(!$result = mysql_query($query)) {
										$error |= DB_USER_CREATION_ERROR;
										return $error;
									}

									$query = "INSERT INTO `db` (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES ('$host','$dbName','$dbUser','Y','Y','Y','Y','Y','Y');";
									if(!$result = mysql_query($query)) {
										$error |= DB_CREATION_ERROR;
										return $error;
									}

									$query = "FLUSH PRIVILEGES;";
									if(!$result = mysql_query($query)) {
										$error |= DB_CREATION_ERROR;
										return $error;
									}
								}
							}
						}
					}
					else {
						$error |= DBMS_ERROR;
					}
				}
				else {
					$error |= DBMS_ERROR;
				}
				mysql_close($sql_handler);
			}
			break;
		default :
			break;
	}

	if(!$error) {
		$_SESSION['db_name']		= $_POST['db_name'];
		$_SESSION['db_user']		= $_POST['db_user'];
		$_SESSION['db_password'] 	= $_POST['db_password'];
		$_SESSION['admin_user'] 	= $_POST['admin_user'];
		$_SESSION['admin_password'] = $_POST['admin_password'];
	}

	return $error;
}


/**
 *
 * returns 0 if step has been sucessfully processed, -1 if form must be (re)displayed
 *
 */
function processStep4() {
	$error = 0;

	if(!isset($_POST['db_user']) || !isset($_POST['db_password']) || !isset($_POST['db_name'])) {
		// first call : display the form
		return -1;
	}

	$_SESSION['db_name'] = $_POST['db_name'];

	// retrieve required informations
	if(!isset($_SESSION['host']) || !isset($_SESSION['port']) || !isset($_SESSION['dbms']) || !isset($_SESSION['db_name'])) {
		die('missing session vars');
	}
	$host 	= $_SESSION['host'];
	$port 	= $_SESSION['port'];
	$dbms 	= $_SESSION['dbms'];
	$dbName	= $_SESSION['db_name'];

	$dbUser 		= $_POST['db_user'];
	$dbPassword = $_POST['db_password'];

	switch($dbms) {
		case 'MYSQL' :
			if(!$sql_handler = mysql_connect($host.":".$port, $dbUser, $dbPassword)){
				$error |= DB_AUTHENTICATION_ERROR;
			}
			else {
				if (!$result = mysql_select_db($dbName)) {
					mysql_close($sql_handler);
					$error |= DB_ACCESS_DENIED_ERROR;
				}
			}
			break;
		default :
			break;
	}

	if(!$error) {
		$_SESSION['db_name']		 = $_POST['db_name'];
		$_SESSION['db_user'] 		 = $_POST['db_user'];
		$_SESSION['db_password'] = $_POST['db_password'];
	}

	return $error;
}

/**
 *
 * returns 0 if step has been sucessfully processed, -1 if form must be (re)displayed
 *
 */
function processStep5() {
	$error = 0;

	if(!isset($_POST['cms_admin_login']) || !isset($_POST['cms_admin_password'])) {
		// first call : display the form
		return -1;
	}

  $dbAlreadyExists = false;
  $dbUpdatable = false;

	// retrieve required informations
	if(!isset($_SESSION['host']) || !isset($_SESSION['port']) || !isset($_SESSION['dbms']) || !isset($_SESSION['db_name']) || !isset($_SESSION['db_user']) || !isset($_SESSION['db_password'])) {
		die('missing session vars');
	}
	$host 			= $_SESSION['host'];
	$port 			= $_SESSION['port'];
	$dbms 			= $_SESSION['dbms'];
	$dbName 		= $_SESSION['db_name'];
	$dbUser 		= $_SESSION['db_user'];
	$dbPassword = $_SESSION['db_password'];

	$adminLogin    = $_POST['cms_admin_login'];
	$adminPassword = $_POST['cms_admin_password'];

  $_SESSION['cms_admin_login']    = $_POST['cms_admin_login'];
  $_SESSION['cms_admin_password'] = $_POST['cms_admin_password'];

	if(isset($_POST['action'])) {
		$_SESSION['action'] = $_POST['action'];
	}

	// check for a previous version
	switch($dbms) {
		case 'MYSQL' :
			if($sql_handler = mysql_connect($host.":".$port, $dbUser, $dbPassword)){
				if (mysql_select_db($dbName)) {
					$dbAlreadyExists = true;
					$query = "select * from `easy_cms_infos`;";
					if($result = mysql_query($query)) {
						if($row = mysql_fetch_array($result)) {
		  				$_SESSION['old_version_number']			= $row['version'];
		  				$_SESSION['old_version_released']		= $row['released'];
		  				$_SESSION['old_version_installed']	= $row['installed'];
		  				$_SESSION['old_version_code_name']	= $row['codename'];
						}
					}
				}
				else {
					mysql_close($sql_handler);
					return DBMS_ERROR;
				}
				mysql_close($sql_handler);
			}
			else {
				return DBMS_ERROR;
			}
			break;
		default:
			break;
	}

	if($_SESSION['action'] == ASK_USE_EXISTING_DB) {
		// check the easy-CMS version signature and try to update
		if(!$dbAlreadyExists) {
			$error |= DB_NOT_FOUND;
		}
		else {
			// check if the current DB is supported for update
			switch($_SESSION['old_version_number']) {
				case "1.0.0b1" :
					if($sql_handler = mysql_connect($host.":".$port, $dbUser, $dbPassword)){
						if(mysql_select_db($dbName)) {
							$dbUpdatable = true;
							$query = "UPDATE `easy_cms_users` SET `login` = '$adminLogin', `password` = '".md5($adminPassword)."' where `id`= 1;";
							if(!mysql_query($query)) {
							  $error |= DBMS_ERROR;
							}
							$query = "UPDATE `easy_cms_infos` SET `installed` = '".date('Y-m-d')."';";
							if(!mysql_query($query)) {
							  $error |= DBMS_ERROR;
							}
						}
					}
					break;
				default:
					$error |= DB_NOT_UPDATABLE;
					break;
			}
		}
	}
	else {
		// use the newly created database
		switch($dbms) {
			case 'MYSQL' :
				// import sql schema to the database
				if($sql_handler=mysql_connect($host.":".$port, $dbUser, $dbPassword)){
					if(mysql_select_db($dbName)) {
				    $sqlSchema = file_get_contents('install/easycms_new.sql');
            // determine the line separator
            $separator = '';
            $i = strpos($sqlSchema, ';')+1;
            while($sqlSchema[$i] == "\n" || $sqlSchema[$i] == "\r") {
              $separator .= $sqlSchema[$i];
              ++$i;
            }
			$sqlArray = explode(';'.$separator, $sqlSchema);
			foreach($sqlArray as $key => $query) {
				if(!isset($query) || strlen($query) <= 3) {
					continue;
				}
				$query .= ';';
				if(!mysql_query($query)) {
					$error |= SQL_SCHEMA_CORRUPT_ERROR;
					break;
				}
			}
            $query = "UPDATE `easy_cms_users` SET `login` = '$adminLogin', `password` = '".md5($adminPassword)."' where `id`= 1;";
            if(!mysql_query($query)) {
				$error |= DBMS_ERROR;
            }
            $query = "UPDATE `easy_cms_infos` SET `installed` = '".date('Y-m-d')."';";
            if(!mysql_query($query)) {
						  $error |= DBMS_ERROR;
            }
					}
					else {
						$error |= DBMS_ERROR;
					}
					mysql_close($sql_handler);
				}
				else {
					$error |= DBMS_ERROR;
				}
				break;
			default :
				break;
		}
	}
	return $error;
}

function processStep6() {
	$error = 0;

	if(!isset($_POST['language']) || !isset($_POST['enable_security']) || !isset($_POST['enable_publication']) || !isset($_POST['publication_state']) || !isset($_POST['enable_versionning']) || !isset($_POST['versions_history']) || !isset($_POST['enable_logging']) || !isset($_POST['debug_level'])) {
		// first call : display the form
		return -1;
	}

	// retrieve required informations
	if(!isset($_SESSION['host']) || !isset($_SESSION['port']) || !isset($_SESSION['dbms']) || !isset($_SESSION['db_name']) || !isset($_SESSION['db_user']) || !isset($_SESSION['db_password'])) {
		die('missing session vars');
	}
	$host 			= $_SESSION['host'];
	$port 			= $_SESSION['port'];
	$dbms 			= $_SESSION['dbms'];
	$dbName 		= $_SESSION['db_name'];
	$dbUser 		= $_SESSION['db_user'];
	$dbPassword = $_SESSION['db_password'];

	$language = $_POST['language'];
	$enableSecurity = $_POST['enable_security'];
	$enablePublication = $_POST['enable_publication'];
	$enableVersionning = $_POST['enable_versionning'];
	$defaultPublicationState = $_POST['publication_state'];

	$versionsHistory = $_POST['versions_history'];
	$enableLogging = $_POST['enable_logging'];
	$debugLevel = $_POST['debug_level'];


	/**
	 *
	 * Check validity of the parameters value
	 */
	if($debugLevel < 0) {
		$debugLevel = 0;
	}
	if($debugLevel > 10) {
		$debugLevel = 10;
	}
	if($versionsHistory < 0) {
		$versionsHistory = 0;
	}
	if($versionsHistory > 15) {
		$versionsHistory = 15;
	}
	$enableSecurity = (int)((bool) $enableSecurity);
	$enablePublication = (int)((bool) $enablePublication);
	$enableVersionning = (int)((bool) $enableVersionning);
	$enableLogging = (int)((bool)$enableLogging);
	$defaultPublicationState = (int)((bool)$_POST['publication_state']);


	/**
	 *
	 * generate the root .htaccess file for url rewriting
	 */
  $scriptPath = dirname($_SERVER["PHP_SELF"]);
  if(strlen($scriptPath) < 2) {
    $scriptPath = '';
  }
  $htaccess_content = "Options -Indexes\n";
  $htaccess_content .= "ErrorDocument 404 $scriptPath/index.php?resolve_alias=1";
	$htaccessFile = '.htaccess';
	if(!($file = @fopen($htaccessFile, 'w'))) {
		// Unable to open file
		$error |= HTACCESS_CREATION_ERROR;
	}
	if($file) {
		if (!(@fwrite($file, $htaccess_content))) {
			// Unable to write to file 
			$error |= HTACCESS_CREATION_ERROR;
		}
		fclose($file);
	}


	/**
	 *
	 * create repositories folders and copy installation folders
	 */
 	$scriptPath = '';
  if(strstr(get_include_path(), '\\')) {
    //windows environment
 	  $scriptPath = dirname($_SERVER["PATH_TRANSLATED"]).DIRECTORY_SEPARATOR;
  }

	$repositoryFolder 			= $scriptPath.REPOSITORY_FOLDER;
	$cacheFolder 						= $scriptPath.REPOSITORY_FOLDER.DIRECTORY_SEPARATOR.CACHE_FOLDER;
	$logsFolder 						= $scriptPath.REPOSITORY_FOLDER.DIRECTORY_SEPARATOR.LOGS_FOLDER;
	$imagesFolder 					= $scriptPath.REPOSITORY_FOLDER.DIRECTORY_SEPARATOR.IMAGES_FOLDER;
	$documentsFolder 				= $scriptPath.REPOSITORY_FOLDER.DIRECTORY_SEPARATOR.DOCUMENTS_FOLDER;
	$stylesFolder 					= $scriptPath.REPOSITORY_FOLDER.DIRECTORY_SEPARATOR.STYLES_FOLDER;
	$templatesFolder 				= $scriptPath.REPOSITORY_FOLDER.DIRECTORY_SEPARATOR.TEMPLATES_FOLDER;
	$versionsFolder 				= $scriptPath.REPOSITORY_FOLDER.DIRECTORY_SEPARATOR.VERSIONS_FOLDER;
	$contentsVersionsFolder = $scriptPath.REPOSITORY_FOLDER.DIRECTORY_SEPARATOR.VERSIONS_FOLDER.DIRECTORY_SEPARATOR.CONTENTS_VERSIONS_FOLDER;

	if(!is_dir($repositoryFolder) && !mkdir($repositoryFolder, 0755)){
		//Unable to create main repository folder
		$error |= REPOSITORIES_CREATION_ERROR;
	}

	if(!is_dir($cacheFolder) && !mkdir($cacheFolder, 0755)){
		//Unable to create cache folder
		$error |= REPOSITORIES_CREATION_ERROR;
	}

	if(!is_dir($logsFolder) && !mkdir($logsFolder, 0755)){
		//Unable to create logs folder
		$error |= REPOSITORIES_CREATION_ERROR;
	}

	if(!is_dir($imagesFolder) && !mkdir($imagesFolder, 0755)){
		//Unable to create images folder
		$error |= REPOSITORIES_CREATION_ERROR;
	}

	if(!is_dir($documentsFolder) && !mkdir($documentsFolder, 0755)){
		//Unable to create documents folder
		$error |= REPOSITORIES_CREATION_ERROR;
	}

	if(!is_dir($templatesFolder) && !mkdir($templatesFolder, 0755)){
		//Unable to create templates folder
		$error |= REPOSITORIES_CREATION_ERROR;
	}

	if(!is_dir($stylesFolder) && !mkdir($stylesFolder, 0755)){
		//Unable to create styles folder
		$error |= REPOSITORIES_CREATION_ERROR;
	}

	if(!is_dir($versionsFolder) && !mkdir($versionsFolder, 0755)){
		//Unable to create versions folder
		$error |= REPOSITORIES_CREATION_ERROR;
	}

	if(!is_dir($contentsVersionsFolder) && !mkdir($contentsVersionsFolder, 0755)){
		//Unable to create contents versions folder
		$error |= REPOSITORIES_CREATION_ERROR;
	}

	if(!dircopy($scriptPath.'install'.DIRECTORY_SEPARATOR.'Images', $imagesFolder)) {
		//Unable to create images folder
		$error |= REPOSITORIES_CREATION_ERROR;
	}
	if(!dircopy($scriptPath.'install'.DIRECTORY_SEPARATOR.'Templates', $templatesFolder)) {
		//Unable to copy templates folder
		$error |= REPOSITORIES_CREATION_ERROR;
	}
	if(!dircopy($scriptPath.'install'.DIRECTORY_SEPARATOR.'Styles', $stylesFolder)) {
		//Unable to copy styles folder
		$error |= REPOSITORIES_CREATION_ERROR;
	}


	/**
	 *
	 * generate the Repository .htaccess file to prevent repositories browsing
	 */
  $htaccess = "Options -Indexes";
	$htaccessFile = $repositoryFolder.DIRECTORY_SEPARATOR.'.htaccess';
	if(!($file = @fopen($htaccessFile, 'w'))) {
		// Unable to open file
		$error |= HTACCESS_CREATION_ERROR;
	}
	if($file) {
		if (!(@fwrite($file, $htaccess))) {
			//Unable to write to file
			$error |= HTACCESS_CREATION_ERROR;
		}
		fclose($file);
	}


	/**
	 *
	 * generate the config.inc.php file
	 */
	$config = "<?php
	include_once('includes/db/dbms.inc.php');
	include_once('includes/db/tables.inc.php');
	include_once('includes/cms/vars.inc.php');
	include_once('includes/cms/properties.inc.php');
	include_once('includes/types/types.inc.php');
	include_once('includes/string/string.inc.php');
	include_once('includes/lang/langs.inc.php');

	\$UILanguage = ".$language.";
	include_once('includes/lang/'.\$translationsFiles[\$UILanguage]);

	define('DB_CONNECTION_DBMS', ".$dbms.");
	define('DB_CONNECTION_HOST', '".$host.":".$port."');
	define('DB_CONNECTION_DB', '".$dbName."');
	define('DB_CONNECTION_USER', '".$dbUser."');
	define('DB_CONNECTION_PASS', '".$dbPassword."');

	define('ENABLE_LOGGING', $enableLogging);
	define('ENABLE_VERSIONING', $enableVersionning);
	define('ENABLE_SECURITY', $enableSecurity);
	define('ENABLE_PUBLICATION', $enablePublication);
	define('ENABLE_GALLERIES', 0);
	define('ENABLE_NEWSLETTER', 0);
	define('ENABLE_PAGES_CREATION', 0);
	define('ENABLE_ADMIN_AREA', 0);

	define('DEBUG_LEVEL', ".$debugLevel.");
	define('PUBLICATION_DEFAULT_VALUE', $defaultPublicationState);
	define('MAX_NUM_SAV_VERS', $versionsHistory);
	define('FORCE_ALIAS_IN_URL', true);
	
	// number of batch per hour
	define('BATCH_SPEED', '10');

	// maximum number of operations
	define('BATCH_SIZE', '10000');

	// maximum execution time (in seconds)
	define('BATCH_DURATION', '10');


	define('MAILING_LIST_FROM_MAIL', 'contact@domain.ext');
	define('MAILING_LIST_FROM_NAME', 'Organisation');

	define('ORG_NAME', 					'ORGANISATION NAME');
	define('ORG_MAIL', 					'contact@domain.ext');
	define('ORG_ABUSE', 				'contact@domain.ext');
	define('ORG_LOGO',					'mailing/small_banner.jpg');
	define('ORG_URL', 					'http://www.domain.ext/');
	define('ORG_MLM_ROOT_URL',	'http://www.domain.ext/mailing/');
	define('ORG_SIG', 					'Contact person');
	define('ORG_TEMPLATE_URL', 	ORG_MLM_ROOT_URL.'easy-mlm.tpl.php');
	define('ORG_FORM_URL',			ORG_MLM_ROOT_URL.'easy-mlm.form.php');

  ".'?'.">";

	$configFile = 'config.inc.php';
	if(!($file = @fopen($configFile, 'w'))) {
		//Unable to open file
		$error |= CONFIG_CREATION_ERROR;
	}
	if($file) {
		if (!(@fwrite($file, $config))) {
			//Unable to write to file
			$error |= CONFIG_CREATION_ERROR;
		}
		fclose($file);
	}
  // prevent access from other user than the creator (i.e. apache)
  chmod($configFile, 500);


	if(!$error) {
	}

	return $error;
}


/**
 *  
 *  display licence agreement
 *
 **/
function displayStep1($errCode=0) {
  $paneWidth  = 515;
  $paneHeight = 500;

  $manager = &egManager::getInstance();
  $main = new egContainer("main_ctn", 0, 0, 0, 0);
	$hiddenValuesContainer = new egContainer("ctn_edt_ctn_hidden_values", 0, 0, 1, 1);
  $main->addContainer($hiddenValuesContainer);
	$objStep = new egEdit("hidden_control_type_step", '2', 0, 0, 0, 0, "step");
	$hiddenValuesContainer->addObject($objStep);

  $previousTop = 40;

	$propertySheet = new egPropertySheet("pts_1", "Menu", 10, 10, $paneWidth, $paneHeight);

	$editContainer = new egContainer("ctn_edit", 5, 5, $paneWidth-5, $paneHeight-5);


  $propertySheet->addPage(new egPropertyPage("ptp_1", '<b>STEP 1 :</b>&nbsp;&nbsp;Terms and Conditions', $editContainer->getContainerName()));
  $propertySheet->addContainer($editContainer);


	if (!is_file('license.txt')) {
		die('license file is missing');
	}

	$eulaContent = preg_replace("/\\r\\n|\\n|\\r/", "<br />", htmlentities(file_get_contents('license.txt'), ENT_QUOTES, "UTF-8"));
	$edit1 = new egEdit("edt_1", $eulaContent, 30, 30, 400, 350, '');

	$checkBox1 = new egCheckBox("ckb_1", "I've read and agree to the Terms and Conditions", 30, 400, 300, null, "check1", 1, false);

  $editContainer->addObject($edit1);
  $editContainer->addObject($checkBox1);

	$nextButton = new egPressbutton("btn_1", 'Next >>', $paneWidth-105, $paneHeight+50, 120, null, "clickNextButton();");


  $main->addObject($propertySheet);
  $main->addObject($nextButton);
  $manager->addContainer($main);

  $scripts = new egScript();
  $line = "function clickNextButton() {
		if(checkBox_ckb_1.checked == 1) {
		 	document.forms[0].submit();
		}
		else {
			alert('You need to agree the easy-CMS terms and conditions');
		}
  }";
  $scripts->addLine($line);
  $manager->addScripts($scripts);

  print($manager->getHTML());
}

/**
 *  
 *  choose DB Type / Host
 *
 **/
function displayStep2($errCode=0) {
	if($errCode < 0) {
		$errCode = 0;
	}

	$errorString = '';

	if($errCode & DB_UNRESOLVABLE_HOST_ERROR) {
		$errorString .= "Unable to resolve host : check hostname<br />";
	}
	if($errCode & DB_UNABLE_TO_CONNECT_ERROR) {
		$errorString .= "Unable to connect to host : check the port number<br />";
	}
	if($errCode & DB_UNKNOWN_DBMS_ERROR) {
		$errorString .= "Unknow DBMS : choose one of the supported DMBS<br />";
	}

	global $DBMS_ARRAY;
  $paneWidth  = 515;
  $paneHeight = 500;

	$dbms = 'MYSQL';
	$host = 'localhost';
	$port = '3306';

	if(isset($_SESSION['dbms'])){
		$dbms = $_SESSION['dbms'];
	}

	if(isset($_SESSION['host'])) {
		$host = $_SESSION['host'];
	}

	if(isset($_SESSION['port'])) {
		$port = $_SESSION['port'];
	}


  $manager = &egManager::getInstance();
  $main = new egContainer("main_ctn", 0, 0, 0, 0);
	$hiddenValuesContainer = new egContainer("ctn_edt_ctn_hidden_values", 0, 0, 1, 1);
  $main->addContainer($hiddenValuesContainer);
	$objStep = new egEdit("hidden_control_type_step", '2', 0, 0, 0, 0, "step");
	$hiddenValuesContainer->addObject($objStep);

  $errorMessage = new egStatic("st_errors", '<font color="red">'.$errorString.'</font>', 30, 30, 350, 0, true);

	if(strlen($errorString) > 0) {
  	$previousTop = 100;
	}
	else {
  	$previousTop = 50;
	}


	$propertySheet = new egPropertySheet("pts_1", "Menu", 10, 10, $paneWidth, $paneHeight);
	$editContainer = new egContainer("ctn_edit", 5, 5, $paneWidth-5, $paneHeight-5);

  $propertySheet->addPage(new egPropertyPage("ptp_1", '<b>STEP 2 :</b>&nbsp;&nbsp;Database Management System', $editContainer->getContainerName()));
  $propertySheet->addContainer($editContainer);

  $dbmsText = new egStatic("st_value_dbms", 'DBMS type :', 30, $previousTop, 140, 0, true);
	$dbmsValue = new egDropDownListBox("obj_item_dbms", 140, $previousTop, 100, null, 'dbms');

	foreach($DBMS_ARRAY as $key => $value) {
  	$dbmsValue->addListItem(new egListItem("lti_dbms_".$key, $key, null, $value));
		if($dbms == $value) {
  		$dbmsValue->setSelectedItemByValue($value);
		}
	}
  $previousTop += 18;
  $dbmsComment = new egStatic("st_dbms_comment", '<i>(Choose among the currently supported DBMS)</i>', 140, $previousTop, 300, 0);
  $previousTop += 40;

  $staticHost = new egStatic("st_db_host", 'Host :', 30, $previousTop, 140, 0, true);
	$editHost = new egEdit("edit_db_host", $host, 140, $previousTop, 140, 18, 'host');
  $previousTop += 16;
	$staticHostComment = new egStatic("st_db_host_comment", '<i>(DBMS hostname or IP address)</i>', 140, $previousTop, 300, 0);
  $previousTop += 40;

  $staticPort = new egStatic("st_db_port", 'Port :', 30, $previousTop, 140, 0, true);
	$editPort = new egEdit("edit_db_port", $port, 140, $previousTop, 40, 18, 'port');
  $previousTop += 16;
	$staticPortComment = new egStatic("st_db_port_comment", '<i>(The port on which the DBMS server is listening)</i>', 140, $previousTop, 300, 0);
  $previousTop += 40;

 	$actionText = new egStatic("st_value_action", 'Database :', 30, $previousTop, 140, 0, true);
	$actionValue = new egDropDownListBox("obj_item_action", 140, $previousTop, 160, null, 'action');
 	$actionValue->addListItem(new egListItem("lti_action_1", 'create a new database', null, ASK_CREATE_NEW_DB));
 	$actionValue->addListItem(new egListItem("lti_action_2", 'use an existing database', null, ASK_USE_EXISTING_DB));
	$actionValue->setSelectedItemByValue(ASK_CREATE_NEW_DB);
  $previousTop += 18;
	$staticActionComment = new egStatic("st_db_action_comment", '<i>(Fresh install or update an existing installation)</i>', 140, $previousTop, 300, 0);
  $previousTop += 40;

	$editContainer->addObject($errorMessage);

  $editContainer->addObject($dbmsText);
  $editContainer->addObject($dbmsValue);
  $editContainer->addObject($dbmsComment);

  $editContainer->addObject($staticHost);
  $editContainer->addObject($editHost);
  $editContainer->addObject($staticHostComment);

  $editContainer->addObject($staticPort);
  $editContainer->addObject($editPort);
  $editContainer->addObject($staticPortComment);

  $editContainer->addObject($actionText);
  $editContainer->addObject($actionValue);
  $editContainer->addObject($staticActionComment);

	$previousButton = new egPressbutton("btn_1", '<< Previous&nbsp;', $paneWidth-235, $paneHeight+50, 120, null, "clickPreviousButton();");
	$nextButton = new egPressbutton("btn_2", 'Next >>', $paneWidth-105, $paneHeight+50, 120, null, "clickNextButton();");

  $main->addObject($propertySheet);
  $main->addObject($previousButton);
  $main->addObject($nextButton);
  $manager->addContainer($main);

  $scripts = new egScript();
  $line = "function clickNextButton() {
  	document.forms[0].submit();
  }
	function clickPreviousButton() {
  	window.location = 'install.php?step=1';
  }
";
  $scripts->addLine($line);
  $manager->addScripts($scripts);

  print($manager->getHTML());
}

/**
 *  
 *  choose dbms user / password
 *
 **/
function displayStep3($errCode=0) {
	if($errCode < 0) {
		$errCode = 0;
	}
	$errorString = '';

	if($errCode & DB_AUTHENTICATION_ERROR) {
		$errorString .= "Unable to authenticate to the SQL server : check admin login and password<br />";
	}

	if($errCode & DB_ALREADY_EXISTS_ERROR) {
		$errorString .= "Unable to create new database : duplicate database name<br />";
	}

	if($errCode & DB_USER_ALREADY_EXISTS_ERROR) {
		$errorString .= "Unable to create new DB user : duplicate username<br />";
	}

	if($errCode & DB_CREATION_ERROR) {
		$errorString .= "Unable to create new user or database : check username and password<br />";
	}

	global $DBMS_ARRAY;
	$paneWidth  = 515;
	$paneHeight = 500;

	if(isset($_SESSION['admin_user'])) {
		$adminUser = $_SESSION['admin_user'];
	}
	else {
		$adminUser = 'root';
	}

	if(isset($_SESSION['admin_password'])) {
		$adminPassword = $_SESSION['admin_password'];
	}
	else {
		$adminPassword = '';
	}

	if(isset($_SESSION['db_user'])) {
		$dbUser = $_SESSION['db_user'];
	}
	else {
		$dbUser = '';
	}

	if(isset($_SESSION['db_password'])) {
		$dbPassword = $_SESSION['db_password'];
	}
	else {
		$dbPassword = '';
	}

	if(isset($_SESSION['db_name'])) {
		$dbName = $_SESSION['db_name'];
	}
	else {
		$dbName = 'easycms';
	}

	$manager = &egManager::getInstance();
	$main = new egContainer("main_ctn", 0, 0, 0, 0);
	$hiddenValuesContainer = new egContainer("ctn_edt_ctn_hidden_values", 0, 0, 1, 1);
	$main->addContainer($hiddenValuesContainer);
	$objStep = new egEdit("hidden_control_type_step", '3', 0, 0, 0, 0, "step");
	$hiddenValuesContainer->addObject($objStep);


	$errorMessage = new egStatic("st_errors", '<font color="red">'.$errorString.'</font>', 30, 30, 450, 0, true);

	$previousTop = 50;
	if(strlen($errorString) > 0) {
		$previousTop = 100;
	}

	$propertySheet = new egPropertySheet("pts_1", "Menu", 10, 10, $paneWidth, $paneHeight);

	$editContainer = new egContainer("ctn_edit", 5, 5, $paneWidth-5, $paneHeight-5);

	$propertySheet->addPage(new egPropertyPage("ptp_1", '<b>STEP 3 :</b>&nbsp;&nbsp;Database creation', $editContainer->getContainerName()));
	$propertySheet->addContainer($editContainer);


	$staticDBMSUser = new egStatic("st_dbms_user", 'DBMS admin :', 30, $previousTop, 150, 0, true);
	$editDBMSUser = new egEdit("edit_dbms_user", $adminUser, 180, $previousTop, 150, 18, 'admin_user');
	$previousTop += 16;
	$staticDBMSUserComment = new egStatic("st_dbms_user_comment", '<i>(DBMS administrator - require database creation privileges)</i>', 180, $previousTop, 300, 0);
	$previousTop += 30;

	$staticDBMSPass = new egStatic("st_dbms_pass", 'DBMS admin password :', 30, $previousTop, 150, 0, true);
	$editDBMSPass = new egEdit("edit_dbms_pass", $adminPassword, 180, $previousTop, 150, 18, 'admin_password');
	$previousTop += 16;
	$staticDBMSPassComment = new egStatic("st_dbms_pass_comment", '<i>(Password of the DBMS administrator)</i>', 180, $previousTop, 300, 0);
	$previousTop += 55;

	$staticDBName = new egStatic("st_db_name", 'DB name :', 30, $previousTop, 150, 0, true);
	$editDBName = new egEdit("edit_db_name", $dbName, 180, $previousTop, 150, 18, 'db_name');
	$previousTop += 16;
	$staticDBNameComment = new egStatic("st_db_name_comment", '<i>(Choose a name for the easy-CMS database)</i>', 180, $previousTop, 300, 0);
	$previousTop += 55;

	$staticDBUser = new egStatic("st_db_user", 'DB user :', 30, $previousTop, 150, 0, true);
	$editDBUser = new egEdit("edit_db_user", $dbUser, 180, $previousTop, 150, 18, 'db_user');
	$previousTop += 16;
	$staticDBUserComment = new egStatic("st_db_user_comment", '<i>(Choose a login for the easy-CMS DB user)</i>', 180, $previousTop, 300, 0);
	$previousTop += 30;

	$staticDBPass = new egStatic("st_db_pass", 'DB password :', 30, $previousTop, 150, 0, true);
	$editDBPass = new egEdit("edit_db_pass", $dbPassword, 180, $previousTop, 150, 18, 'db_password', true);
	$previousTop += 16;
	$staticDBPassComment = new egStatic("st_db_pass_comment", '<i>(Choose a password for the easy-CMS DB user)</i>', 180, $previousTop, 300, 0);
	$previousTop += 30;

	$staticDBConfirm = new egStatic("st_db_confirm", 'Password confirmation :', 30, $previousTop, 150, 0, true);
	$editDBConfirm = new egEdit("edit_db_confirm",$dbPassword, 180, $previousTop, 150, 18, 'db_confirm', true);
	$previousTop += 16;
	$staticDBConfirmComment = new egStatic("st_db_confirm_comment", '<i>(Confirm the password for the easy-CMS DB user)</i>', 180, $previousTop, 300, 0);
	$previousTop += 55;



	$editContainer->addObject($errorMessage);

	$editContainer->addObject($staticDBMSUser);
	$editContainer->addObject($editDBMSUser);
	$editContainer->addObject($staticDBMSUserComment);

	$editContainer->addObject($staticDBMSPass);
	$editContainer->addObject($editDBMSPass);
	$editContainer->addObject($staticDBMSPassComment);

	$editContainer->addObject($staticDBName);
	$editContainer->addObject($editDBName);
	$editContainer->addObject($staticDBNameComment);

	$editContainer->addObject($staticDBUser);
	$editContainer->addObject($editDBUser);
	$editContainer->addObject($staticDBUserComment);

	$editContainer->addObject($staticDBPass);
	$editContainer->addObject($editDBPass);
	$editContainer->addObject($staticDBPassComment);

	$editContainer->addObject($staticDBConfirm);
	$editContainer->addObject($editDBConfirm);
	$editContainer->addObject($staticDBConfirmComment);


	$previousButton = new egPressbutton("btn_1", '<< Previous&nbsp;', $paneWidth-235, $paneHeight+50, 120, null, "clickPreviousButton();");
	$nextButton = new egPressbutton("btn_2", 'Next >>', $paneWidth-105, $paneHeight+50, 120, null, "clickNextButton();");

	$main->addObject($propertySheet);
	$main->addObject($previousButton);
	$main->addObject($nextButton);
	$manager->addContainer($main);

	$scripts = new egScript();
	$line = "function clickNextButton() {
			if(validationFunction()) {
				document.forms[0].submit();
			}
		}
		function validationFunction() {
		  var inputAdmin		= document.getElementById('edit_dbms_user_value').value;
		  var inputDB				= document.getElementById('edit_db_name_value').value;
		  var inputUser			= document.getElementById('edit_db_user_value').value;
		  var inputPassword = document.getElementById('edit_db_pass_value').value;
		  var inputConfirm  = document.getElementById('edit_db_confirm_value').value;

			if(inputAdmin == '') {
				window.alert('Please enter a login for the DBMS admin.');
				return false;
			}

			if(inputUser == '') {
				window.alert('Please choose a login for the DB user.');
				return false;
			}

			if(inputDB == '') {
				window.alert('Please choose a name for the easy-CMS database.');
				return false;
			}

		  if(inputPassword != '') {
			if(inputPassword != inputConfirm) {
			  window.alert('The confirmation password does not match the original password.');
			  return false;
			}
		  }
			else {
				window.alert('Please enter a password for the DB user.');
				return false;
			}

			return true;
		}
		function clickPreviousButton() {
			window.location = 'install.php?step=2';
		}
	";

  $scripts->addLine($line);
  $manager->addScripts($scripts);

  print($manager->getHTML());
}

/**
 *
 *  do : nothing
 *  display : choose DB name, DB user and DB password
 *
 **/
function displayStep4($errCode=0) {
	if($errCode < 0) {
		$errCode = 0;
	}
	$errorString = '';

	if($errCode & DB_AUTHENTICATION_ERROR) {
		$errorString .= "Unable to authenticate to the SQL server : check username and password<br />";
	}

	if($errCode & DB_ACCESS_DENIED_ERROR) {
		$errorString .= "User does not have permissions to access this database : check your parameters<br />";
	}

	if($errCode & DBMS_ERROR) {
		$errorString .= "one or more DBMS function(s) returned an error : please report this issue to the easy-CMS support<br />";
	}


  $paneWidth  = 515;
  $paneHeight = 500;


	if(isset($_SESSION['db_user'])) {
		$dbUser = $_SESSION['db_user'];
	}
	else {
		$dbUser = '';
	}

	if(isset($_SESSION['db_password'])) {
		$dbPassword = $_SESSION['db_password'];
	}
	else {
		$dbPassword = '';
	}

	if(isset($_SESSION['db_name'])) {
		$dbName = $_SESSION['db_name'];
	}
	else {
		$dbName = 'easycms';
	}

  $manager = &egManager::getInstance();
  $main = new egContainer("main_ctn", 0, 0, 0, 0);
	$hiddenValuesContainer = new egContainer("ctn_edt_ctn_hidden_values", 0, 0, 1, 1);
  $main->addContainer($hiddenValuesContainer);
	$objStep = new egEdit("hidden_control_type_step", '4', 0, 0, 0, 0, "step");
	$hiddenValuesContainer->addObject($objStep);


  $errorMessage = new egStatic("st_errors", '<font color="red">'.$errorString.'</font>', 30, 30, 450, 0, true);

	if(strlen($errorString) > 0) {
  	$previousTop = 100;
	}
	else {
  	$previousTop = 50;
	}

	$propertySheet = new egPropertySheet("pts_1", "Menu", 10, 10, $paneWidth, $paneHeight);

	$editContainer = new egContainer("ctn_edit", 5, 5, $paneWidth-5, $paneHeight-5);


  $propertySheet->addPage(new egPropertyPage("ptp_1", '<b>STEP 3 :</b>&nbsp;&nbsp;Database user informations', $editContainer->getContainerName()));
  $propertySheet->addContainer($editContainer);


  $staticDBName = new egStatic("st_db_name", 'DB name :', 30, $previousTop, 150, 0, true);
	$editDBName = new egEdit("edit_db_name", $dbName, 180, $previousTop, 150, 18, 'db_name');
  $previousTop += 16;
  $staticDBNameComment = new egStatic("st_db_name_comment", '<i>(Enter the name of the easy-CMS database)</i>', 180, $previousTop, 300, 0);
  $previousTop += 55;

  $staticDBUser = new egStatic("st_db_user", 'DB user :', 30, $previousTop, 150, 0, true);
	$editDBUser = new egEdit("edit_db_user", $dbUser, 180, $previousTop, 150, 18, 'db_user');
  $previousTop += 16;
  $staticDBUserComment = new egStatic("st_db_user_comment", '<i>(Enter the login of the easy-CMS DB user)</i>', 180, $previousTop, 300, 0);
  $previousTop += 30;

  $staticDBPass = new egStatic("st_db_pass", 'DB password :', 30, $previousTop, 150, 0, true);
	$editDBPass = new egEdit("edit_db_pass", $dbPassword, 180, $previousTop, 150, 18, 'db_password', true);
  $previousTop += 16;
  $staticDBPassComment = new egStatic("st_db_pass_comment", '<i>(Enter the password of the easy-CMS DB user)</i>', 180, $previousTop, 300, 0);
  $previousTop += 30;

  $staticDBConfirm = new egStatic("st_db_confirm", 'Password confirmation :', 30, $previousTop, 150, 0, true);
	$editDBConfirm = new egEdit("edit_db_confirm", $dbPassword, 180, $previousTop, 150, 18, 'db_confirm', true);
  $previousTop += 16;
  $staticDBConfirmComment = new egStatic("st_db_confirm_comment", '<i>(Confirm the password of the easy-CMS DB user)</i>', 180, $previousTop, 300, 0);
  $previousTop += 55;


	$editContainer->addObject($errorMessage);

	$editContainer->addObject($staticDBName);
  $editContainer->addObject($editDBName);
  $editContainer->addObject($staticDBNameComment);

	$editContainer->addObject($staticDBUser);
  $editContainer->addObject($editDBUser);
  $editContainer->addObject($staticDBUserComment);

	$editContainer->addObject($staticDBPass);
  $editContainer->addObject($editDBPass);
  $editContainer->addObject($staticDBPassComment);

	$editContainer->addObject($staticDBConfirm);
  $editContainer->addObject($editDBConfirm);
  $editContainer->addObject($staticDBConfirmComment);

	$previousButton = new egPressbutton("btn_1", '<< Previous&nbsp;', $paneWidth-235, $paneHeight+50, 120, null, "clickPreviousButton();");
	$nextButton = new egPressbutton("btn_2", 'Next >>', $paneWidth-105, $paneHeight+50, 120, null, "clickNextButton();");

  $main->addObject($propertySheet);
  $main->addObject($previousButton);
  $main->addObject($nextButton);
  $manager->addContainer($main);

  $scripts = new egScript();

	if($_SESSION['action'] == ASK_CREATE_NEW_DB) {
		$step = 3;
	}
	else {
		$step = 2;
	}

  $line = "function clickNextButton() {
    if(validationFunction()) {
		  document.forms[0].submit();
    }
	}
	function clickPreviousButton() {
  	window.location = 'install.php?step=$step';
	}
	function validationFunction() {
	  var inputPassword = document.getElementById('edit_db_pass_value').value;
	  var inputConfirm  = document.getElementById('edit_db_confirm_value').value;

	  if(inputPassword != '') {
	    if(inputPassword != inputConfirm) {
	      window.alert('The confirmation password does not match the original password.');
	      return false;
	    }
	  }
		return true;
	}";
  $scripts->addLine($line);
  $manager->addScripts($scripts);

  print($manager->getHTML());
}

/**
 *
 *  
 *	display DB creation status, warning if already exists, multiple choice for action (db already exists / sig found / unrecognized version)
 *
 **/
function displayStep5($errCode=0) {
	if($errCode < 0) {
		$errCode = 0;
	}
	$errorString = '';

	if($errCode & SQL_SCHEMA_CORRUPT_ERROR) {
		$errorString .= "SQL schema corrupted : check the sql syntax<br />";
	}

	if($errCode & DB_NOT_FOUND) {
		$errorString .= "Unable to use or update an existing database : no database found<br />";
	}

	if($errCode & DB_NOT_UPDATABLE) {
		$errorString .= "Unable to update existing database : no signature found or unsupported database<br />";
	}

	if($errCode & DBMS_ERROR) {
		$errorString .= "A DBMS function returned an error : please report this issue to the easy-CMS support<br />";
	}

	if(isset($_SESSION['cms_admin_login'])) {
		$adminLogin = $_SESSION['cms_admin_login'];
	}
	else {
		$adminLogin = '';
	}

	if(isset($_SESSION['cms_admin_password'])) {
		$adminPassword = $_SESSION['cms_admin_password'];
	}
	else {
		$adminPassword = '';
	}


	$paneWidth  = 515;
	$paneHeight = 500;


	$manager = &egManager::getInstance();
	$main = new egContainer("main_ctn", 0, 0, 0, 0);
	$hiddenValuesContainer = new egContainer("ctn_edt_ctn_hidden_values", 0, 0, 1, 1);
	$main->addContainer($hiddenValuesContainer);

	$objStep = new egEdit("hidden_control_type_step", '5', 0, 0, 0, 0, "step");
	$hiddenValuesContainer->addObject($objStep);

	$propertySheet = new egPropertySheet("pts_1", "Menu", 10, 10, $paneWidth, $paneHeight);
	$editContainer = new egContainer("ctn_edit", 5, 5, $paneWidth-5, $paneHeight-5);

	if(strlen($errorString) > 0) {
		$errorMessage = new egStatic("st_errors", '<font color="red">'.$errorString.'</font>', 30, 30, 450, 0, true);
		$previousTop = 100;

		$actionText = new egStatic("st_value_action", 'Action :', 30, $previousTop, 140, 0, true);
		$actionValue = new egDropDownListBox("obj_item_action", 140, $previousTop, 160, null, 'action');
		$actionValue->addListItem(new egListItem("lti_action_1", 'overwrite database', null, ASK_CREATE_NEW_DB));
		$actionValue->addListItem(new egListItem("lti_action_2", 'update database', null, ASK_USE_EXISTING_DB));
		$actionValue->setSelectedItemByValue(ASK_USE_EXISTING_DB);
		$previousTop += 18;
		$staticActionComment = new egStatic("st_db_action_comment", '<i>(Choose an action : update or overwrite existing database)</i>', 140, $previousTop, 300, 0);
		$previousTop += 40;

		$editContainer->addObject($actionText);
		$editContainer->addObject($actionValue);
		$editContainer->addObject($staticActionComment);
	}
	else {
  	$previousTop = 50;
	}

  // choose a login and a password for the easy-CMS admin user
  $staticUser = new egStatic("st_user", 'CMS admin user :', 30, $previousTop, 150, 0, true);
	$editUser = new egEdit("edit_user", $adminLogin, 180, $previousTop, 150, 18, 'cms_admin_login');
  $previousTop += 16;
  $staticUserComment = new egStatic("st_user_comment", '<i>(Choose a login for the easy-CMS admin user)</i>', 180, $previousTop, 300, 0);
  $previousTop += 30;

  $staticPass = new egStatic("st_pass", 'CMS admin password :', 30, $previousTop, 150, 0, true);
	$editPass = new egEdit("edit_pass", $adminPassword, 180, $previousTop, 150, 18, 'cms_admin_password', true);
  $previousTop += 16;
  $staticPassComment = new egStatic("st_pass_comment", '<i>(Choose a password for the easy-CMS admin user)</i>', 180, $previousTop, 300, 0);
  $previousTop += 30;

  $staticConfirm = new egStatic("st_confirm", 'Password confirmation :', 30, $previousTop, 150, 0, true);
	$editConfirm = new egEdit("edit_confirm", $adminPassword, 180, $previousTop, 150, 18, 'cms_admin_confirm', true);
  $previousTop += 16;
  $staticConfirmComment = new egStatic("st_confirm_comment", '<i>(Confirm the password for the easy-CMS admin user)</i>', 180, $previousTop, 300, 0);
  $previousTop += 55;

  $editContainer->addObject($staticUser);
  $editContainer->addObject($editUser);
  $editContainer->addObject($staticUserComment);

  $editContainer->addObject($staticPass);
  $editContainer->addObject($editPass);
  $editContainer->addObject($staticPassComment);

  $editContainer->addObject($staticConfirm);
  $editContainer->addObject($editConfirm);
  $editContainer->addObject($staticConfirmComment);


	$previousButton = new egPressbutton("btn_1", '<< Previous&nbsp;', $paneWidth-235, $paneHeight+50, 120, null, "clickPreviousButton();");
	$nextButton = new egPressbutton("btn_2", 'Next >>', $paneWidth-105, $paneHeight+50, 120, null, "clickNextButton();");

  $propertySheet->addPage(new egPropertyPage("ptp_1", '<b>STEP 4 :</b>&nbsp;&nbsp;populating easy-CMS database', $editContainer->getContainerName()));
  $propertySheet->addContainer($editContainer);

	$editContainer->addObject($errorMessage);

  $main->addObject($propertySheet);
  $main->addObject($previousButton);
  $main->addObject($nextButton);
  $manager->addContainer($main);

  $scripts = new egScript();

	if($_SESSION['action'] == ASK_CREATE_NEW_DB) {
		$step = 3;
	}
	else {
		$step = 4;
	}

  $line = "function clickNextButton() {
    if(validationFunction()) {
      document.forms[0].submit();
    }
	}
  function clickPreviousButton() {
  	window.location = 'install.php?step=$step';
	}
	function validationFunction() {
	  var inputLogin = document.getElementById('edit_user_value').value;
	  var inputPassword = document.getElementById('edit_pass_value').value;
	  var inputConfirm  = document.getElementById('edit_confirm_value').value;

    if(inputLogin.length <= 2){
      window.alert('Admin login must be at least 3 characters long.');
      return false;
    }
	  if(inputPassword != '') {
	    if(inputPassword != inputConfirm) {
	      window.alert('The confirmation password does not match the original password.');
	      return false;
	    }
	  }
    else {
      window.alert('Please choose a password for the admin user.');
      return false;
    }
		return true;
	}";
  $scripts->addLine($line);
  $manager->addScripts($scripts);

  print($manager->getHTML());
}

/**
 *  
 *  display miscellaneous options
 *
 **/
function displayStep6($errCode=0) {
	global $LANGS_ARRAY;

	if($errCode < 0) {
		$errCode = 0;
	}
	$errorString = '';

	if($errCode & HTACCESS_CREATION_ERROR) {
		$errorString .= "Unable to create .htaccess file : check FS permissions on the easy-CMS folder<br />";
	}

	if($errCode & REPOSITORIES_CREATION_ERROR) {
		$errorString .= "Unable to create repositories : check FS permissions on the easy-CMS folder<br />";
	}

	if($errCode & CONFIG_CREATION_ERROR) {
		$errorString .= "Unable to create config file : check FS permissions on the easy-CMS folder<br />";
	}


  $paneWidth  = 515;
  $paneHeight = 500;


	if(isset($_SESSION['db_user'])) {
		$dbUser = $_SESSION['db_user'];
	}
	else {
		$dbUser = '';
	}


  $manager = &egManager::getInstance();
  $main = new egContainer("main_ctn", 0, 0, 0, 0);
	$hiddenValuesContainer = new egContainer("ctn_edt_ctn_hidden_values", 0, 0, 1, 1);
  $main->addContainer($hiddenValuesContainer);
	$objStep = new egEdit("hidden_control_type_step", '6', 0, 0, 0, 0, "step");
	$hiddenValuesContainer->addObject($objStep);


  $errorMessage = new egStatic("st_errors", '<font color="red">'.$errorString.'</font>', 30, 30, 450, 0, true);

	if(strlen($errorString) > 0) {
  	$previousTop = 80;
	}
	else {
  	$previousTop = 30;
	}

	$propertySheet = new egPropertySheet("pts_1", "Menu", 10, 10, $paneWidth, $paneHeight);

	$editContainer = new egContainer("ctn_edit", 5, 5, $paneWidth-5, $paneHeight-5);


  $propertySheet->addPage(new egPropertyPage("ptp_1", '<b>STEP 5 :</b>&nbsp;&nbsp;Miscellaneous options', $editContainer->getContainerName()));
  $propertySheet->addContainer($editContainer);


  $langText = new egStatic("st_value_language", 'User interface language :', 30, $previousTop, 150, 0, true);
	$langValue = new egDropDownListBox("obj_item_language", 180, $previousTop, 100, null, 'language');

	foreach($LANGS_ARRAY as $lang => $value) {
  	$langValue->addListItem(new egListItem("lti_language_".$value, $lang, null, $value));
	}
  $langValue->setSelectedItemByIndex(0);
  $previousTop += 35;

  $staticSecurity	= new egStatic("st_security", 'Security :', 30, $previousTop, 150, 0, true);
	$cbSecurity			= new egCheckBox("cb_sec", "enable rights management", 180, $previousTop, 150, null, "enable_security", 1, false);
	$previousTop += 16;
  $staticSecurityComment = new egStatic("st_security_comment", '<i>(Check this box to be able to manage users rights on the items)</i>', 180, $previousTop, 320, 0);
	$previousTop += 40;

  $staticPublication	= new egStatic("st_publication", 'Publication :', 30, $previousTop, 150, 0, true);
	$cbPublication			= new egCheckBox("cb_pub", "enable publication", 180, $previousTop, 150, null, "enable_publication", 1, false);
	$previousTop += 16;
  $staticPublicationComment = new egStatic("st_publication_comment", '<i>(Check this box to be able to manage the publication of items)</i>', 180, $previousTop, 320, 0);
	$previousTop += 35;

  $staticPubState = new egStatic("st_pub_state", 'default status :', 50, $previousTop, 150, 0);
	$rbUnpublished = new egRadiobutton("rb_pub_1", "unpublished", 180, $previousTop-10, 150, null, "publication_state", 0);
	$rbPublished = new egRadiobutton("rb_pub_2", "published", 180, $previousTop+10, 150, null, "publication_state", 1, true);
	$previousTop += 24;
  $staticPubStateComment = new egStatic("st_pub_state_comment", '<i>(New items will have the chosen publication state)</i>', 180, $previousTop, 300, 0);
	$previousTop += 40;

  $staticVersions	= new egStatic("st_versions", 'Versionning :', 30, $previousTop, 150, 0, true);
	$cbVersions			= new egCheckBox("cb_ver", "enable versionning", 180, $previousTop, 150, null, "enable_versionning", 1, false);
	$previousTop += 16;
  $staticVersionsComment = new egStatic("st_versions_comment", '<i>(Check this box to be able to manage contents versions)</i>', 180, $previousTop, 320, 0);
	$previousTop += 35;

  $staticVersionsHistory = new egStatic("st_ver_hist", 'history :', 50, $previousTop, 150, 0);
	$editVersionsHistory = new egEdit("edit_ver_hist", '5', 180, $previousTop, 30, 18, "versions_history");
  $previousTop += 16;
  $staticVersionsHistoryComment = new egStatic("st_ver_hist_comment", '<i>(Choose the number of saved versions for each item - max. 15)</i>', 180, $previousTop, 320, 0);
  $previousTop += 40;


  $staticLogging	= new egStatic("st_logging", 'Logs :', 30, $previousTop, 150, 0, true);
	$cbLogging			= new egCheckBox("cb_log", "enable logs", 180, $previousTop, 150, null, "enable_logging", 1, false);
	$previousTop += 16;
  $staticLoggingComment = new egStatic("st_logging_comment", '<i>(Check this box to be able to review the CMS logs)</i>', 180, $previousTop, 320, 0);
	$previousTop += 40;

  $staticDebugLevel = new egStatic("st_deb_lev", 'verbose level :', 50, $previousTop, 150, 0);
	$editDebugLevel = new egEdit("edit_deb_lev", '3', 180, $previousTop, 30, 18, "debug_level");
  $previousTop += 16;
  $staticDebugLevelComment = new egStatic("st_deb_lev_comment", '<i>(Choose a verbose level from 0 to 10 - level 10 : debugging only)</i>', 180, $previousTop, 320, 0);
  $previousTop += 55;


	$editContainer->addObject($errorMessage);


	$editContainer->addObject($langText);
  $editContainer->addObject($langValue);

	$editContainer->addObject($staticSecurity);
  $editContainer->addObject($cbSecurity);
  $editContainer->addObject($staticSecurityComment);

	$editContainer->addObject($staticPublication);
  $editContainer->addObject($cbPublication);
  $editContainer->addObject($staticPublicationComment);

	$editContainer->addObject($staticPubState);
  $editContainer->addObject($rbUnpublished);
  $editContainer->addObject($rbPublished);
  $editContainer->addObject($staticPubStateComment);

	$editContainer->addObject($staticVersions);
  $editContainer->addObject($cbVersions);
  $editContainer->addObject($staticVersionsComment);

	$editContainer->addObject($staticVersionsHistory);
  $editContainer->addObject($editVersionsHistory);
  $editContainer->addObject($staticVersionsHistoryComment);

	$editContainer->addObject($staticLogging);
  $editContainer->addObject($cbLogging);
  $editContainer->addObject($staticLoggingComment);

	$editContainer->addObject($staticDebugLevel);
  $editContainer->addObject($editDebugLevel);
  $editContainer->addObject($staticDebugLevelComment);



	$previousButton = new egPressbutton("btn_1", '<< Previous&nbsp;', $paneWidth-235, $paneHeight+50, 120, null, "clickPreviousButton();");
	$nextButton = new egPressbutton("btn_2", 'Next >>', $paneWidth-105, $paneHeight+50, 120, null, "clickNextButton();");

  $main->addObject($propertySheet);
  $main->addObject($previousButton);
  $main->addObject($nextButton);
  $manager->addContainer($main);

  $scripts = new egScript();

  $line = "function clickNextButton() {
		document.forms[0].submit();
	}
	function clickPreviousButton() {
  	window.location = 'install.php?step=5';
	}";
  $scripts->addLine($line);
  $manager->addScripts($scripts);

  print($manager->getHTML());
}

/**
 *  
 *  display confirmation message - everything should be OK at this level
 *
 **/
function displayStep7($errCode=0) {
  $paneWidth  = 515;
  $paneHeight = 500;

	if(isset($_SESSION['db_name'])) {
		$dbName = $_SESSION['db_name'];
	}

  $manager = &egManager::getInstance();
  $main = new egContainer("main_ctn", 0, 0, 0, 0);

  $previousTop = 40;

	$propertySheet = new egPropertySheet("pts_1", "Menu", 10, 10, $paneWidth, $paneHeight);

	$editContainer = new egContainer("ctn_edit", 5, 5, $paneWidth-5, $paneHeight-5);


  $propertySheet->addPage(new egPropertyPage("ptp_1", '<b>STEP 6 :</b>&nbsp;&nbsp;Setup complete', $editContainer->getContainerName()));
  $propertySheet->addContainer($editContainer);


  $dbText = new egStatic("st_value_db", "OK - Database '".$dbName."' successfully created", 30, $previousTop, 350, 0);
  $previousTop += 25;
  $sqlText = new egStatic("st_value_sql", "OK - easy-CMS tables successfully inserted/updated", 30, $previousTop, 350, 0);
  $previousTop += 25;
  $repositoryText = new egStatic("st_value_repo", "OK - Repository folders successfully created/updated", 30, $previousTop, 350, 0);
  $previousTop += 25;
  $configText = new egStatic("st_value_config", "OK - Configuration file successfully created", 30, $previousTop, 350, 0);

  $previousTop += 55;
  $commentText = new egStatic("st_value_comment", "You are now ready to use easy-CMS, click on the 'Finish' button below to display the home page of your new website.", 30, $previousTop, 350, 0);

  $editContainer->addObject($dbText);
  $editContainer->addObject($sqlText);
  $editContainer->addObject($configText);
	$editContainer->addObject($repositoryText);
  $editContainer->addObject($commentText);

	$nextButton = new egPressbutton("btn_2", 'Finish', $paneWidth-105, $paneHeight+50, 120, null, "clickNextButton();");

  $main->addObject($propertySheet);
  $main->addObject($nextButton);
  $manager->addContainer($main);

  $scripts = new egScript();
  $line = "function clickNextButton() {
  	window.location = 'index.php';
  }";
  $scripts->addLine($line);
  $manager->addScripts($scripts);

  print($manager->getHTML());
}
?>