<?php

/************************************************************************/
/* Eleonline                                                            */
/* ============================================                         */
/*  Installer was based on Joomla Installer                             */
/************************************************************************/

// Set flag that this is a parent file
define( "_VALID_MOS", 1 );

// Include common.php
require_once( 'common.php' );
require_once( './includes/database.php' );

$DBhostname = mosGetParam( $_POST, 'DBhostname', '' );
$DBuserName = mosGetParam( $_POST, 'DBuserName', '' );
$DBpassword = mosGetParam( $_POST, 'DBpassword', '' );
$DBname  	= mosGetParam( $_POST, 'DBname', '' );
$DBPrefix  	= mosGetParam( $_POST, 'DBPrefix', 'soraldo' );
$DBcreated	= intval( mosGetParam( $_POST, 'DBcreated', 0 ) );
$BUPrefix = 'old_';
$configArray['sitename'] = trim( mosGetParam( $_POST, 'sitename', 'Elezioni On Line' ) );
$configArray['nomecomune'] = trim( mosGetParam( $_POST, 'nomecomune', '' ) );
$configArray['istat'] = trim( mosGetParam( $_POST, 'istat', '' ) );
$Capoluogo = mosGetParam( $_POST, 'Capoluogo', '' );
$Lingua = mosGetParam( $_POST, 'Lingua', '' );
$Multicomune = mosGetParam( $_POST, 'Multicomune', '' );
$Replica = mosGetParam( $_POST, 'Replica', '' );
//tema
$tema = mosGetParam( $_POST, 'tema', '' );
$sceltatema = mosGetParam( $_POST, 'sceltatema', '' );
$blocco = mosGetParam( $_POST, 'blocco', '' );
$flash = mosGetParam( $_POST, 'flash', '' );
// d'hondt
$Hondt = mosGetParam( $_POST, 'Hondt', '' );
$Limite = mosGetParam( $_POST, 'Limite', '' );
$Consin = mosGetParam( $_POST, 'Consin', '' );
$infpremio = mosGetParam( $_POST, 'infpremio', '67' );
$supsbarramento = mosGetParam( $_POST, 'supsbarramento', '3' );
$suppremio = mosGetParam( $_POST, 'suppremio', '60' );
$supminpremio = mosGetParam( $_POST, 'supminpremio', '40' );
$database = null;
$themelist = mosGetParam( $_POST, 'themelist', '' );

$errors = array();
if (!$DBcreated){
	if (!$DBhostname || !$DBuserName || !$DBname) {
		db_err ("stepBack3","The database details provided are incorrect and/or empty.");
	}

	
	if($DBPrefix == '') {
		db_err ('stepBack','Non avete indicato il prefisso tabelle database.');
	}
	
	$database = new database( $DBhostname, $DBuserName, $DBpassword, '', '', false );
	$test = $database->getErrorMsg();

	if (!$database->_resource) {
		db_err ('stepBack2','password ed username inseriti non sono corretti.');
	}

	// Does this code actually do anything???
	$configArray['DBhostname'] = $DBhostname;
	$configArray['DBuserName'] = $DBuserName;
	$configArray['DBpassword'] = $DBpassword;
	$configArray['DBname']	 = $DBname;
	$configArray['DBPrefix']= $DBPrefix;

	$sql = "CREATE DATABASE `$DBname`";
	$database->setQuery( $sql );
	$database->query();
	$test = $database->getErrorNum();

	if ($test != 0 && $test != 1007) {
		db_err( 'stepBack', 'Avvenuto un errore database: ' . $database->getErrorMsg() );
	}

	// db is now new or existing, create the db object connector to do the serious work
	$database = new database( $DBhostname, $DBuserName, $DBpassword, $DBname, $DBPrefix );

	// delete existing mos table if exists
	$query = "SHOW TABLES FROM `$DBname`";
	$database->setQuery( $query );
	$errors = array();
	if ($tables = $database->loadResultArray()) {
		foreach ($tables as $table) {
				$query = "DROP TABLE IF EXISTS `$table`";
				$database->setQuery( $query );
				$database->query();
				if ($database->getErrorNum()) {
					$errors[$database->getQuery()] = $database->getErrorMsg();
				}
		}
	}

	populate_db( $database, 'eleonline.sql' );
	$DBcreated = 1;
}

