<?PHP
/********************************************************************************
* Setupscript for DEDI http://www.der-dirigent.de                               *
* (c) 2002 - 2003 by Björn Brockmann bjoern@project-gooseberry.de               *
*                                                                               *
*                                                                               *
* @License: GPL                                                                 *
* @Version: 1.0.4                                                               *
*********************************************************************************/

class gb_template {
	function insert($Loop, $TemplateName, $ToInsert)
	{
		global $TemplateArray, $TemplateLoopArray;

		if ($Loop ==''){
			$TemplateArray[$TemplateName] = $ToInsert;
		}
		else{
			$TemplateLoopArray[$Loop][$TemplateName][] = $ToInsert;
		}
	}

	function make($File)
	{
		global $TemplateArray, $TemplateLoopArray;

		$Matrix = implode('', (file($File)));
		if (is_array($TemplateLoopArray)) {
			$KeysLoopname = array_keys($TemplateLoopArray);
			for ($f = 0; $f < count($KeysLoopname); $f++)
			{
				$Start = strpos($Matrix, "<!--{start:".$KeysLoopname[$f]."}-->");
				$Stop = strpos($Matrix, "<!--{stop:".$KeysLoopname[$f]."}-->");
				$LoopLength = $Stop - $Start;
				$Loop = substr( $Matrix, $Start, $LoopLength);
				$KeysLoopTemplate = array_keys($TemplateLoopArray[$KeysLoopname[$f]]);
				$KeysLoopValue = array_keys($TemplateLoopArray[$KeysLoopname[$f]][$KeysLoopTemplate[0]]);
				for ($t = 0; $t < count($KeysLoopValue); $t++)
				{
					$Loopb = $Loop;
					for ($s = 0; $s < count($KeysLoopTemplate); $s++)
					{
						$Loopb = str_replace("<!--{".$KeysLoopTemplate[$s]."}-->", $TemplateLoopArray[$KeysLoopname[$f]][$KeysLoopTemplate[$s]][$t], $Loopb);
					}
					$LoopFinal = $LoopFinal.$Loopb;
				}
				$Matrix = str_replace ($Loop, $LoopFinal, $Matrix);
				$Matrix = str_replace ("<!--{start:".$KeysLoopname[$f]."}-->", '', $Matrix);
				$Matrix = str_replace ("<!--{stop:".$KeysLoopname[$f]."}-->", '', $Matrix);
				$Matrix = str_replace ($Loop, $Start, $Matrix);
				$LoopFinal = '';
			}
		}
		if (is_array($TemplateArray)) {
			$Keys = array_keys($TemplateArray);
			for ($i = 0; $i < count($Keys); $i++) $Matrix = str_replace("<!--{".$Keys[$i]."}-->", $TemplateArray[$Keys[$i]], $Matrix);
		}
		return $Matrix;
	}

	function flush()
	{
		global $TemplateArray, $TemplateLoopArray;

		unset($TemplateArray);
		unset($TemplateLoopArray);
	}
}

class setup {
	var $globals;
	var $debug = false;
	var $updatefiles = array(
							'updates.sql',
							'updates_from.00.97.00.sql',
							'updates_from.00.98.00.sql',
							'updates_from.00.99.00.sql',
							'updates_from.01.00.00.sql',
                            'updates_from.01.00.01.sql',
                            'updates_from.01.00.02.sql',
                            'updates_from.01.00.03.sql');

	/**
	* Konstruktor. Catch all globals
	*/
	function setup()
	{
		$this -> catch_globals();

		//manipulate some actions if user chose updat
		if ($this -> globals['mode'] == 'update') {
			//seperate update finish screen
			if ($this -> globals['action'] == 'enter_email') $this -> globals['action'] = 'screen_execute_update_and_finish';
		}
	}

	/**
	* Manage the setup
	*
	* @return string specific HTML- screen
	*/
	function make_setup()
	{
		switch ($this -> globals['action'])
		{
			case 'screen_pretest':
				$return_this = $this -> screen_pretest();
				break;
			case 'screen_test':
				$return_this = $this -> screen_test();
				break;
			case 'screen_chose_setup_kind':
				$return_this = $this -> screen_chose_setup_kind();
				break;
		    case 'screen_enter_path':
				$return_this = $this -> screen_enter_path();
				break;
		    case 'screen_validate_path':
				$return_this = $this -> screen_validate_path();
				break;
			case 'screen_enter_admin_account':
				$return_this = $this -> screen_enter_admin_account();
				break;
			case 'validate_admin_pass':
				$return_this = $this -> validate_admin_pass();
				break;
			case 'screen_enter_mysql_data':
				$return_this = $this -> screen_enter_mysql_data();
				break;
			case 'screen_ready_to_insert_sql':
				$return_this = $this -> screen_ready_to_insert_sql_dump();
				break;
			case 'screen_download_config':
				$return_this = $this -> manage_insert_sql_dump();
				$return_this .= $this -> screen_download_config();
				break;
			case 'screen_finish':
				$return_this = $this -> screen_finish();
				break;
			case 'screen_finish_update':
				$return_this = $this -> screen_finish_update();
				break;
			case 'screen_execute_update_and_finish':
				$return_this = $this -> screen_execute_update_and_finish();
				break;
			case 'make_cfg_general':
				$return_this = $this -> make_cfg_general();
				break;
			default:
				$return_this = $this -> screen_welcome();
		}
		return $return_this;
	}

