<?php

$dal_info = array();

/**
 * User API function
 * @param String sql
 */
function UsersTableName()
{
	global $cman;
	$connection = $cman->getForLogin();
	return $connection->addTableWrappers("tb_usuarios");
}

/**
 * User API function
 * It uses the default db connection
 * @param String dalSQL
 */
function CustomQuery($dalSQL)
{
	$connection = getDefaultConnection();
	$result = $connection->query( $dalSQL );
	if($result)
		return $result;
}

/**
 * User API function
 * It uses the default db connection 
 * @param String sql
 */
function DBLookup($sql)
{
	$connection = getDefaultConnection();
	$data = $connection->query( $sql )->fetchAssoc();

	if( $data )
		return reset($data);
	  
	return null;
}

/**
  * Data Access Layer.
  */
class tDAL
{
	var $tblfatto_db2026_at_localhost__dbw_cmggf;
	var $tblfatto_db2026_at_localhost__dbw_cmmobra;
	var $tblfatto_db2026_at_localhost__dbw_despesas;
	var $tblfatto_db2026_at_localhost__dbw_faturados;
	var $tblfatto_db2026_at_localhost__dbw_mintrabalhado;
	var $tblfatto_db2026_at_localhost__dbw_mkps;
	var $tblfatto_db2026_at_localhost__dbw_nfaturados;
	var $tblfatto_db2026_at_localhost__dbw_oftotal;
	var $tblfatto_db2026_at_localhost__dbw_resumo_calculo;
	var $tblfatto_db2026_at_localhost__fatto_2026_uggroups;
	var $tblfatto_db2026_at_localhost__fatto_2026_ugmembers;
	var $tblfatto_db2026_at_localhost__fatto_2026_ugrights;
	var $tblfatto_db2026_at_localhost__grade_pdto;
	var $tblfatto_db2026_at_localhost__tb_aporte_fin;
	var $tblfatto_db2026_at_localhost__tb_categ_despesas;
	var $tblfatto_db2026_at_localhost__tb_categpdtos;
	var $tblfatto_db2026_at_localhost__tb_clientes;
	var $tblfatto_db2026_at_localhost__tb_componentes;
	var $tblfatto_db2026_at_localhost__tb_contas_desp;
	var $tblfatto_db2026_at_localhost__tb_cotacao_material;
	var $tblfatto_db2026_at_localhost__tb_custominuto;
	var $tblfatto_db2026_at_localhost__tb_despesas;
	var $tblfatto_db2026_at_localhost__tb_dist_cotas;
	var $tblfatto_db2026_at_localhost__tb_fecha_cx;
	var $tblfatto_db2026_at_localhost__tb_ficha_tecnica;
	var $tblfatto_db2026_at_localhost__tb_fornecedores;
	var $tblfatto_db2026_at_localhost__tb_ftec_blocos;
	var $tblfatto_db2026_at_localhost__tb_margemlucro;
	var $tblfatto_db2026_at_localhost__tb_materiais;
	var $tblfatto_db2026_at_localhost__tb_mcalculo;
	var $tblfatto_db2026_at_localhost__tb_metricas;
	var $tblfatto_db2026_at_localhost__tb_mintrabalhados;
	var $tblfatto_db2026_at_localhost__tb_negociado;
	var $tblfatto_db2026_at_localhost__tb_obrigacao_fiscal;
	var $tblfatto_db2026_at_localhost__tb_orcamento_producao;
	var $tblfatto_db2026_at_localhost__tb_pedidos;
	var $tblfatto_db2026_at_localhost__tb_peditens;
	var $tblfatto_db2026_at_localhost__tb_produtos;
	var $tblfatto_db2026_at_localhost__tb_provisao_caixa;
	var $tblfatto_db2026_at_localhost__tb_usuarios;
	var $tblfatto_db2026_at_localhost__tb_varggf;
	var $lstTables;
	var $Table = array();