function db_err($step, $alert) {
	global $DBhostname,$DBuserName,$DBpassword,$DBname,$DBPrefix;
	echo "<form name=\"$step\" method=\"post\" action=\"install1.php\">
	<input type=\"hidden\" name=\"DBhostname\" value=\"$DBhostname\">
	<input type=\"hidden\" name=\"DBuserName\" value=\"$DBuserName\">
	<input type=\"hidden\" name=\"DBpassword\" value=\"$DBpassword\">
	<input type=\"hidden\" name=\"DBname\" value=\"$DBname\">
	<input type=\"hidden\" name=\"DBPrefix\" value=\"$DBPrefix\">
	</form>\n";
	echo "<script>alert(\"$alert\"); window.history.go(-1);</script>";
	//echo "<script>alert(\"$alert\"); document.location.href='install1.php';</script>";  
	
	exit();
	
	

}

/**
 * @param object
 * @param string File name
 */
function populate_db( &$database, $sqlfile='eleonline.sql') {
	global $errors;

	$mqr = @get_magic_quotes_runtime();
	@set_magic_quotes_runtime(0);
	$query = fread( fopen( 'sql/' . $sqlfile, 'r' ), filesize( 'sql/' . $sqlfile ) );
	@set_magic_quotes_runtime($mqr);
	$pieces  = split_sql($query);

	for ($i=0; $i<count($pieces); $i++) {
		$pieces[$i] = trim($pieces[$i]);
		if(!empty($pieces[$i]) && $pieces[$i] != "#") {
			$database->setQuery( $pieces[$i] );
			if (!$database->query()) {
				$errors[] = array ( $database->getErrorMsg(), $pieces[$i] );
			}
		}
	}
}

/**
 * @param string
 */
function split_sql($sql) {
	$sql = trim($sql);
	$sql = preg_replace('/\n#[^\n]*\n/', "\n", $sql);

	$buffer = array();
	$ret = array();
	$in_string = false;

	for($i=0; $i<strlen($sql)-1; $i++) {
		if($sql[$i] == ";" && !$in_string) {
			$ret[] = substr($sql, 0, $i);
			$sql = substr($sql, $i + 1);
			$i = 0;
		}

		if($in_string && ($sql[$i] == $in_string) && $buffer[1] != "\\") {
			$in_string = false;
		}
		elseif(!$in_string && ($sql[$i] == '"' || $sql[$i] == "'") && (!isset($buffer[0]) || $buffer[0] != "\\")) {
			$in_string = $sql[$i];
		}
		if(isset($buffer[1])) {
			$buffer[0] = $buffer[1];
		}
		$buffer[1] = $sql[$i];
	}

	if(!empty($sql)) {
		$ret[] = $sql;
	}
	return($ret);
}

$isErr = intval( count( $errors ) );

echo "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?".">";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Eleonline Installer</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="install.css" type="text/css" />
<script  type="text/javascript">
<!--
function check() {
	// form validation check
	var formValid=false;
	var f = document.form;
	if ( f.sitename.value == '' ) {
		alert('Inserisci il nome del sito');
		f.sitename.focus();
		formValid=false;
	} else if ( f.nomecomune.value == '' ) {
		alert('Inserisci il nome del Comune');
		f.nomecomune.focus();
		formValid=false;
	} else if ( f.istat.value == '' ) {
		alert('Inserisci il numero Istat del Comune');
		f.istat.focus();
		formValid=false;
	
		} else if ( confirm('Sei sicuro che questi settaggi sono corretti?')) {
		formValid=true;
	}

	return formValid;
}
//-->
</script>
</script>
</head>
<body onload="document.form.sitename.focus();">
<div id="wrapper">
	<div id="header">
		<div id="eleonline"><img src="header_install.png" alt="Installazione Eleonline" title="Installazione Eleonline" /></div>
	</div>
</div>