	/**
	* Catch POST and GET - Statements
	*/
	function catch_globals() {

		if (isset($_SERVER)) {
			$this->globals = $_REQUEST + $_SERVER + $_GET + $_POST;
			return;
		}
		while (list($key, $val) = @each($_GET)) $this -> globals[$key] = $val;
		while (list($key, $val) = @each($_POST)) $this -> globals[$key] = $val;
		while (list($key, $val) = @each($_SERVER)) $this -> globals[$key] = $val;
	}

	/**
	* Make the Welcome screen. If it supported in future dirigent-versions
	* you can chose your language here (at the moment only german)
	*
	* @return string comple HTML welcome screen
	*/
	function screen_welcome()
	{
		$tpl = new gb_template();
		$tpl -> insert('', 'next_step', 'screen_pretest');
		return $tpl -> make('templates/welcome.tpl');
	}

	/**
	* Make the Pre-Test screen.
	*
	* @return string comple HTML welcome screen
	*/
	function screen_pretest()
	{
		include_once('fnc.test.php');
		$tpl = new gb_template();
		$tpl -> insert('', 'lang', $this -> globals['lang']);
		$tpl -> insert('', 'next_step', 'screen_chose_setup_kind');
		$tpl -> insert('', 'test_PHP_check', @test_PHP_check() );
		$tpl -> insert('', 'test_PHP_config', @test_PHP_config() );
		return $tpl -> make('templates/'. $this -> globals['lang'] . '/screen_pretest.tpl');
	}

	/**
	* Make the Test screen.
	*
	* @return string comple HTML welcome screen
	*/
	function screen_test()
	{
		include_once('fnc.test.php');
		$tpl = new gb_template();
		$tpl -> insert('', 'test_folder', @test_folder() );
		$tpl -> insert('', 'test_configuration', @test_configuration() );
		return $tpl -> make('templates/'. $this -> globals['lang'] . '/screen_test.tpl');
	}

	/**
	* Make screen where user can chose mysql-dump
	*
	* @return string complete HTML chose screen
	*/
	function screen_chose_setup_kind()
	{
		$tpl = new gb_template();
		$tpl -> insert('', 'lang', $this -> globals['lang']);
		$tpl -> insert('', 'next_step', 'screen_enter_path');
		return $tpl -> make('templates/'. $this -> globals['lang'] . '/chose_setup_kind.tpl');
	}

	/**
	* Make screen where user enter path informmation (root_path,
	* root_httpp_path, full_root_http_path)
	*
	* @return string complete HTML enter path screen
	*/
	function screen_enter_path()
	{
		$tpl = new gb_template();

		// make pathvariables
		$root_path = str_replace ('\\', '/', dirname(__FILE__) . '/*');
		$root_path = str_replace('setup/*', '', $root_path);
	        $root_http_path = str_replace('setup/index.php', '', $_SERVER['PHP_SELF']);
		$root_full_http_path = 'http://'.$_SERVER['HTTP_HOST'].$root_http_path;
		$tpl -> insert('', 'root_path', $root_path);
		$tpl -> insert('', 'root_http_path', $root_http_path);
		$tpl -> insert('', 'root_full_http_path', $root_full_http_path);
		$tpl -> insert('', 'mode', $this -> globals['mode']);
		$tpl -> insert('', 'sql_target', $this -> globals['sql_target']);
		$tpl -> insert('', 'lang', $this -> globals['lang']);
		$tpl -> insert('', 'next_step', 'screen_validate_path');
		return $tpl -> make('templates/'. $this -> globals['lang'] . '/enter_path.tpl');
	}

