<?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): __________________.                                                   |
// +---------------------------------------------------------------------------------------+

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

// Security - ensure that file never called directly
// not required if global variables are off or API is hosted on a non-public server
if (eregi(basename(__FILE__),$_SERVER['PHP_SELF'])) {
    die ("You can't access this file directly...");
}

//define adodb case
define('ADODB_ASSOC_CASE',0);

require(getcwd().'/application/include/modules/external/class/adodb/adodb.inc.php');	
require(getcwd().'/application/include/modules/generic/class/error.class.php');

function ts_time($cfg) {
	return time();
}

// install function
function do_database_dump($dsn,$prefix,$cfg,$type_replace,$unique=TRUE,$references=TRUE) {
	// Connect to the database
    $conn = &ADONewConnection($dsn);
	if (!$conn) {
		// Connection to the database could not be established
		$error_code[] = "e14";
		if($conn !== FALSE) {
			$error_code[] = $conn->ErrorMsg();
		}
	 	// generate and display the xml
		return $error_code;
	}
	// break of database type replace into a search and replace arrays
	if($type_replace) {
		$search = array_keys($type_replace);
		$replace = array_values($type_replace);
	}
	// get all the tables information
	$table = get_tables();
	$sql = array();
	// create the sql statements
	foreach($table as $key => $value) {
		if(is_array($value)) {
			$sql[] = create_sql_table($prefix,$key,$value,$search,$replace,$unique,$references);
		}
	}
	// start transaction
	$conn->StartTrans();
	// execute sql
	$result = execute_sql_files($sql,$conn);
	if($result !== TRUE) {
		$conn->CompleteTrans(FALSE);
		$conn->close();
		return $result;
	}
	// end tranasction
	$conn->CompleteTrans();
	$conn->close();
	return TRUE;
}

// create tables SQL
// also update application/include/modules/loader/api_import.php
function create_sql_table($prefix,$key,$value,$search,$replace,$unique=TRUE,$references=TRUE) {
	$statement = "";
	$id = TRUE;
	foreach($value as $key1 => $value1) {
		$statement.= " ".$key1." ".str_replace($search,$replace,$value1[0]);
		if($key1 == "id") {
			$id = FALSE;
		}
		// DEFAULT
		if(isset($value1[1]) && $value1[1] !== FALSE) {
			$statement.= " default '".$value1[1]."'";
		}
		// NULL
		if(isset($value1[2]) && $value1[2]) {
			$statement.= " NOT NULL"; 
		}
		// UNIQUE
		if(isset($value1[3]) && $value1[3] && $unique) {
			$statement.= " UNIQUE"; 
		}
		// FOREIGN KEY
		if(isset($value1[4]) && $value1[4] && $references) {
			$statement.= " references ".$prefix.$value1[4]."(id)"; 
		}
		
		$statement.= ",";
	}
	if($id) {
		$id_statement = " id ".str_replace($search,$replace,"integer")." NOT NULL,";
		$statement = " CREATE TABLE ".$prefix.$key." ( ".$id_statement.$statement;
		
	} else {
		$statement = " CREATE TABLE ".$prefix.$key." ( ".$statement;	
	}
	$statement.= " created_date ".str_replace($search,$replace,"date").",";
	$statement.= " created_time ".str_replace($search,$replace,"time").",";
	$statement.= " created_by ".str_replace($search,$replace,"integer")." default '0',";
	$statement.= " deleted_date ".str_replace($search,$replace,"date").",";
	$statement.= " deleted_time ".str_replace($search,$replace,"time").",";
	$statement.= " deleted_by ".str_replace($search,$replace,"integer")." default '0' ";
	if($id) {
		$statement.= ", PRIMARY KEY (id) ";
	}
	$statement.= " )";
	return $statement;
}

function get_tables() {
	$table = array();
	$dir = examinedir("./modules");
	// get all table information 
	foreach($dir as $value) {
		// only table files
		if(strpos($value,"/tables/") && strpos($value,".php")) {
			require($value);
		}
	}
	$final_table = array();
	$in_table = array();
	$loop = TRUE;
	$count = 0;
	// resort array so that tables with no references come first
	while($loop) {
		$tmp_table = array();
		$loop = FALSE;
		// loop through tables
		foreach($table as $key => $value) {
			// loop through columns
			$good_table = TRUE;
			// check if all tables with references are already added
			foreach($value as $key1 => $value1) {
				if(isset($value1[4]) && $value1[4] && !in_array($value1[4],$in_table) && $value1[4] !== $key) {
					// go onto next table
					$good_table = FALSE;
					break;
				}
			}
			if($good_table) {
				// table can be addded
				$final_table[$key] = $value;
				$in_table[] = $key;
			} else {
				// table can not addded
				$tmp_table[$key] = $value;
				$loop = TRUE;
			}
		}
		$table = $tmp_table;
	}
	// return correctly order table array
	return $final_table;
}