<div id="ctr" align="center">
	<form action="install3.php" method="post" name="form" id="form" onsubmit="return check();">
	<input type="hidden" name="DBhostname" value="<?php echo "$DBhostname"; ?>" />
	<input type="hidden" name="DBuserName" value="<?php echo "$DBuserName"; ?>" />
	<input type="hidden" name="DBpassword" value="<?php echo "$DBpassword"; ?>" />
	<input type="hidden" name="DBname" value="<?php echo "$DBname"; ?>" />
	<input type="hidden" name="DBPrefix" value="<?php echo "$DBPrefix"; ?>" />
	<input type="hidden" name="DBcreated" value="<?php echo "$DBcreated"; ?>" />

	<div class="install">
		<div id="stepbar">
		  	<div class="step-off">Inizio</div>
	  		<div class="step-off">licenza</div>
		  	<div class="step-off">passo 1</div>
		  	<div class="step-on">passo 2</div>
	  		<div class="step-off">passo 3</div>
		  	<div class="step-off">passo 4</div>
		</div>
		
		<div id="right">
  			<div class="far-right">
<?php if (!$isErr) { ?>
  		  		<input class="button" type="submit" name="next" value="Avanti >>"/>
<?php } ?>
  			</div>
	  		<div id="step">passo 2</div>
  			<div class="clr"></div>

  			<h1>Risultato inserimento database <?php echo "<font color=\"#ff0000\">$DBname</font> su <font color=\"#ff0000\">$DBhostname</font>"; ?> :</h1>
			<div class="install-text">
