<?php
/*
EasyGUI XP is free software released under the terms of the following BSD license.

Copyright (c) 2005,2006 Gaetan Lauff (glauff@plansoft.de)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

- Redistributions of source code must retain the above copyright notice, 
this list of conditions and the following disclaimer. 

- Redistributions in binary form must reproduce the above copyright notice, 
this list of conditions and the following disclaimer in the documentation 
and/or other materials provided with the distribution.

- Neither the name of the developer nor the names of its contributors may 
be used to endorse or promote products derived from this software without 
specific prior written permission. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/**
 * DB Data Handler for EasyGUI XP System
 * Updates, inserts and deletes from Database
 *
 * If an application has simple database transactions to perform
 * this class handles all database stuff for you. The only thing you
 * have to take care of is that all fields you want to update or insert
 * are defined in the dlg_vars table.
 * For more information on how to do this please consult the 
 * EasyGUI XP User's Guide.
 *
 * @author Gaetan Lauff <glauff@plansoft.de>
 * @version	XP $Id: class.ek_datahandler.php 50 2006-03-10 10:04:54Z glauff $
 * @package dataspace
 */
class EK_DataHandler extends EK_Handler 
{
	/**
	 * @var array
	 */
	var $transaction = array();
	
	/**
	 * Sets the Insert Mode
	 *
	 * @return void
	 *
	 * @access public
	 */
	function dbInsert()
	{
		$dlgId		= $this->webapp->getTargetDlgId();
		
		if ( !$dlgId ) {
			$dlgId = $this->webapp->getDlgId();
		}
		
		$dlgKeys 	= $this->webapp->getDlgKeys( $dlgId );
		
		foreach ( $dlgKeys as $table => $row ) {
			$key = explode( '.', $row['key_ctrl'] );
			$sessionKey	= $dlgId;
			
			if (empty($key[1])) {
				$dlgKey = $key[0];
			} else {
				$sessionKey	= $key[0];
				$dlgKey 	= $key[1];
			}
			
			if (isset($_SESSION[$sessionKey][$dlgKey]) && !empty($_SESSION[$sessionKey][$dlgKey])) {
				$_SESSION[$sessionKey][$dlgKey] = null;
			} 
			
			if ( isset($_SESSION['*'][$dlgKey]) && !empty( $_SESSION['*'][$dlgKey])) {
				$_SESSION['*'][$dlgKey] = null;
			} 
			
			if ( isset( $_SESSION[$dlgKey] ) && !empty( $_SESSION[$dlgKey] ) ) {
				$_SESSION[$dlgKey] = null;
			}
			
			$_SESSION[$dlgId]['DLG_TABLES']['PRIMARY_KEYS'][$table] = null;
			
			$sql = "SELECT * FROM dlg_table_refs WHERE reference_table='".$table."'";
			
			$result =& $this->webapp->dbHandler->Execute( $sql );
			
			while ( $_row = $result->FetchRow() ) {
				$_SESSION[$dlgId]['DLG_TABLES']['FOREIGN_KEYS'][$_row['table_name']][$_row['foreign_key']] = null;
			}
		}
		
		return true;
	}
	