	/**
	* Validate path_values (root_path, root_http_path, root_full_http_path) and print
	* out error or the mysql data Screen.
	*
	* @return string complete HTML ready to enter mysql data or error screen
	*/
	function screen_validate_path()
	{
		$error = false;
		$tpl = new gb_template();

	        //check root_path
		if (!is_dir($this -> globals['root_path'])) {
			$target_tpl = "enter_path.tpl";
			$tpl -> insert('', 'path_error', " <b>FEHLER!</b> Der 'root_path' exestiert nicht!<br><br>");
			$error = true;
		}
		$tpl -> insert('', 'root_path', $this -> add_ending_slash($this -> globals['root_path']));
		$tpl -> insert('', 'root_http_path', $this -> add_ending_slash($this -> globals['root_http_path']));
		$tpl -> insert('', 'root_full_http_path', $this -> add_ending_slash($this -> globals['root_full_http_path']));
		$tpl -> insert('', 'sql_target', $this -> globals['sql_target']);
		$tpl -> insert('', 'lang', $this -> globals['lang']);
		$tpl -> insert('', 'mode', $this -> globals['mode']);

		if ($error) {
  			$tpl -> insert('', 'next_step', 'screen_validate_path');
			$target_tpl = "enter_path.tpl";
		} else {
			if ($this -> globals['sql_target'] == "updates.sql") {
				// Insert template dummies for some erros that can in occur screen_ready_to_insert_sql_dump()
				$tpl -> insert('', 'host', 'localhost');
				$tpl -> insert('', 'db', '');
				$tpl -> insert('', 'prefix', 'dedi_');
				$tpl -> insert('', 'user', '');
				$tpl -> insert('', 'pass', '');
				$tpl -> insert('', 'connection_error', '');
	  			$tpl -> insert('', 'next_step', 'screen_ready_to_insert_sql');
				$target_tpl = "enter_mysql_data.tpl";
			} else {
				$tpl -> insert('', 'adminpass_error', '');
				$tpl -> insert('', 'next_step', 'validate_admin_pass');
				$target_tpl = "enter_admin_account.tpl";
			}
		}
		return $tpl -> make('templates/'. $this -> globals['lang'] . '/' . $target_tpl);
	}

	/**
	* Make screen where user enter administration passwort for admin account
	*
	* @return string complete HTML ready_to_insert_sql or error  screen
	*/
	function screen_enter_admin_account() {
		$tpl = new gb_template();
		$tpl -> insert('', 'mode', $this -> globals['mode']);
		$tpl -> insert('', 'sql_target', $this -> globals['sql_target']);
		$tpl -> insert('', 'lang', $this -> globals['lang']);
   		$tpl -> insert('', 'next_step', 'validate_admin_pass');
		$tpl -> insert('', 'root_path', $this -> globals['root_path']);
		$tpl -> insert('', 'root_http_path', $this -> globals['root_http_path']);
		$tpl -> insert('', 'root_full_http_path', $this -> globals['root_full_http_path']);
		return $tpl -> make('templates/'. $this -> globals['lang'] . '/enter_admin_account.tpl');
	}

	// check admin_passwort for dedi-account
	function validate_admin_pass() {
		$error = false;
		$tpl = new gb_template();
		if (empty($this -> globals['adminpass']) || $this -> globals['adminpass'] != $this -> globals['adminpass1'] || preg_match('/[\'\"\#\<\>]/i', $this -> globals['adminpass'])) {
			$tpl -> insert('', 'adminpass_error', ' <b>FEHLER!</b> Fehlerhaftes Administrator-Passwort. Passwort und Wiederholung stimmen nicht überein oder nicht erlaubte Zeichen verwendet: [\'][\"][#][<][>]<br><br>');
			$error = true;
		}
		$tpl -> insert('', 'mode', $this -> globals['mode']);
		$tpl -> insert('', 'sql_target', $this -> globals['sql_target']);
		$tpl -> insert('', 'lang', $this -> globals['lang']);
		$tpl -> insert('', 'root_path', $this -> globals['root_path']);
		$tpl -> insert('', 'root_http_path', $this -> globals['root_http_path']);
		$tpl -> insert('', 'root_full_http_path', $this -> globals['root_full_http_path']);
		$tpl -> insert('', 'adminpass', $this -> globals['adminpass']);

		// Insert template dummies for some erros that can in occur screen_ready_to_insert_sql_dump()
		$tpl -> insert('', 'host', 'localhost');
		$tpl -> insert('', 'db', '');
		$tpl -> insert('', 'prefix', 'dedi_');
		$tpl -> insert('', 'user', '');
		$tpl -> insert('', 'pass', '');
		$tpl -> insert('', 'connection_error', '');

		if ($error) {
  			$tpl -> insert('', 'next_step', 'validate_admin_pass');
			$target_tpl = "enter_admin_account.tpl";
		} else {
  			$tpl -> insert('', 'next_step', 'screen_ready_to_insert_sql');
			$target_tpl = "enter_mysql_data.tpl";
		}
		return $tpl -> make('templates/'. $this -> globals['lang'] . '/' . $target_tpl);
	}