<?php if ($isErr) { ?>
			Sembra che ci siano errori con l'inserimento dei dati nel tuo database!<br />
  			Non puoi continuare.
			</div>
			<div class="install-form">
			    <div class="form-block">
  				<table class="content2">
		<?php			
			echo '<tr><td colspan="2">';
				echo '<b></b>';
				echo "<br/><br />Error log:<br />\n";
				// abrupt failure
				echo '<textarea rows="10" cols="50">';
				foreach($errors as $error) {
					echo "SQL=$error[0]:\n- - - - - - - - - -\n$error[1]\n= = = = = = = = = =\n\n";
				}
				echo '</textarea>';
				echo "</td></tr>\n";		
		?>		
			        </table>
			     </div>
			</div>
				
<?php } else { ?>


			TUTTO OK!
			<br/>
			<br/>
			</div>
			<div class="install-form">
			  <div class="clr"></div>
			</div>
			

			
  			

  		
		
		
		<div class="clr"></div>
		
		<h1>Inserisci i dati di configurazione del sito:</h1>
			<div class="install-text">
			
			Inserisci il nome del tuo sito. In genere viene usato il nome del Comune.
			</div>
  		<div class="install-form">
  			<div class="form-block">
  				<table class="content2">

  				<tr>
  					<td width="100">Nome del sito</td>
  					<td align="left"><input class="inputbox" type="text" name="sitename" size="40" value="<?php echo "{$configArray['sitename']}"; ?>" /></td>
					<td></td>
  				</tr>
  				<tr>
  					<td width="100">Nome del Comune</td>
  					<td align="left"><input class="inputbox" type="text" name="nomecomune" size="40" value="<?php echo "{$configArray['nomecomune']}"; ?>" /></td>
					<td></td>
  				</tr>

				<tr>
  					<td width="100">Numero Istat</td>
  					<td align="left"><input class="inputbox" type="text" name="istat" size="6" value="<?php echo "{$configArray['istat']}"; ?>" />
					<a href="http://www.istat.it/strumenti/definizioni/comuni/" target="_blank">Preleva i codici Istat dei comuni italiani</a>
					</td><td></td>
  				</tr>
				<tr>
					  <td width="150"><em>Fascia abitanti</em>			  			</td><td>
							<select name="Limite">
							<option value="1" selected>fino a 3.000 ab.</option>
							<option value="2">fino a 10.000 ab.</option>
							<option value="3">fino a 15.000 ab.</option>
							<option value="4">fino a 30.000 ab.</option>
							<option value="5">fino a 100.000 ab.</option>
							<option value="6">fino a 250.000 ab.</option>
							<option value="7">fino a 500.000 ab.</option>
							<option value="8">fino a 1.000.000 ab.</option>
							<option value="9">sopra il 1.000.000 ab.</option>
							</select>
					  </td>
			  			
  				</tr>	



				
				</table>
  				<table class="content2">
				




				<tr>
			  			<td width="70">Capoluogo</td><td width="70">
			  				<input type="checkbox" name="Capoluogo" id="Capoluogo" value="1" <?php if ($Capoluogo) echo 'checked="checked"'; ?> />
			  			</td>
						<td>Check se il comune e' Capoluogo di Provincia</td>
  						
			  	</tr>
				<tr>
					  <td width="70">Linguaggio </td><td width="70">
							<select name="Lingua"><option value="it" selected>italiano</option><option value="en">english</option></select>
					  </td>
					  <td>Lingua di default del sito</td>
			  			
  				</tr>
				<tr>
			  			<td width="70">Multicomune </td><td width="70">
			  				<input type="checkbox" name="Multicomune" id="Multicomune" value="1" <?php if ($Multicomune) echo 'checked="checked"'; ?> />
			  			</td>
						<td>Check se il sito ospita piu' di un comune</td>
  						
			  	</tr>
				<tr>
			  			<td width="70">Replica Db </td><td width="70">
			  				<input type="checkbox" name="Replica" id="Replica" value="1" <?php if ($Replica) echo 'checked="checked"'; ?> />
			  			</td>
						<td>Check in caso di replica del database. Se sullo stesso server lasciare libero</td>
  						
			  		</tr>

			



</table>

  			</div>
  		</div>
  		<div class="clr"></div>
		<div class="clr"></div>
	<h1>Configurazione del Tema:</h1>
			<div class="install-text">
  				<p>La visualizzazione dei risultati puo' essere configurata in maniera da scegliere il 
				tema e altro ancora.
				<br><br>
				
					  Potete comunque sempre cambiare le opzioni successivamete agendo sul file config.php<br/>
				</p>
  			</div>
			<div class="install-form">
  				<div class="form-block">
  		 			
					<br/>
					<table class="content2">
  		  			<tr>
  						<td></td>
  						<td></td>
  						<td></td>
  					</tr>
					
			  		
  		  			
					<tr>
  					<td width="150">Scelta del tema</td>
  					<td><select name='tema'>
					<?php
					$handle=opendir('../client/temi');
					while ($file = readdir($handle)) {
					  if ( (preg_match('/^([_0-9a-zA-Z]+)([_0-9a-zA-Z]{3})$/',$file)) ){
					  //if ( (!preg_match('/[.]/',$file)) ) {
					    $themelist .= "$file ";
					  }
					}
					closedir($handle);
					$themelist = explode(" ", $themelist);
					sort($themelist);
					for ($i=0; $i < sizeof($themelist); $i++) {
					      if(!empty($themelist[$i])) {
						  echo "<option name='tema' value='$themelist[$i]' ";
						  if($themelist[$i]=="default") echo "selected";
						  echo ">$themelist[$i]\n";
					      }
					}
				      echo "</select>";
				      ?>
				    </td>
					
					</tr>
		  		 	</table>
					<br/>
					<table class="content2">
  		  			<tr>
  						<td></td>
  						<td></td>
  						<td></td>
  					</tr>
					
			  		
  		  			
					<tr><td width="150">Visualizza menu per la scelta del tema</td>
							
					
					<td>
					  <select name="sceltatema"><option value="1" selected>SI</option><option value="0">NO</option></select></td><td>Permette di far scegliere all'utente che naviga sul sito il tipo di grafica
					  
					  
					  </td>
					
  					</tr>
		  		 	</table>
					<br/>
					<table class="content2">
  		  			<tr>
  						<td></td>
  						<td></td>
  						<td></td>
  					</tr>
					
			  		
  		  			
					<tr><td width="150">Visualizza blocco laterale?</td><td>
					  <select name="blocco"><option value="1" selected>SI</option><option value="0">NO</option></select></td>
					  <td>Il blocco laterale destro puo' contenere dati e link </td>
					
  					</tr>
		  		 	</table>
					<br/>
					<table class="content2">
  		  			<tr>
  						<td></td>
  						<td></td>
  						<td></td>
  					</tr>
					
			  		
  		  			
					<tr><td width="150">Abilita il formato Flash?</td><td>
					  <select name="flash"><option value="1" selected>SI</option><option value="0">NO</option></select></td>
					  <td>L'abilitazione del Flash permette di avere grafici in movimento. Se disabilitato e grafici saranno statici</td>
					
  					</tr>
		  		 	</table>
					
					
					
					
					
		</div></div></div>
		
		
	  		
			
			
			
			
			
			
			
			
			  			<div class="clr"></div>
	  		
	
	<div class="clr"></div>
	</form>

<?php } // fine if ?> 

</div>
<div class="clr"></div>
<div class="clr"></div>
<?php include("footer.php"); ?>

</body>
</html>
