<?php
// +---------------------------------------------------------------------------------------+
// | TenderSystem                                                                          |
// +---------------------------------------------------------------------------------------+
// | The contents of this file are subject to the TenderSystem Public License Version 1.1  |
// | ("License"); you may not use this file except in compliance with the License. You may |
// | obtain a copy of the License at http://www.tendersystem.com/tpl/                      |
// |                                                                                       |
// | Software distributed under the License is distributed on an "AS IS" basis, WITHOUT    |
// | WARRANTY OF ANY KIND, either express or implied. See the License for the specific     |
// | language governing rights and limitations under the License.                          |
// |                                                                                       |
// | All copies of the Covered Code must include the "Powered by TenderSystem" logo and    |
// | ValueCard copyright notice on every user interface screen and in every outgoing       |
// | email in the same form as they appear in the distribution.                            |
// |                                                                                       |
// | The Original Code is: TenderSystem                                                    |
// | The Initial Developer of the Original Code is ValueCard (Pty) Limited.                |
// | Portions created by ValueCard are Copyright (C) 2002 ValueCard (Pty) Limited.         |
// | All Rights Reserved.                                                                  |
// | Contributor(s): __________________.                                                   |
// +---------------------------------------------------------------------------------------+

/**
* Re-install a database
* @package TenderSystem
* @subpackage install
* @copyright Copyright &copy; 2002, ValueCard (Pty) Ltd
* @license http://www.tendersystem.com/tpl/ TenderSystem Public License
* @version 
*/

// include required file
require(getcwd()."/modules/external/class/dunzip/dUnzip2.inc.php");

// check config file
if($_FILES['config']['name'] && $_FILES['config']['error']) {
	// generate xml
	xml_generator("install",$function,"e30",$params,$cfg);
} elseif($_FILES['config']['name']) {
	if(strpos($_FILES['config']['type'],"zip") || strpos($_FILES['config']['name'],".zip")) {
		$config_file = $_FILES['config']['tmp_name'];
	} else {
		// generate xml
		xml_generator("install",$function,"e35",$params,$cfg);
	}
}

// check data file
if($_FILES['data']['name'] && $_FILES['data']['error']) {
	// generate xml
	xml_generator("install",$function,"e31",$params,$cfg);
} elseif($_FILES['data']['name']) {
	if(strpos($_FILES['data']['type'],"zip") || strpos($_FILES['data']['name'],".zip")) {
		// if zip file
		$new_dunzip = new dUnzip2($_FILES['data']['tmp_name']);
		$params['extracted'] = count($new_dunzip->getList());
		$new_dunzip->unzipAll(getcwd()."/upload");
		$data = unserialize(file_get_contents(getcwd()."/upload/data"));
	} else {
		// if not zip
		$data = unserialize(file_get_contents($_FILES['data']['tmp_name']));
	}
	if(!$data) {
		// generate xml
		xml_generator("install",$function,"e33",$params,$cfg);
	}
}

if($config_file) {
	// if theres a config file extract it
	$new_dunzip = new dUnzip2($config_file);
	$new_dunzip->getList();
	$new_dunzip->unzipAll(getcwd()."/upload/");
	$files = examinedir(getcwd()."/upload");
	// copy config settings over
	foreach($files as $value) {
		if(strpos($value,"config.inc.php") && file_exists(str_replace("upload/","",$value))) {
			insert_old_config($value,str_replace("upload/","",$value));
		}
	}
}

// load new database connection
$result = load_db_settings($dsn,$info['dbprefix'],$cfg,$info['genid'],$info['transaction']);