	/**
	* Make screen where user enter datbaseinformation (host,
	* database, user, password).
	*
	* @return string complete HTML enter_mysql_data screen
	*/
	function screen_enter_mysql_data()
	{
		$tpl = new gb_template();

		//check if user have chose "update"
		if ($this -> globals['sql_target'] == 'updates.sql') $this -> globals['mode'] = 'update';
		else $this -> globals['mode'] = 'normal';
		$tpl -> insert('', 'mode', $this -> globals['mode']);
		$tpl -> insert('', 'sql_target', $this -> globals['sql_target']);
		$tpl -> insert('', 'lang', $this -> globals['lang']);
   		$tpl -> insert('', 'next_step', 'screen_ready_to_insert_sql');
		$tpl -> insert('', 'root_path', $this -> globals['root_path']);
		$tpl -> insert('', 'root_http_path', $this -> globals['root_http_path']);
		$tpl -> insert('', 'root_full_http_path', $this -> globals['root_full_http_path']);
		$tpl -> insert('', 'adminpass', $this -> globals['adminpass']);

		// Insert template dummies for some erros that can in occur screen_ready_to_insert_sql_dump()
		$tpl -> insert('', 'host', '');
		$tpl -> insert('', 'db', '');
		$tpl -> insert('', 'prefix', 'dedi_');
		$tpl -> insert('', 'user', '');
		$tpl -> insert('', 'pass', '');
		$tpl -> insert('', 'connection_error', '');
		return $tpl -> make('templates/'. $this -> globals['lang'] . '/enter_mysql_data.tpl');
	}

	/**
	* Validate User Data(host, database, prefix, user, password) and print out error
	* or the ready_to_insert_mysql Screen.
	*
	* @return string complete HTML ready_to_insert_sql or error  screen
	*/
	function screen_ready_to_insert_sql_dump()
	{
		$error = false;
		$tpl = new gb_template();

		// check table_prefix
		if (!preg_match('/^[a-zA-Z]{1,1}[[:alnum:]_-]*$/', $this -> globals['prefix'])) {
			$tpl -> insert('', 'connection_error', ' <b>FEHLER!</b> Fehlerhaftes Tabellen-Präfix. Erlaubte Zeichen: [a-z][A-Z][0-9][-][_]<br><br>');
			$error = true;
		}

		//check host, username and password
		$con_handle = @mysql_connect ($this -> globals['host'], $this -> globals['user'], $this -> globals['pass']);
		if (empty($con_handle)) {
			$tpl -> insert('', 'connection_error', ' <b>FEHLER!</b> Bitte überprüfen Sie HOST, USERNAME UND PASSWORT<br><br>');
			$error = true;
		} elseif (!mysql_select_db ($this -> globals['db'], $con_handle)) {
			$tpl -> insert('', 'connection_error', '<b>FEHLER!</b> Die Datenbank "'. $this -> globals[db] . '" existiert nicht oder ist nicht erreichbar! Überprüfen Sie bitte, ob diese Datenbank schon angelegt ist.<br><br>');
			$error = true;
		}

		$tpl -> insert('', 'root_path', $this -> globals['root_path']);
		$tpl -> insert('', 'root_http_path', $this -> globals['root_http_path']);
		$tpl -> insert('', 'root_full_http_path', $this -> globals['root_full_http_path']);
		$tpl -> insert('', 'host', $this -> globals['host']);
		$tpl -> insert('', 'db', $this -> globals['db']);
		$tpl -> insert('', 'user', $this -> globals['user']);
		$tpl -> insert('', 'pass', $this -> globals['pass']);
		$tpl -> insert('', 'sql_target', $this -> globals['sql_target']);
		$tpl -> insert('', 'lang', $this -> globals['lang']);
		$tpl -> insert('', 'mode', $this -> globals['mode']);
		$tpl -> insert('', 'adminpass', $this -> globals['adminpass']);
		if ($error) {
  			$tpl -> insert('', 'prefix', $this -> globals['prefix']);
  			$tpl -> insert('', 'next_step', 'screen_ready_to_insert_sql');
			$target_tpl = "enter_mysql_data.tpl";
		} else {
			//prefix check
			if(! preg_match('/(.*)_$/', $this -> globals['prefix'])){
				$this -> globals['prefix'] = $this -> globals['prefix'] .'_';
			}
			//Update
			if(! is_array($this->get_dedi_version() ) && $this -> globals['sql_target'] =='updates.sql'){
				$tpl -> insert('', 'prefix', $this -> globals['prefix']);
				$tpl -> insert('', 'connection_error', '<b>FEHLER!</b> Das Update kann nicht durchgeführt werden, da keine DeDi- Version in der Datenbank gefunden wurde. Bitte überprüfen Sie den Datenbanknamen und ggf. das Prefix');
				$tpl -> insert('', 'next_step', 'screen_ready_to_insert_sql');
				$target_tpl = "enter_mysql_data.tpl";
			}
			//normales setup
			else{
				$tpl -> insert('', 'prefix', $this -> globals['prefix']);
				$tpl -> insert('', 'next_step', 'screen_download_config');
				$target_tpl = "ready_to_insert_sql.tpl";
			}
		}
		return $tpl -> make('templates/'. $this -> globals['lang'] . '/' . $target_tpl);
	}