	function FillTablesList()
	{
		if($this->lstTables)
			return;
		$this->lstTables[] = array("name" => "dbw_cmggf", "varname" => "fatto_db2026_at_localhost__dbw_cmggf", "altvarname" => "dbw_cmggf", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "dbw_cmmobra", "varname" => "fatto_db2026_at_localhost__dbw_cmmobra", "altvarname" => "dbw_cmmobra", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "dbw_despesas", "varname" => "fatto_db2026_at_localhost__dbw_despesas", "altvarname" => "dbw_despesas", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "dbw_faturados", "varname" => "fatto_db2026_at_localhost__dbw_faturados", "altvarname" => "dbw_faturados", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "dbw_mintrabalhado", "varname" => "fatto_db2026_at_localhost__dbw_mintrabalhado", "altvarname" => "dbw_mintrabalhado", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "dbw_mkps", "varname" => "fatto_db2026_at_localhost__dbw_mkps", "altvarname" => "dbw_mkps", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "dbw_nfaturados", "varname" => "fatto_db2026_at_localhost__dbw_nfaturados", "altvarname" => "dbw_nfaturados", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "dbw_oftotal", "varname" => "fatto_db2026_at_localhost__dbw_oftotal", "altvarname" => "dbw_oftotal", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "dbw_resumo_calculo", "varname" => "fatto_db2026_at_localhost__dbw_resumo_calculo", "altvarname" => "dbw_resumo_calculo", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "fatto_2026_uggroups", "varname" => "fatto_db2026_at_localhost__fatto_2026_uggroups", "altvarname" => "fatto_2026_uggroups", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "fatto_2026_ugmembers", "varname" => "fatto_db2026_at_localhost__fatto_2026_ugmembers", "altvarname" => "fatto_2026_ugmembers", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "fatto_2026_ugrights", "varname" => "fatto_db2026_at_localhost__fatto_2026_ugrights", "altvarname" => "fatto_2026_ugrights", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "grade_pdto", "varname" => "fatto_db2026_at_localhost__grade_pdto", "altvarname" => "grade_pdto", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_aporte_fin", "varname" => "fatto_db2026_at_localhost__tb_aporte_fin", "altvarname" => "tb_aporte_fin", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_categ_despesas", "varname" => "fatto_db2026_at_localhost__tb_categ_despesas", "altvarname" => "tb_categ_despesas", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_categpdtos", "varname" => "fatto_db2026_at_localhost__tb_categpdtos", "altvarname" => "tb_categpdtos", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_clientes", "varname" => "fatto_db2026_at_localhost__tb_clientes", "altvarname" => "tb_clientes", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_componentes", "varname" => "fatto_db2026_at_localhost__tb_componentes", "altvarname" => "tb_componentes", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_contas_desp", "varname" => "fatto_db2026_at_localhost__tb_contas_desp", "altvarname" => "tb_contas_desp", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_cotacao_material", "varname" => "fatto_db2026_at_localhost__tb_cotacao_material", "altvarname" => "tb_cotacao_material", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_custominuto", "varname" => "fatto_db2026_at_localhost__tb_custominuto", "altvarname" => "tb_custominuto", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_despesas", "varname" => "fatto_db2026_at_localhost__tb_despesas", "altvarname" => "tb_despesas", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_dist_cotas", "varname" => "fatto_db2026_at_localhost__tb_dist_cotas", "altvarname" => "tb_dist_cotas", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_fecha_cx", "varname" => "fatto_db2026_at_localhost__tb_fecha_cx", "altvarname" => "tb_fecha_cx", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_ficha_tecnica", "varname" => "fatto_db2026_at_localhost__tb_ficha_tecnica", "altvarname" => "tb_ficha_tecnica", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_fornecedores", "varname" => "fatto_db2026_at_localhost__tb_fornecedores", "altvarname" => "tb_fornecedores", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_ftec_blocos", "varname" => "fatto_db2026_at_localhost__tb_ftec_blocos", "altvarname" => "tb_ftec_blocos", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_margemlucro", "varname" => "fatto_db2026_at_localhost__tb_margemlucro", "altvarname" => "tb_margemlucro", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_materiais", "varname" => "fatto_db2026_at_localhost__tb_materiais", "altvarname" => "tb_materiais", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_mcalculo", "varname" => "fatto_db2026_at_localhost__tb_mcalculo", "altvarname" => "tb_mcalculo", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_metricas", "varname" => "fatto_db2026_at_localhost__tb_metricas", "altvarname" => "tb_metricas", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_mintrabalhados", "varname" => "fatto_db2026_at_localhost__tb_mintrabalhados", "altvarname" => "tb_mintrabalhados", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_negociado", "varname" => "fatto_db2026_at_localhost__tb_negociado", "altvarname" => "tb_negociado", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_obrigacao_fiscal", "varname" => "fatto_db2026_at_localhost__tb_obrigacao_fiscal", "altvarname" => "tb_obrigacao_fiscal", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_orcamento_producao", "varname" => "fatto_db2026_at_localhost__tb_orcamento_producao", "altvarname" => "tb_orcamento_producao", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_pedidos", "varname" => "fatto_db2026_at_localhost__tb_pedidos", "altvarname" => "tb_pedidos", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_peditens", "varname" => "fatto_db2026_at_localhost__tb_peditens", "altvarname" => "tb_peditens", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_produtos", "varname" => "fatto_db2026_at_localhost__tb_produtos", "altvarname" => "tb_produtos", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_provisao_caixa", "varname" => "fatto_db2026_at_localhost__tb_provisao_caixa", "altvarname" => "tb_provisao_caixa", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_usuarios", "varname" => "fatto_db2026_at_localhost__tb_usuarios", "altvarname" => "tb_usuarios", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
		$this->lstTables[] = array("name" => "tb_varggf", "varname" => "fatto_db2026_at_localhost__tb_varggf", "altvarname" => "tb_varggf", "connId" => "fatto_db2026_at_localhost", "schema" => "", "connName" => "db_fatto26 at localhost");
	}

	/**
      * Returns table object by table name.
      * @intellisense
      */
	function & Table($strTable, $schema = "", $connName = "")
	{
		$this->FillTablesList();
		foreach($this->lstTables as $tbl)
		{
			if(strtoupper($strTable)==strtoupper($tbl["name"]) &&
				( $schema == "" || strtoupper($schema) == strtoupper($tbl["schema"]) ) &&
				($connName == "" || strtoupper($connName) == strtoupper($tbl["connName"]) ) )
			{
				$this->CreateClass($tbl);
				return $this->{"tbl".$tbl["varname"]};
			}
		}
//	check table names without dbo. and other prefixes
		foreach($this->lstTables as $tbl)
		{
			if(strtoupper(cutprefix($strTable))==strtoupper(cutprefix($tbl["name"])))
			{
				$this->CreateClass($tbl);
				return $this->{"tbl".$tbl["varname"]};
			}
		}
		$dummy=null;
		return $dummy;
	}
	
	function CreateClass(&$tbl)
	{
		if($this->{"tbl".$tbl["varname"]})
			return;
//	load table info
		global $dal_info;
		include(getabspath("include/dal/".($tbl["varname"]).".php"));
//	create class and object

		$classname="class_".$tbl["varname"];
		$str = "class ".$classname." extends tDALTable  {";
		foreach($dal_info[$tbl["varname"]] as $fld)
		{
			$str.=' var $'.$fld["varname"].'; ';
		}
		
		$tableName = $tbl["name"];
		if( $tbl["schema"] )
			$tableName = $tbl["schema"] . "." . $tbl["name"];
		$str.=' function __construct()
			{
				$this->m_TableName = \''.escapesq( $tableName ).'\';
				$this->infoKey = \'' . $tbl["varname"] . '\';
				$this->setConnection(\''. $tbl["connId"] .'\');
			}
		};';
		eval($str);
		$this->{"tbl".$tbl["varname"]} = new $classname;
		$this->{$tbl["altvarname"]} = $this->{"tbl".$tbl["varname"]};
		$this->Table[$tbl["name"]]=&$this->{"tbl".$tbl["varname"]};
	}
	
	/**
      * Returns list of table names.
      * @intellisense
      */
	function GetTablesList()
	{
		$this->FillTablesList();
		$res=array();
		foreach($this->lstTables as $tbl)
			$res[]=$tbl["name"];
		return $res;
	}
	
	/**
      * Get list of table fields by table name.
      * @intellisense
      */
	function GetFieldsList($table)
	{
		$tbl = $this->Table($table);
		return $tbl->GetFieldsList();
	}
	
	/**
      * Get field type by table name and field name.
      * @intellisense
      */
	function GetFieldType($table,$field)
	{
		$tbl = $this->Table($table);
		return $tbl->GetFieldType($field);
	}

	/**
      * Get table key fields by table name.
      * @intellisense
      */
	function GetDBTableKeys($table)
	{
		$tbl = $this->Table($table);
		return $tbl->GetDBTableKeys();
	}
}

$dal = new tDAL;

/**
 * Data Access Layer table class.
 */ 
class tDALTable
{
	var $m_TableName;
	var $infoKey;
	var $Param = array();
	var $Value = array();
	/**
	 * @type Connection
	 */
	var $_connection;
	