	/**
	 * Updates or Inserts into the application database
	 *
	 * This Method determines whether to INSERT or UPDATE the Database.
	 *
	 * @return string	Modus
	 *
	 * @access public
	 */
	function dbUpdate()
	{
		$dlgId		= $this->webapp->getDlgId();
		$dlgKeys 	= $this->webapp->getDlgKeys( $dlgId );
		$dlgTables 	= $this->webapp->getDlgTables( $dlgId );
		
		$insertIds	= array();
		
		foreach ( $dlgTables as $table => $desc ) {
			$where 		= false;
			$values 	= array();
			
			$dbHandler 	= (!isset($desc['dsn']) || empty($desc['dsn'])) ? $this->webapp->getDefaultDbHandler() : $this->webapp->getDatabaseHandler($desc['dsn']);
			
			if (EK_DEBUG) {
				//$dbHandler->debug = true;
			}
			
			$dbHandler->StartTrans();
									
			foreach( $dlgKeys as $keytable => $row ) {
				// Fill the key table only atomar values. Arrays are serialized
				if ($table == $keytable) {
					$key = explode( '.', $row['key_ctrl'] );
					
					if (empty($key[1])) {
						$dlgKey 	= $key[0];
						$sessionKey = $row['dlg_id'];
					} else {
						$sessionKey	= $key[0];
						$dlgKey 	= $key[1];
					}
					
					$pkVal = $this->webapp->getSessionValue( $dlgKey, $sessionKey );
					$mode = ( is_null( $pkVal ) || $pkVal === false || $pkVal == '' ) ? 'INSERT' : 'UPDATE';
					
					foreach($this->webapp->dlgVars[$dlgId] as $dlgVar) {
						if ( $dlgVar['ctrl_db_table'] == $table) {
							if ( $dlgVar['ctrl_db_insert'] && $mode == 'UPDATE' ) {
								continue;
							}
								
							$value = $this->webapp->dbValues[$dlgId][$dlgVar['ctrl_id']];
							
							if ( is_array( $value ) ) {
								$value = serialize( $value );
							}
							
							if ( !is_null( $dlgVar['ctrl_db_field'] ) ) {
								$values[$dlgVar['ctrl_db_field']] = $value;
							}
						}
					}
					
					if ( $mode == 'UPDATE' ) {
						$where = $this->getPrimaryKeyField( $table, $dbHandler ) . "='" . $pkVal . "'";
					}
					
					$dbHandler->AutoExecute( $table, $values, $mode, $where );
					
					if ( $mode == 'INSERT' ) {
						$lastInsertId = $dbHandler->Insert_ID();
						
						if ( $lastInsertId === false ) {
							trigger_error( 'Unsupported Database', E_USER_ERROR );
						}

						$insertIds[$table]	= $lastInsertId;
						
						$keyvar = $this->webapp->getDlgVar( $sessionKey, $dlgKey );
						
						if ( $keyvar['global'] ) {
							$_SESSION['*'][$dlgKey] = $lastInsertId;
						} else { 
							$_SESSION[$sessionKey][$dlgKey] = $lastInsertId;
						}
					}
					
					continue 2;
				}
			}
			
			$sql = "SELECT * FROM dlg_table_refs WHERE table_name='".$table."'";
			$result =& $this->webapp->dbHandler->Execute( $sql );
			
			while( $row = $result->FetchRow() ) {
				$pkVal = null;
				$fkVal = null;
				$where = false;
				
				$mode 	= 'UPDATE';
				
				if (isset($_SESSION[$dlgId]['DLG_TABLES']['PRIMARY_KEYS'][$table]) && 
					!empty($_SESSION[$dlgId]['DLG_TABLES']['PRIMARY_KEYS'][$table]) ) {
						$pkVal = $_SESSION[$dlgId]['DLG_TABLES']['PRIMARY_KEYS'][$table];
					}
			
				$fk = $row['foreign_key'];
				$rt = $row['reference_table'];
				
				if ( array_key_exists( $rt, $insertIds ) ) {
					$mode 	= 'INSERT';
					$fkVal	= $insertIds[$rt];
				} else {
					if (isset( $_SESSION[$dlgId]['DLG_TABLES']['FOREIGN_KEYS'][$table][$fk] ) &&
						!empty( $_SESSION[$dlgId]['DLG_TABLES']['FOREIGN_KEYS'][$table][$fk] )) {
							$fkVal = $_SESSION[$dlgId]['DLG_TABLES']['FOREIGN_KEYS'][$table][$fk];
						}
				}
				
				if ( !is_null( $pkVal ) ) {
					$where = $this->getPrimaryKeyField( $table, $dbHandler ) . "='" . $pkVal . "'";
				} elseif ( $mode == 'UPDATE' ) {
					$where = $fk . " = '" . $fkVal . "'";
				}
				
				foreach($this->webapp->dlgVars[$dlgId] as $dlgVar) {
					if ( $dlgVar['ctrl_db_table'] == $table && isset( $this->webapp->dbValues[$dlgId][$dlgVar['ctrl_id']] )) {
						$value = $this->webapp->dbValues[$dlgId][$dlgVar['ctrl_id']];
						
						if ( is_array( $value ) ) {
							if ($mode == 'UPDATE') {
								$sql = "DELETE FROM " . $table . " WHERE " . $where;
								$dbHandler->Execute( $sql );
							}
							
							$mode = 'INSERT';
							
							foreach( $value as $idx => $val ) {
								$values 		= array();
								$values[$fk] 	= $fkVal;
								$values[$dlgVar['ctrl_db_field']] = $val;
								$dbHandler->AutoExecute( $table, $values, $mode, $where );
								unset( $values );
							}
							
							continue 3;
						}
						
						$values[$dlgVar['ctrl_db_field']] = $value;
					}
				}
				
				if ( !empty($values)) {
					$values[$fk] = $fkVal;
					$dbHandler->AutoExecute( $table, $values, $mode, $where );
				}
			}
		}
		
		if ( $dbHandler->CompleteTrans() === false ) {
			return false;
		}
		
		return $mode;
	}
	