	/**
	* Give user the opinion to download the config.php
	*
	* @return string complete HTML download_config  screen
	*/
	function screen_download_config()
	{
		$tpl = new gb_template();

		if($this -> globals['mode'] == 'update') $tpl -> insert('', 'show_txt_only_by_update', '<div align="center"><b>Auch wenn Sie die Updateoption gewählt haben, müssen Sie die Konfigurationsdatei neu herunterladen!"</b></div>');
		else $tpl -> insert('', 'show_txt_only_by_update', '');
		$tpl -> insert('', 'root_path', $this -> globals['root_path']);
		$tpl -> insert('', 'root_http_path', $this -> globals['root_http_path']);
		$tpl -> insert('', 'root_full_http_path', $this -> globals['root_full_http_path']);
		$tpl -> insert('', 'host', $this -> globals['host']);
		$tpl -> insert('', 'db', $this -> globals['db']);
		$tpl -> insert('', 'prefix', $this -> globals['prefix']);
		$tpl -> insert('', 'user', $this -> globals['user']);
		$tpl -> insert('', 'pass', $this -> globals['pass']);
		$tpl -> insert('', 'email', $this -> globals['email']);
		$tpl -> insert('', 'sql_target', $this -> globals['sql_target']);
		$tpl -> insert('', 'lang', $this -> globals['lang']);
		$tpl -> insert('', 'next_step', 'screen_finish');
		$tpl -> insert('', 'mode', $this -> globals['mode']);
		$tpl -> insert('', 'adminpass', $this -> globals['adminpass']);
		return $tpl -> make('templates/'. $this -> globals['lang'] . '/download_config.tpl');
	}

	/**
	* Setup is done. Throw out the finish screen
	*
	* @return string complete HTML finish screen
	*/
	function screen_finish()
	{
		$tpl = new gb_template();
		$tpl -> insert('', 'lang', $this -> globals['lang']);
		$tpl -> insert('', 'next_step', 'screen_test');
		return $tpl -> make('templates/'. $this -> globals['lang'] . '/finish.tpl');
	}


	/**
	* Update is done. Throw out the finish screen
	* for update
	*
	* @return string complete HTML finish screen
	*/
	function screen_execute_update_and_finish()
	{
		$this -> insert_sql_dump();

		$tpl = new gb_template();
		return $tpl -> make('templates/'. $this -> globals['lang'] . '/finish_update.tpl');
	}

	function make_cfg_general() {

		// make pathvariables for the configfile
		$dedi_path = $_SERVER['root_path'];
		$client_path = $_SERVER['root_path'];

		//make headers for download
		header("Content-Type: text/x-delimtext; name=\"config.php\"");
		header("Content-disposition: attachment; filename=config.php");

		//insert data
		$tpl = new gb_template();
		$tpl -> insert('', 'host', $this -> globals['host']);
		$tpl -> insert('', 'db', $this -> globals[db]);
		$tpl -> insert('', 'prefix', $this -> globals['prefix']);
		$tpl -> insert('', 'user', $this -> globals['user']);
		$tpl -> insert('', 'pass', $this -> globals['pass']);
		$tpl -> insert('', 'dedi_path', $dedi_path);
		$tpl -> insert('', 'dedi_http_path', $dedi_http_path);
		$tpl -> insert('', 'dedi_full_http_path', $this -> globals['root_full_http_path']);
		$tpl -> insert('', 'client_path', $client_path);
		$tpl -> insert('', 'client_http_path', $client_http_path);
		$tpl -> insert('', 'sql_target', $this -> globals['sql_target']);
		$tpl -> insert('', 'lang', $this -> globals['lang']);
		$tpl -> insert('', 'email', $this -> globals[email]);
		return $tpl -> make('templates/'. $this -> globals['lang'] . '/config.php.tpl');
	}


