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

/**
* Database class
* @package TenderSystem
* @subpackage generic
* @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...");
}

Class database {
	// set the paramaters
	var $error;
	
	function get_next_id($table,$cfg,$conn,$startID=FALSE) {
		// determine if table present
		if (!$table) {
			// no table present
			$this->error[] = "69";
		}
		$this->parse_sql($table,$cfg);
		
		if($cfg['dsn']['0']['next_id'] == "sequence") {
			// use sequences
			if(is_numeric($startID)) {
				return $conn->GenID("sequence_".$table,$startID);
			} else {
				return $conn->GenID("sequence_".$table);
			}
		} else {
		     // Query database to find out provinces and areas
	   		$sqlstr = "SELECT max(".$table.".id) ";
			$sqlstr.= "FROM ".$table." ";
			$one = $conn->GetOne($sqlstr);
	        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();
				$new_error->log("SQL","critical",$error_text,$cfg);
				// set the response error
				$this->error[] = "286";
				// response
				return FALSE;
	        } else {
	        	if (!$one) {
					// response
					$next_id = "1";
		        } else {
					// return response
					$next_id = $one + 1;
				}
				if ($startID && $next_id < $startID) {
					$next_id = $startID;
				}
				return $next_id;
	        }
		}
	}

	/**
	 * Use carefully because the replaces all ~ with the database prefix
	 */
	function parse_sql(&$sqlstr,&$cfg) {
		$sqlstr = str_replace("~",$cfg['dsn']['0']['prefix'],$sqlstr);
	}

	function setTime($name,&$params,$time_now,&$cfg) {
		if(!$time_now) {
			$time_now = ts_time($cfg);
		}
		$params[$name."_date"] = date("Y-m-d",$time_now);
		$params[$name."_time"] = date("H:i:s",$time_now);
	}

	function convertTime(&$all,&$cfg) {
		foreach($all as $row => $value) {
			foreach($value as $col => $value1) {
				if($value1) {
					if(strpos($col,"_date")) {
						list($year,$month,$day) = sscanf(str_replace(array("-"," "),"",$value1),'%4s%2s%2s');
						if($year && $month && $day) {
							$all[$row][$col] = date($cfg['date']['format'], mktime(0,0,0,$month,$day,$year));
						} else {
							$all[$row][$col] = "Date Unknown";
						}
					} elseif(strpos($col,"_time")) {
						list($hour,$minute,$second) = sscanf(str_replace(array(":"," "),"",$value1),'%2s%2s%2s');
						if($hour !== NULL || $minute !== NULL || $second !== NULL) {
							$all[$row][$col] = date($cfg['time']['format'], mktime($hour,$minute,$second));
						} else {
							$all[$row][$col] = "Time Unknown";
						}
					} elseif(strpos($col,"_until")) {
						list($year,$month,$day) = sscanf(str_replace(array("-"," "),"",$value1),'%4s%2s%2s');
						if($year && $month && $day) {
							$all[$row][$col] = date($cfg['date']['format'], mktime(0,0,0,$month,$day,$year));
						} else {
							$all[$row][$col] = "Date Unknown";	
						}
					}
				}
			}
		}
	}

	function convertSingleTime(&$row,&$cfg) {
		foreach ($row as $key => $value) {
			if($value) {
				if(strpos($key,"_date")) {
					list($year,$month,$day) = sscanf(str_replace(array("-"," "),"",$value),'%4s%2s%2s');
					if($year !== NULL && $month !== NULL && $day !== NULL) {
						$row[$key] = date($cfg['date']['format'], mktime("0","0","0",$month,$day,$year));
					} else {
						$row[$key] = "Date Unknown";	
					}
				} elseif(strpos($key,"_time")) {
					list($hour,$minute,$second) = sscanf(str_replace(array(":"," "),"",$value),'%2s%2s%2s');
					if($hour !== NULL || $minute !== NULL || $second !== NULL) {
						$row[$key] = date($cfg['time']['format'], mktime($hour,$minute,$second));
					} else {
						$row[$key] = "Time Unknown";
					}
				}
			}
		}
	}
	
	/**
	 * Updates a row
	 * 
	 * @param string table_name The Table Name
	 * @param array update Update Information
	 * @param string where Where Statement
	 * @param mixed cfg The Config settings of tendersystem
	 * @param [ADOConnection] conn The connection to the database
	 *
	 * @param boolean TRUE on Success or FALSE on error  
	 */
	function update_table($table_name,$update,$where,$cfg,$conn) {
		if (!$table_name){
			// missing table name
			$this->error[] = "320";
		}
		if (!$update){
			// missing update information
			$this->error[] = "230";
		}
		// Check if main parameters exist 
		if (!$where){
			// missing where clause
			$this->error[] = "231";
		}
		// errors 
		if(!empty($this->error)){
			return FALSE;
		}
		unset($update['id']);
		// the table name
		$this->parse_sql($table_name,$cfg);
		// execute
		$conn->AutoExecute($table_name,$update,"UPDATE",$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();
			$new_error->log("SQL","critical",$error_text,$cfg);
			// error occurred while updating information on database
			$this->error[] = "1066";
			// response
			return FALSE;
      	}
      	return TRUE;
	}
}
?>