	/**
	 * Set the connection property
	 * @param String connId
	 */
	function setConnection( $connId )
	{
		global $cman;
		$this->_connection = $cman->byId( $connId );
	}
	
	/**
      * Get table key fields.
      * @intellisense
      */
	function GetDBTableKeys()
	{
		global $dal_info;
		if( !array_key_exists($this->infoKey, $dal_info) || !is_array($dal_info[ $this->infoKey ]) )
			return array();
		
		$ret = array();
		foreach($dal_info[ $this->infoKey ] as $fname=>$f)
		{
			if( @$f["key"] )
				$ret[] = $fname;
		}
		return $ret;
	}
	
	/**
      * Get list of table fields.
      * @intellisense
      */
	function GetFieldsList()
	{
		global $dal_info;
		return array_keys( $dal_info[ $this->infoKey ] );
	}

	/**
      * Get field type.
      * @intellisense
      */
	function GetFieldType($field)
	{
		global $dal_info;
		
		if( !array_key_exists( $field, $dal_info[ $this->infoKey ]) )
			return 200;
			
		return $dal_info[ $this->infoKey ][ $field ]["type"];
	}
	
	/**
	 *
	 */
	function PrepareValue($value, $type)
	{
		if( $this->_connection->dbType == nDATABASE_Oracle || $this->_connection->dbType == nDATABASE_DB2 || $this->_connection->dbType == nDATABASE_Informix )
		{
			if( IsBinaryType($type) )
			{
				if( $this->_connection->dbType == nDATABASE_Oracle )
					return "EMPTY_BLOB()";
					
				return "?";
			}
			
			if( $this->_connection->dbType == nDATABASE_Informix  && IsTextType($type) )
				return "?";
		}
	
		if( IsDateFieldType($type) )
		{
			if( !$value )
				return "null";
			else
				$this->_connection->addDateQuotes( $value );
		}
		
		if( NeedQuotes($type) )
			return $this->_connection->prepareString( $value );

		return 0 + $value;
	}
	