function execute_sql_files($sql,$conn) {
	foreach($sql as $key => $value) {
		$conn->Execute($value);
		if ($conn->ErrorMsg()) {
			// - Could not execute sql statement
			$error_code[] = "e18";
			// extra info for debuging
			$error_code[] = "ERROR -> ".$conn->ErrorMsg();
			$error_code[] = "SQL -> ".$value;
			$error_code[] = "Execution Number -> ".$key;
			return $error_code;
		}
	}
	return TRUE;
}

// load database settings
function load_db_settings($dsn,$prefix,$cfg,$genid = FALSE,$transaction = "FALSE") {
	// Test the dsn
	$conn = ADONewConnection($dsn);
	if(!$conn) {
		$error_code[] = "e15";
		return $error_code;
	}
	$conn->Close();
	// default settings
	if($genid !== "sequence" && $genid !== "query") {
		$genid = "query";
	}
	// file to write settings
	$file = getcwd().'/application/include/modules/settings/config.inc.php';
	if(!file_exists($file) || !is_file($file)) {
		// Api application/include/config.inc.php file is missing
		$error_code[] = "e21";
		return $error_code;
	}
	// check if readable and writable
	if(!is_readable($file) || !is_writable($file)) {
		// application/include/config.inc.php is not readable or writable
		$error_code[] = "e17";
		return $error_code;
	}
	// server location
	if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ){
	   $location = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	} else {
	   $location = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	}
	$location = str_replace("main.php","",$location);
	// all the settings
	$settings = array(
		'dsn0conn'				=> "['dsn']['0']['conn']",
		'dsn0prefix'			=> "['dsn']['0']['prefix']",
		'dsn0next_id'			=> "['dsn']['0']['next_id']",
		'dsn0transactionenable'	=> "['dsn']['0']['transaction']['enable']",
		'url'					=> "['url']"
	);
	// all the settings to write
	$newsettings = array(
		'dsn0conn'				=> $dsn,
		'dsn0prefix'			=> $prefix,
		'dsn0next_id'			=> $genid,
		'dsn0transactionenable'	=> $transaction,
		'url'					=> $location
	);
	if(!write_settings($file,$newsettings,$settings)) {
		// Cannot open file application/include/config.inc.php
		$error_code[] = "e21";
		return $error_code;
	}
	$file = getcwd().'/modules/settings/config.inc.php';
	if(!file_exists($file) || !is_file($file)) {
		// modules/settings/config.inc.php config file is missing
		$error_code[] = "e26";
		return $error_code;
	}
	// check if readable and writable
	if(!is_readable($file) || !is_writable($file)) {
		// modules/settings/config.inc.php is not readable or writable
		$error_code[] = "e27";
		return $error_code;
	}
	// all the settings
	$settings = array(
		'install'			=> "['installed']"
	);
	// all the settings to write
	$newsettings = array(
		'install'			=> "TRUE"
	);
	if(!write_settings($file,$newsettings,$settings)) {
		// Cannot open file application/include/config.inc.php
		$error_code[] = "e28";
		return $error_code;
	}
	// response
	return TRUE;
}

// load database settings
function load_password_settings($params,$cfg) {
	$file = "application/include/modules/settings/config.inc.php";
	if(!file_exists($file) || !is_file($file)) {
		// Api application/include/config.inc.php file is missing
		$error_code[] = "e19";
		return $error_code;
	}
	// check if readable and writable
	if(!is_readable($file) || !is_writable($file)) {
		// application/include/config.inc.php is not readable or writable
		$error_code[] = "e17";
		return $error_code;
	}
	// all the settings
	$settings = array(
		'passwordsaltpre'	=> "['password']['salt']['pre']",
		'passwordsaltpost'	=> "['password']['salt']['post']",
		'passwordscheme'	=> "['password']['scheme']",
		'passwordhash'		=> "['password']['hash']"
	);
	// all the settings
	$newsettings = array(
		'passwordsaltpre'	=> $params['passwordsaltpre'],
		'passwordsaltpost'	=> $params['passwordsaltpost'],
		'passwordscheme'	=> $params['passwordscheme'],
		'passwordhash'		=> $params['passwordhash']
	);
	if(!write_settings($file,$newsettings,$settings)) {
		// Cannot open file application/include/config.inc.php
		$error_code[] = "e21";
		return $error_code;
	}
	// open file for reading
	$file = getcwd()."/modules/settings/config.inc.php";
	if(!file_exists($file) || !is_file($file)) {
		// modules/settings/config.inc.php config file is missing
		$error_code[] = "e26";
		return $error_code;
	}
	// check if readable and writable
	if(!is_readable($file) || !is_writable($file)) {
		// modules/settings/config.inc.php is not readable or writable
		$error_code[] = "e27";
		return $error_code;
	}
	if(!write_settings($file,$newsettings,$settings)) {
		// Cannot open file modules/settings/config.inc.php
		$error_code[] = "e28";
		return $error_code;
	}
	// response
	return TRUE;
}
?>