// include required files
require(getcwd().'/application/include/modules/settings/config.inc.php');
if($result === TRUE) {
	$conn = ADONewConnection($cfg['dsn']['0']['conn']);
	if(!$conn) {
		// generate xml
		xml_generator("install",$function,"e15",$params,$cfg);	
	} 
	$conn->SetFetchMode(ADODB_FETCH_ASSOC);
	// go tables
	$table = get_tables();
	// type replace
	if($type_replace) {
		$search = array_keys($type_replace);
		$replace = array_values($type_replace);
	}
	$tables = array_keys($table);
	$dbtables = $conn->MetaTables('TABLES',FALSE);
	// check if tables exists and columns
	foreach($tables as $value) {
		$tablename = $cfg['dsn']['0']['prefix'].$value;
		$tablename_upper = strtoupper($tablename);
		if(!in_array($tablename,$dbtables) && !in_array($tablename_upper,$dbtables)) {
			$sql_statement = create_sql_table($cfg['dsn']['0']['prefix'],$value,$table[$value],$search,$replace,$supports_unique,$supports_references);
			$conn->Execute($sql_statement);
			if ($conn->ErrorMsg()) {
				// An error occurred creating the tables 
				$error_code[] = "e18";
				// extra info for debuging
				$error_code[] = "ERROR :".$conn->ErrorMsg();
				$error_code[] = "SQL :".$sql_statement;
				$conn->close();
				// generate xml
				xml_generator("install",$function,$error_code,$params,$cfg);
			}
		}
		// check columns
		$ado = $conn->MetaColumnNames($tablename);
		foreach($table[$value] as $key1 => $value1) {
			if($key1 && !in_array($key1,$ado)) {
				// column does not exist
				$sqlstr = "ALTER TABLE ".$tablename." ADD ".$key1." ".str_replace($search,$replace,$value1[0]);
				if($value1[1] && $value1[1] !== FALSE) {
					$sqlstr.= " default '".$value1[1]."'";
				}
				if($value1[2]) {
					$sqlstr.= " NOT NULL ";
				}
				if($value1[3] && $supports_unique) {
					$sqlstr.= " UNIQUE ";
				}
				// FOREIGN KEY
				if($value1[4] && $supports_references) {
					$statement.= " references ".$cfg['dsn']['0']['prefix'].$value1[4]."(id)"; 
				}
				$conn->Execute($sqlstr);
				if ($conn->ErrorMsg()) {
					// An error occurred creating the column 
					$error_code[] = "e36";
					// extra info for debuging
					$error_code[] = "ERROR :".$conn->ErrorMsg();
					$error_code[] = "SQL :".$sqlstr;
					$conn->close();
					// generate xml
					xml_generator("install",$function,$error_code,$params,$cfg);
				}
			}
		}
	}
	$cfg['file'] = getcwd().'/application/include/';
	$cfg['directory'] = getcwd().'/application';
	// get the themes
	$themes = get_themes();
	// insert data
	if($data) {
		$data_tables = array_keys($data);
		// start transaction
		$conn->StartTrans();
		// go through each table
		foreach($tables as $value) {
			if(in_array($value,$data_tables)) {
				$rows = explode("\n", $data[$value]);
				$colname = explode("\t",array_shift($rows));
				while($rows) {
					$tuple = explode("\t",array_shift($rows));
					foreach($colname as $key1 => $value1) {
						if(trim($value1) !== "" && isset($tuple[$key1]) && trim($tuple[$key1]) !== "") {	
							$insert[strtolower(trim($value1))] = trim($tuple[$key1]);
						}
					}
					if($insert && array_values($insert)) {
						if($value == "message_schedule") {
							$body = $insert['body'];
							unset($insert['body']);	
						}
						if($value == "attachment") {
							$content = $insert['content'];
							unset($insert['content']);	
						}
						// upgrading from version 0.8 and below
						if($value == "tender" && $insert['classification'] == "rfq") {
							$insert['classification'] = "tender";
						}
						// make sure user theme exists
						if($value == "users" && !in_array($insert['theme'],$theme)) {
							$insert['theme'] = $cfg['default'];
						}
						// upgrading from version 0.9.3 and below
						if($value == "service_rating") {
							$value = "supplier_rating";
						}
						if($value == "supplier_rating") {
							if($insert['first']) {
								$insert['first_rate'] = $insert['first'];
								unset($insert['first']);
							}
							if($insert['second']) {
								$insert['second_rate'] = $insert['second'];
								unset($insert['second']);
							}
							if($insert['third']) {
								$insert['third_rate'] = $insert['third'];
								unset($insert['third']);
							}
							if($insert['fourth']) {
								$insert['fourth_rate'] = $insert['fourth'];
								unset($insert['fourth']);
							}
							if($insert['fifth']) {
								$insert['fifth_rate'] = $insert['fifth'];
								unset($insert['fifth']);
							}
							if($insert['comment']) {
								$insert['rating_comment'] = $insert['comment'];
								unset($insert['comment']);
							}
						}
						// insert into database each row
						$result = $conn->Replace($cfg['dsn']['0']['prefix'].$value,$insert,"id",TRUE);
						if ($conn->ErrorMsg()) {
							// instantiate the error class and log
							$new_error = new error;
							$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg()." Result:".$result;
							$new_error->log("SQL","critical",$error_text,$cfg);
				       	}
				       	// attachment content
				       	if($content) {
					       	$where = "id = ".$insert['id'];
					       	// execute the update
							$conn->UpdateBlob($cfg['dsn']['0']['prefix'].$value,"content",$content,$where);
							if ($conn->ErrorMsg()) {
								// instantiate the error class and log
								$new_error = new error;
								$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg()." Table:".$value;
								$new_error->log("SQL","critical",$error_text,$cfg);
					       	}
							unset($content);
				       	}
				       	// message body
				       	if($body) {
					       	$where = "id = ".$insert['id'];
					       	// execute the update
							$conn->UpdateBlob($cfg['dsn']['0']['prefix'].$value,"body",$body,$where);
							if ($conn->ErrorMsg()) {
								// instantiate the error class and log
								$new_error = new error;
								$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg()." Table:".$value;
								$new_error->log("SQL","critical",$error_text,$cfg);
					       	}
							unset($body);
				       	}
					}
					unset($insert);
				}
				unset($rows);
			}
		}
		// end transaction
		$conn->CompleteTrans();
	}
	// check if an admin exists
	$sqlstr = "SELECT * FROM ".$cfg['dsn']['0']['prefix']."users WHERE classification = '3' and permission = '2' and status != '0' ";
	$all = $conn->GetAll($sqlstr);
	$conn->Close();// reset session
	unset($_SESSION['ts_id']);
	if($all) {
		xml_generator("session","login","",$params,$cfg);
	} else {
		// no administrator
		xml_generator("install","newinstall_admin","",$params,$cfg);
	}
	// done
} else {
	// generate xml
	xml_generator("install",$function,$result,$params,$cfg);	
}
?>