	/**
      * Get table name.
      * @intellisense
      */
	function TableName()
	{
		return $this->_connection->addTableWrappers( $this->m_TableName );
	} 

	/**
	 * @param Array blobs
	 * @param String dalSQL
	 * @param Array tableinfo
	 */
	protected function Execute_Query($blobs, $dalSQL, $tableinfo)
	{		
		$blobTypes = array();
		if( $this->_connection->dbType == nDATABASE_Informix )
		{		
			foreach( $blobs as $fname => $fvalue )
			{
				$blobTypes[ $fname ] = $tableinfo[ $fname ]["type"];
			}
		}

		$this->_connection->execWithBlobProcessing( $dalSQL, $blobs, $blobTypes );
	}

	/**
      * Add new record to the table.
      * @intellisense
      */
	function Add() 
	{
		global $dal_info;
		
		$insertFields = "";
		$insertValues = "";
		$tableinfo = &$dal_info[ $this->infoKey ];
		$blobs = array();
		//	prepare parameters		
		foreach($tableinfo as $fieldname => $fld)
		{
			if( isset($this->{$fld['varname']}) )
			{
				$this->Value[ $fieldname ] = $this->{$fld['varname']};
			}
			
			foreach($this->Value as $field => $value)
			{
				if( strtoupper($field) != strtoupper($fieldname) )
					continue;
					
				$insertFields.= $this->_connection->addFieldWrappers( $fieldname ).",";
				$insertValues.= $this->PrepareValue($value,$fld["type"]) . ",";
				
				if( $this->_connection->dbType == nDATABASE_Oracle || $this->_connection->dbType == nDATABASE_DB2 || $this->_connection->dbType == nDATABASE_Informix )
				{
					if( IsBinaryType( $fld["type"] ) )
						$blobs[ $fieldname ] = $value;
						
					if( $this->_connection->dbType == nDATABASE_Informix && IsTextType( $fld["type"] ) )
						$blobs[ $fieldname ] = $value;
				}
				break;
			}
		}
		//	prepare and exec SQL
		if( $insertFields != "" && $insertValues != "" )		
		{
			$insertFields = substr($insertFields, 0, -1);
			$insertValues = substr($insertValues, 0, -1);
			$dalSQL = "insert into ".$this->_connection->addTableWrappers( $this->m_TableName )." (".$insertFields.") values (".$insertValues.")";
			$this->Execute_Query($blobs, $dalSQL, $tableinfo);
		}
		//	cleanup		
	    $this->Reset();
	}