	/**
	 * Deletes record from Database with referential integrity
	 *
	 * @return void
	 *
	 * @access public
	 */
	function dbDelete()
	{
		$dlgId 		= $this->webapp->getDlgId();
		$dlgKeys 	= $this->webapp->getDlgKeys( $dlgId );
		
		if (!empty($dlgKeys)) {
			foreach( $dlgKeys as $table => $row ) {
				$tableDesc = $this->webapp->getTableDescription( $table );
				$dbHandler = $this->webapp->getDatabaseHandler('default');
				
				if (is_array( $tableDesc ) && isset( $tableDesc['dsn'] ) && !empty( $tableDesc['dsn'] ) ) {
					$dbHandler = $this->webapp->getDatabaseHandler( $tableDesc['dsn'] );
				}
				
				$dlgId 	= $this->getDlgIdEntry( $row['key_ctrl'] );
				$dlgKey = $this->getDlgKeyEntry( $row['key_ctrl'] );
		
				$keys[] = $this->webapp->getSessionValue( $dlgKey, $dlgId );
				$pkVar = $this->getPrimaryKeyField( $table , $dbHandler );
						
				$this->delete($table, $pkVar, $keys, $dbHandler);
			}
		}
		
		return true;
	}
	
	/**
	 * This function handles the database deletes with referential integrity
	 *
	 * @param 	string	table
	 * @param 	string	refKey		Reference Key (Primary Key)
	 * @param 	array	keys		an array of Primary Key Values
	 * @param 	ref		dbHandler	a reference to the dbHandler
	 *
	 * @return 	void
	 *
	 * @internal
	 * @access 	private
	 */
	function delete($table, $refKey, $keys, &$dbHandler)
	{
		if (empty($table)) {
			return;
		}
			
		$pkVar 		= $this->getPrimaryKeyField($table, $dbHandler );
		$references = $this->webapp->getReferences( $table );
	
		if (!empty($references)) {
			$referenceKeys = null;
			
			foreach($keys as $key) {
				$whereClause[] = $pkVar . "='".$key."'";
			}

			$whereClause = implode(' OR ', $whereClause);				
			$result =& $dbHandler->Execute("SELECT " . $pkVar . " FROM " . $table . " WHERE " . $whereClause);
			
			while($key = $result->FetchRow()) {
				$referenceKeys[] = $key[$pkVar];
			}
		
			if (empty($referenceKeys)) {
				$referenceKeys = $keys;
			}
			
			foreach($references as $reference) {
				$referenceHandler = (empty($reference['dsn'])) ? $this->webapp->getDatabaseHandler('default') : $this->webapp->getDatabaseHandler($reference['dsn']);
				$this->delete($reference['table_name'], $reference['reference_key'], $referenceKeys, $referenceHandler);
			}
		}
	
		foreach($keys as $key) {
			array_push( $this->transaction, "DELETE FROM " . $table . " WHERE " . $refKey . "=" . $key . ";" );
		}
		
		$this->startTransaction( $dbHandler );
	}
	
	/**
	 * Starts a transaction
	 *
	 * @param 	object	dbHandler
	 *
	 * @access 	private
	 */
	function startTransaction( &$dbHandler )
	{
		$dbHandler->StartTrans();
		
		foreach( $this->transaction as $query ) {
			$dbHandler->Execute( $query );
		}

		$dbHandler->CompleteTrans();
	}
	
	/**
	 * Returns the Dialog Id
	 *
	 * @param 	reference	&$str
	 *	
	 * @return 	string	The Dialog Id
	 *
	 * @access 	private
	 */
	function getDlgIdEntry( &$str ) 
	{
		$key = explode( '.', $str );
			
		if (empty($key[1])) {
			return '*';
		}
		
		return $key[0];
	}
	
	/**
	 * Returns the Dialog Key
	 *
	 * @param 	reference	&$str
	 *
	 * @return 	string		The Dialog Key
	 */
	function getDlgKeyEntry( &$str )
	{
		$key = explode( '.', $str );
		
		if (empty($key[1])) {
			return $key[0];
		}
			
		return $key[1];
	}
	
	/**
	 * Returns the Primary Key value stored in the Session
	 *
	 * @param 	array	$row
	 *
	 * @return 	The Session Value for the Primary Key
	 *
	 * @access 	public
	 */
	function getPrimaryKeyValue( $row )
	{
		$dlgId 	= $this->getDlgIdEntry( $row['key_ctrl'] );
		$dlgKey = $this->getDlgKeyEntry( $row['key_ctrl'] );
				
		return $this->webapp->getSessionValue( $dlgKey, $dlgId );
	}
	
	/**
	 * Returns the Primary Key Field
	 *
	 * @param 	string	$table	Table Name
	 * @param 	refer
	 *
	 * @return mixed
	 *
	 * @access public
	 */
	function getPrimaryKeyField( $table, &$dbHandler )
	{
		$pkVars = $dbHandler->MetaPrimaryKeys( $table );
		return $pkVars[0];
	}
}
?>