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

/**
* Import module
* @package TenderSystem
* @subpackage loader
* @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...");
}

// instantiate the xml object
$new_xml = new xml;
// set the required type and permission required
$required[0]['classification'] = "3";
$required[0]['permission'] = "2";
// Security - determine if user authorised to perform transaction
$authorised = $new_security->permission_authentication($required,$user,$cfg);
// unauthorised user
if (!$authorised) {
	// instantiate the error class
	$new_error = new error;
	// proses the reponse error
	$xml = $new_error->response_xml($new_security->error,$user,$cfg);
} elseif (is_array($params['table'])) {
	// Assume it supports unique
	$unique = TRUE;
	// type replace
	$type_replace['money']	= "decimal(12,2)";
	$type_replace['percentage'] = "decimal(5,2)";
	if(strpos($cfg['dsn']['0']['conn'],"firebird") === 0) {
		$type_replace['time'] = "char(8)";
		$type_replace['inet'] = "varchar(24)";
		$type_replace['text'] = "varchar(255)";
		$unique = FALSE;
	} elseif(strpos($cfg['dsn']['0']['conn'],"mysql") === 0) {
		$type_replace['inet'] = "varchar(24)";
	} elseif(strpos($cfg['dsn']['0']['conn'],"oci8") === 0) {
		$type_replace['date'] = "char(10)";
		$type_replace['time'] = "char(8)";
		$type_replace['inet'] = "varchar(24)";
		$type_replace['text'] = "varchar(255)";
	} elseif(strpos($cfg['dsn']['0']['conn'],"postgres") === 0) {
		$type_replace['blob'] = "bytea";
		$type_replace['text'] = "varchar";
	}
	$search = array_keys($type_replace);
	$replace = array_values($type_replace);
	
	$dbtables = $conn->MetaTables('TABLES',FALSE);
	// check if tables exists and columns
	foreach($params['table'] as $key => $value) {
		$tablename = $cfg['dsn']['0']['prefix'].$key;
		$tablename_upper = strtoupper($tablename);
		if(!in_array($tablename,$dbtables) && !in_array($tablename_upper,$dbtables)) {
			$sql_statement = create_sql_table($cfg['dsn']['0']['prefix'],$key,$value,$search,$replace,$unique);
			$conn->Execute($sql_statement);
			if ($conn->ErrorMsg()) {
				// An error occurred creating the tables 
				$error_code[] = "e7";
				// extra info for debuging
				$error_code[] = "ERROR :".$conn->ErrorMsg();
				$error_code[] = "SQL :".$sql_statement;
			}
		} else {
			// check columns
			$ado = $conn->MetaColumnNames($tablename);
			foreach($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] && $unique) {
						$sqlstr.= " UNIQUE ";
					}
					$conn->Execute($sqlstr);
					if ($conn->ErrorMsg()) {
						// An error occurred creating the column 
						$error_code[] = "e7";
						// extra info for debuging
						$error_code[] = "ERROR :".$conn->ErrorMsg();
						$error_code[] = "SQL :".$sqlstr;
						// instantiate the error class and log
						$new_error = new error;
						$error_text = "SQL error in file ".__file__." on line ".__line__." Error:".$conn->ErrorMsg();
						$new_error->log("SQL","critical",$error_text,$cfg);
					}
				}
			}
		}
	}
	$xml_params['extracted'] = $params['extracted'];
	$xml = $new_xml->xml_generator("loader","import",$error_code,$xml_params,$user,$cfg);
} else {
	$xml = $new_xml->xml_generator("loader","import",$params['error'],$xml_params,$user,$cfg);
}

/**
* @todo Place function in own class
*/

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

function create_sql_table($prefix,$key,$value,$search,$replace,$unique) {
	$statement = "";
	$id = TRUE;
	foreach($value as $key1 => $value1) {
		$statement.= " ".$key1." ".str_replace($search,$replace,$value1[0]);
		if($key1 == "id") {
			$id = FALSE;
		}
		if(isset($value1[1]) && $value1[1] !== FALSE) {
			$statement.= " default '".$value1[1]."'";
		}
		
		if($value1[2]) {
			$statement.= " NOT NULL"; 
		}
		if($value1[3] && $unique) {
			$statement.= " UNIQUE"; 
		}
		$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;
}
?>