	/**
      * Query all records from the table.
      * @intellisense
      */
	function QueryAll()
	{
		$dalSQL = "select * from ".$this->_connection->addTableWrappers( $this->m_TableName );
		return $this->_connection->query( $dalSQL );
	}

	/**
      * Do a custom query on the table.
      * @intellisense
      */
	function Query($swhere = "", $orderby = "")
	{
		if ($swhere)
			$swhere = " where ".$swhere;
			
		if ($orderby)
			$orderby = " order by ".$orderby;
			
		$dalSQL = "select * from ".$this->_connection->addTableWrappers( $this->m_TableName ).$swhere.$orderby;
		return $this->_connection->query( $dalSQL );
	}

	/**
      * Delete a record from the table.
      * @intellisense
      */
	function Delete()
	{
		global $dal_info;
		
		$deleteFields = "";
		$tableinfo = &$dal_info[ $this->infoKey ];
		//	prepare parameters		
		foreach($tableinfo as $fieldname => $fld)
		{
			if( isset($this->{$fld['varname']}) )
			{
				$this->Param[ $fieldname ] = $this->{$fld['varname']};
			}
			
			foreach($this->Param as $field => $value)
			{
				if( strtoupper($field) != strtoupper($fieldname) )
					continue;
					
				$deleteFields.= $this->_connection->addFieldWrappers( $fieldname )."=". $this->PrepareValue($value, $fld["type"]) . " and ";
				break;
			}
		}
		//	do delete
		if ($deleteFields)
		{
			$deleteFields = substr($deleteFields, 0, -5);
			$dalSQL = "delete from ".$this->_connection->addTableWrappers( $this->m_TableName )." where ".$deleteFields;
			$this->_connection->exec( $dalSQL );
		}
	
		//	cleanup
	    $this->Reset();
	}

	/**
      * Reset table object.
      * @intellisense
      */
	function Reset()
	{
		global $dal_info;
		
		$this->Value = array();
		$this->Param = array();
		
		$tableinfo = &$dal_info[ $this->infoKey ];
		//	prepare parameters		
		foreach($tableinfo as $fieldname => $fld)
		{
			unset($this->{$fld["varname"]});
		}
	}	