	function insert_config_values()
	{
		global $_SERVER;

		//make pathvariables for the configfile
		$dedi_path = $this -> globals['root_path'];
		$client_path = $this -> globals['root_path'];

		//insert data
		$tpl = new gb_template();
		$tpl -> insert('', 'host', $this -> globals['host']);
		$tpl -> insert('', 'db', $this -> globals[db]);
		$tpl -> insert('', 'prefix', $this -> globals['prefix']);
		$tpl -> insert('', 'user', $this -> globals['user']);
		$tpl -> insert('', 'pass', $this -> globals['pass']);
		$tpl -> insert('', 'dedi_path', $dedi_path);
		$tpl -> insert('', 'dedi_http_path', $dedi_http_path);
		$tpl -> insert('', 'dedi_full_http_path', $this -> globals['root_full_http_path']);
		$tpl -> insert('', 'client_path', $client_path);
		$tpl -> insert('', 'client_http_path', $client_http_path);
		$tpl -> insert('', 'sql_target', $this -> globals['sql_target']);
		$tpl -> insert('', 'lang', $this -> globals['lang']);
		$tpl -> insert('', 'email', $this -> globals[email]);
		$sql_data = $tpl -> make('sql/config.sql');

		// replace prefix in sql statement
		$in = array("!ALTER TABLE dedi_!",
	                "!ALTER TABLE `dedi_!",
	                "!DELETE FROM dedi_!",
                    "!DELETE FROM `dedi_!",
		            "!UPDATE dedi_!",
		            "!UPDATE `dedi_!",
                    "!REPAIR TABLE `dedi_!",
                    "!OPTIMIZE TABLE `dedi_!",
                    "!DROP TABLE IF EXISTS dedi_!",
			        "!CREATE TABLE dedi_!",
			        "!CREATE TABLE `dedi_!",
			        "!INSERT INTO `dedi_!",
			        "!INSERT INTO dedi_!");
		$out = array('ALTER TABLE '.$this -> globals['prefix'],
			         'ALTER TABLE `'.$this -> globals['prefix'],
			         'DELETE FROM '.$this -> globals['prefix'],
		             'DELETE FROM `'.$this -> globals['prefix'],
			         'UPDATE '.$this -> globals['prefix'],
			         'UPDATE `'.$this -> globals['prefix'],
                     'REPAIR TABLE `'.$this -> globals['prefix'],
                     'OPTIMIZE TABLE `'.$this -> globals['prefix'],
			         'DROP TABLE IF EXISTS '.$this -> globals['prefix'],
			         'CREATE TABLE '.$this -> globals['prefix'],
			         'CREATE TABLE `'.$this -> globals['prefix'],
			         'INSERT INTO `'.$this -> globals['prefix'],
			         'INSERT INTO '.$this -> globals['prefix']);
		$sql_data = preg_replace($in, $out, $sql_data);
		$sql_data = $this -> remove_remarks($sql_data);
		$sql_pieces = $this -> split_sql_file($sql_data, ';');
		$sql_count = count($sql_pieces);
		$con_handle =  mysql_connect ($this -> globals['host'], $this -> globals['user'], $this -> globals['pass']);
		mysql_select_db ($this -> globals[db], $con_handle);

		// DEBUGGING
		if ($this -> debug) {
                 	echo "Auszuführende querys:  $sql_count <br><br>";
			if (mysql_error() != '') echo  $i+1 . ":  <font color='darkred'><b>FEHLER</b></font>  -->  " . mysql_error() . "<br>" . $sql . '<br><br>';
			else echo  $i+1 . ":   <font color= 'darkgreen'><b>AUSGEFÜHRT</b></font><br>". $sql . '<br><br>';
		}

		for($i = 0; $i < $sql_count; $i++)
		{
			$sql = trim($sql_pieces[$i]);
			if (!empty($sql)) {
				mysql_query ($sql, $con_handle);

				//DEBUGGING
				if($this -> debug) {
					if(mysql_error() != '')	echo  $i+1 . ":  <font color='darkred'><b>FEHLER</b></font>  -->  " . mysql_error() . "<br>" . $sql . '<br><br>';
					else echo  $i+1 . ":   <font color= 'darkgreen'><b>AUSGEFÜHRT</b></font><br>". $sql . '<br><br>';
				}
			}
		}
	}

	function manage_insert_sql_dump(){
		if($this->globals['sql_target'] == 'updates.sql'){
			$versionarray = $this -> get_dedi_version();
			$filecount = count($this->updatefiles);


			//compare version number, if dedi version is greater then the newest versionnumber
			//of the updatefile, abort
			$fileversion = explode('.', $this->updatefiles[$filecount-1]);

			// print_r($versionarray);echo"<br>";
			// if system version is grater then updatefileversion abort
			if ($versionarray['prior'] > $fileversion['1']) return;
			else if ($versionarray['prior'] == $fileversion['1']) {
				if ($versionarray['minor'] >  $fileversion['2']) return;
				else if ($versionarray['minor'] == $fileversion['2']) {
					if($versionarray['fix'] >  $fileversion['3']) return;
				}
			}

			//figure out needed files for update
			for($i=$filecount; $i>0;$i--){
				$key = $i-1;
				$fileversion = explode('.', $this->updatefiles[$key]);
				if ($versionarray['prior'] >=  $fileversion['1'] && $versionarray['minor'] >=  $fileversion['2'] && $versionarray['fix'] >=  $fileversion['3']) break;
			}

			$return_this = '';

			//insert update files
			for($i=$key; $i<$filecount; $i++){
				$this->globals['sql_target'] = $this->updatefiles[$i];
				$return_this .= $this->insert_sql_dump();
			}
		}
		else{
			$return_this = $this->insert_sql_dump();
			$return_this .= $this -> insert_config_values();//output only for debugging
		}

		return $return_this;
	}