	/**
      * Update record in the table.
      * @intellisense
      */
	function Update()
	{
		global $dal_info;
		
		$tableinfo = &$dal_info[ $this->infoKey ];
		$updateParam = "";
		$updateValue = "";
		$blobs = array();

		foreach($tableinfo as $fieldname => $fld)
		{
			$command = 'if(isset($this->'.$fld['varname'].')) { ';
			if( $fld["key"] )
				$command.= '$this->Param[\''.escapesq($fieldname).'\'] = $this->'.$fld['varname'].';';
			else
				$command.= '$this->Value[\''.escapesq($fieldname).'\'] = $this->'.$fld['varname'].';';
			$command.= ' }';
			
			eval($command);
			
			if( !$fld["key"] && !array_key_exists( strtoupper($fieldname), array_change_key_case($this->Param, CASE_UPPER) ) )
			{
				foreach($this->Value as $field => $value)
				{
					if( strtoupper($field) != strtoupper($fieldname) )
						continue;
						
					$updateValue.= $this->_connection->addFieldWrappers( $fieldname )."=".$this->PrepareValue($value, $fld["type"]) . ", ";
					
					if( $this->_connection->dbType == nDATABASE_Oracle || $this->_connection->dbType == nDATABASE_DB2 || $this->_connection->dbType == nDATABASE_Informix )
					{
						if( IsBinaryType( $fld["type"] ) )
							$blobs[ $fieldname ] = $value;
							
						if( $this->_connection->dbType == nDATABASE_Informix && IsTextType( $fld["type"] ) )	
							$blobs[ $fieldname ] = $value;		
					}
					break;
				}
			}
			else
			{
				foreach($this->Param as $field=>$value)
				{
					if( strtoupper($field) != strtoupper($fieldname) )
						continue;
						
					$updateParam.= $this->_connection->addFieldWrappers( $fieldname )."=".$this->PrepareValue($value, $fld["type"]) . " and ";
					break;
				}
			}
		}

		//	construct SQL and do update	
		if ($updateParam)
			$updateParam = substr($updateParam, 0, -5);
		if ($updateValue)
			$updateValue = substr($updateValue, 0, -2);
			
		if ($updateValue && $updateParam)
		{
			$dalSQL = "update ".$this->_connection->addTableWrappers( $this->m_TableName )." set ".$updateValue." where ".$updateParam;
			$this->Execute_Query($blobs, $dalSQL, $tableinfo);
		}

		//	cleanup
		$this->Reset();
	}
	
	/**
	 * Select one or more records matching the condition
	 */
	function FetchByID()
	{
		global $dal_info;
		$tableinfo = &$dal_info[ $this->infoKey ];

		$dal_where = "";
		foreach($tableinfo as $fieldname => $fld)
		{
			$command = 'if(isset($this->'.$fld['varname'].')) { ';
			$command.= '$this->Value[\''.escapesq($fieldname).'\'] = $this->'.$fld['varname'].';';
			$command.= ' }';
			
			eval($command);
			
			foreach($this->Param as $field => $value)
			{
				if( strtoupper($field) != strtoupper($fieldname) )
					continue;
					
				$dal_where.= $this->_connection->addFieldWrappers( $fieldname )."=".$this->PrepareValue($value, $fld["type"]) . " and ";
				break;
			}
		}
		// cleanup
		$this->Reset();
		// construct and run SQL
		if ($dal_where)
			$dal_where = " where ".substr($dal_where, 0, -5);
			
		$dalSQL = "select * from ".$this->_connection->addTableWrappers( $this->m_TableName ).$dal_where;
		return $this->_connection->query( $dalSQL );
	}
}

function cutprefix($table)
{
	$pos = strpos($table,".");
	if( $pos === false )
		return $table;
		
	return substr($table, $pos + 1);
}

function escapesq($str)
{
	return str_replace(array("\\","'"),array("\\\\","\\'"),$str);
}

?>