	/**
	* insert the mysqldump into the datbase
	*
	* @return void
	*/
	function insert_sql_dump() {
		// Zeitinterval vergrößern
		@set_time_limit(0);

		$con_handle =  mysql_connect ($this -> globals['host'],
		$this -> globals['user'],
		$this -> globals['pass']);
		mysql_select_db ($this -> globals['db'], $con_handle);

		//Load mysql_dump - file, replace prefix, format it and make it handy
		$sql_data = implode('',(file('sql/' . $this -> globals['sql_target'])));



		$in = array("!ALTER TABLE dedi_!",
	                "!ALTER TABLE `dedi_!",
	                "!DELETE FROM dedi_!",
                    "!DELETE FROM `dedi_!",
		            "!UPDATE dedi_!",
		            "!UPDATE `dedi_!",
                    "!REPAIR TABLE `dedi_!",
                    "!OPTIMIZE TABLE `dedi_!",
                    "!DROP TABLE IF EXISTS dedi_!",
			        "!CREATE TABLE dedi_!",
			        "!CREATE TABLE `dedi_!",
			        "!INSERT INTO `dedi_!",
			        "!INSERT INTO dedi_!");
		$out = array('ALTER TABLE '.$this -> globals['prefix'],
			         'ALTER TABLE `'.$this -> globals['prefix'],
			         'DELETE FROM '.$this -> globals['prefix'],
		             'DELETE FROM `'.$this -> globals['prefix'],
			         'UPDATE '.$this -> globals['prefix'],
			         'UPDATE `'.$this -> globals['prefix'],
                     'REPAIR TABLE `'.$this -> globals['prefix'],
                     'OPTIMIZE TABLE `'.$this -> globals['prefix'],
			         'DROP TABLE IF EXISTS '.$this -> globals['prefix'],
			         'CREATE TABLE '.$this -> globals['prefix'],
			         'CREATE TABLE `'.$this -> globals['prefix'],
			         'INSERT INTO `'.$this -> globals['prefix'],
			         'INSERT INTO '.$this -> globals['prefix']);

		$sql_data = preg_replace($in, $out, $sql_data);
		// change admin passwort by user input if not in update mode
		if ($this -> globals['sql_target'] != 'updates.sql') {
			$sql_data = preg_replace('!{adminpass}!', md5($this -> globals['adminpass']), $sql_data);
		}
		$sql_data = $this -> remove_remarks($sql_data);
		$sql_pieces = $this -> split_sql_file($sql_data, ';');
		$sql_count = count($sql_pieces);


		// DEBUGGING
		if($this -> debug) echo "Auszuführende querys:  $sql_count <br><br>";
		for ($i = 0; $i < $sql_count; $i++) {
			$sql = trim($sql_pieces[$i]);
			if (!empty($sql)) {
				mysql_query ($sql, $con_handle);

				//DEBUGGING
				if($this -> debug) {
					if(mysql_error() != '') echo  $i+1 . ":  <font color='darkred'><b>FEHLER</b></font>  -->  " . mysql_error() . "<br>" . $sql . '<br><br>';
					else echo  $i+1 . ":   <font color= 'darkgreen'><b>AUSGEFÜHRT</b></font><br>";//. $sql . '<br><br>';
				}
			}
		}
	}

	function get_dedi_version(){

		if( empty($this -> globals['host'])) die('Fatal error - No DB connection data');

		$con_handle =  mysql_connect ($this -> globals['host'],
		$this -> globals['user'],
		$this -> globals['pass']);
		mysql_select_db ($this -> globals[db], $con_handle);

		$sql = 'SHOW TABLES';
		$result = mysql_query ($sql, $con_handle);

        $version_exists = false;
        while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
           foreach ($line as $col_value) {
               if($col_value == $this -> globals['prefix'] . 'values'){
               		$version_exists = true;
               }
           }
        }
        mysql_free_result($result);

        //abort - no update table found
        if(! $version_exists)
        	return false;

        //echo $this -> globals['prefix']."values<br>";
        if($version_exists){
        	$sql = "SELECT value FROM `".$this -> globals['prefix']."values`  WHERE group_name =  'cfg' AND key1 =  'version'";
			$result = mysql_query ($sql, $con_handle);
			if ($line = mysql_fetch_array($result, MYSQL_ASSOC)){
				$pieces = explode('.', $line['value']);
				$version['prior'] = $pieces['0'];
				$version['minor'] = $pieces['1'];
				$version['fix']   = $pieces['2'];
				//print_r($version);
				//return version
				return $version;
			}
        }

        mysql_close($con_handle);

		$version['prior'] = '00';
		$version['minor'] = '00';
		$version['fix']   = '00';
		//print_r($version);
		//clean install - no version exists return 00 00 00
		return $version;
	}

	/**
	* removes '# blabla...' from the mysql_dump.
	* This function was original developed for the phpbb 2.01
	* (C) 2001 The phpBB Group http://www.phpbb.com
	*
	* @return string input_without_#
	*/
	function remove_remarks($sql) {
		$lines = explode("\n", $sql);

		// try to keep mem. use down
		$sql = '';
		$linecount = count($lines);
		$output = '';
		for ($i = 0; $i < $linecount; $i++) {
			if (($i != ($linecount - 1)) || (strlen($lines[$i]) > 0)) {
				if ($lines[$i][0] != '#') $output .= $lines[$i] . "\n";
				else $output .= "\n";

				// Trading a bit of speed for lower mem. use here.
				$lines[$i] = '';
			}
		}
		return $output;
	}

	/**
	* Splits sql- statements into handy pieces.
	* This function was original developed for the phpbb 2.01
	* (C) 2001 The phpBB Group http://www.phpbb.com
	*
	* @return array sql_pieces
	*/
	function split_sql_file($sql, $delimiter) {
		// Split up our string into "possible" SQL statements.
		$tokens = explode($delimiter, $sql);

		// try to save mem.
		$sql = '';
		$output = array();

		// we don't actually care about the matches preg gives us.
		$matches = array();

		// this is faster than calling count($oktens) every time thru the loop.
		$token_count = count($tokens);
		for ($i = 0; $i < $token_count; $i++) {
			// Dont wanna add an empty string as the last thing in the array.
			if (($i != ($token_count - 1)) || (strlen($tokens[$i] > 0))) {
				// This is the total number of single quotes in the token.
				$total_quotes = preg_match_all("/'/", $tokens[$i], $matches);

				// Counts single quotes that are preceded by an odd number of backslashes,
				// which means they're escaped quotes.
				$escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$i], $matches);
				$unescaped_quotes = $total_quotes - $escaped_quotes;

				// If the number of unescaped quotes is even, then the delimiter did NOT occur inside a string literal.
				if (($unescaped_quotes % 2) == 0) {
					// It's a complete sql statement.
					$output[] = $tokens[$i];
					// save memory.
					$tokens[$i] = '';
				} else {
					// incomplete sql statement. keep adding tokens until we have a complete one.
					// $temp will hold what we have so far.
					$temp = $tokens[$i] . $delimiter;

					// save memory..
					$tokens[$i] = '';

					// Do we have a complete statement yet?
					$complete_stmt = false;
					for ($j = $i + 1; (!$complete_stmt && ($j < $token_count)); $j++)
					{
						// This is the total number of single quotes in the token.
						$total_quotes = preg_match_all("/'/", $tokens[$j], $matches);

						// Counts single quotes that are preceded by an odd number of backslashes,
						// which means theyre escaped quotes.
						$escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$j], $matches);
						$unescaped_quotes = $total_quotes - $escaped_quotes;
        						if (($unescaped_quotes % 2) == 1) {
							// odd number of unescaped quotes. In combination with the previous incomplete
							// statement(s), we now have a complete statement. (2 odds always make an even)
							$output[] = $temp . $tokens[$j];

							// save memory.
							$tokens[$j] = '';
							$temp = '';

							// exit the loop.
							$complete_stmt = true;

							// make sure the outer loop continues at the right point.
							$i = $j;
						} else {
							// even number of unescaped quotes. We still dont have a complete statement.
							// (1 odd and 1 even always make an odd)
							$temp .= $tokens[$j] . $delimiter;
							// save memory.
							$tokens[$j] = '';
						}

					}
				}
			}
		}
		return $output;
	}

	/**
	* Add ending slash to url or path
	*
	* @return string input with ending slash
	*/
	function add_ending_slash($path_value)
	{
		if(substr($path_value,-1) != '/') $path_value = $path_value.'/';
		return $path_value;
	}
}
set_magic_quotes_runtime(0);
error_reporting(E_ALL & ~E_NOTICE);
ignore_user_abort(true);
$con_setup = &new setup();
$data = $con_setup -> make_setup();
echo $data;
?>