<?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.
*/

/**
 * Handler for all Database Value Fetching
 *
 * @author Gaetan Lauff <glauff@plansoft.de>
 * @version	XP $Id: class.ek_applicationhandler.php 45 2006-03-02 11:50:20Z glauff $
 * @package dataspace
 */
class EK_ApplicationHandler extends EK_Handler 
{
	/**
	 * Tries to get definition for a dlg var from dlg_vars table.
	 *
	 * First tries to get the definition from the dlg id,
	 * If it not exists the funtion tries to get the definition from the global context.
	 * If nothing is found an error is thrown.
	 *
	 * @param string	$dlgId	Dialolg Id
	 * @param string	$id		Component ID
	 *
	 * @return array
	 */
	function getDlgVar( $dlgId, $id )
	{
		$sql = "SELECT * FROM dlg_vars WHERE dlg_id='".$dlgId."' AND ctrl_id='" . $id . "'";
		$result =& $this->webapp->dbHandler->Execute( $sql );
		
		if ( $result->RecordCount() == 0 ) {
			$sql = "SELECT * FROM dlg_vars WHERE dlg_id='*' AND ctrl_id='" . $id . "'";
			$result =& $this->webapp->dbHandler->Execute( $sql );
			
			if ( $result->RecordCount() == 0 ) {
				trigger_error( 'No entry for ' . $id . ' on dlg: ' . $dlgId . ' in table dlg_vars!', E_USER_NOTICE );
				return false;
			}
		}
			
		if ($result->RecordCount() == 1) {
			return $result->FetchRow();
		}
			
		trigger_error('Duplicate Entries for ' . $id . ' on dlg: ' . $dlgId . ' in table dlg_vars!', E_USER_ERROR );
	}
	
	/**
	 * Returns all tables that have reference to to the current table
	 *
	 * @param	string	$table
	 *
	 * @return 	mixed	An array with all references to a given table, FALSE if nothing is found
	 *
	 * @access 	private
	 */
	function getReferences( $table ) 
	{
		$tables = array();
		$sql = "SELECT * FROM dlg_table_refs WHERE reference_table='" . $table . "'";
		$result =& $this->webapp->dbHandler->Execute($sql);
		
		if ($result->RecordCount() == 0) {
			return false;
		}
		
		while ($row = $result->FetchRow()) {
			$tables[] = $row;
		}
		
		return $tables;	
	}
	
	/**
	 * Tries to get the Dlg Keys for a dialog
	 *
	 * @return object	An ADODB Result Object @see ADODB_Result
	 *
	 * @access private
	 */
	function getDlgKeys( $dlgId )
	{
		$keys = array();
		
		$sql = "SELECT * FROM dlg_keys WHERE dlg_id='" . $dlgId . "'";
		$result =& $this->webapp->dbHandler->Execute( $sql );
		
		while ( $row = $result->FetchRow() ) {
			$keys[$row['key_table']] = $row;
		}
			
		return $keys;
	}
	
	/**
	 * Returns all tables that are affected in the give dialog
	 * 
	 * @param 	string	$dlgId	The Dialog Id
	 *
	 * @return 	array	An ADODB Result Object
	 *
	 * @access 	public
	 */
	function getDlgTables( $dlgId )
	{
		$tables = array();
	
		$sql = "SELECT DISTINCT t1.ctrl_db_table as table_id, t3.* FROM dlg_vars t1  
				LEFT JOIN dlg_keys t2 ON t1.ctrl_db_table = t2.key_table LEFT JOIN dlg_tables t3 ON t1.ctrl_db_table = t3.table_name WHERE t1.dlg_id='".$dlgId."' AND t2.key_table is not NULL;";
		
		$result =& $this->webapp->dbHandler->Execute( $sql );
	
		while ( $row = $result->FetchRow() ) {
			$tables[$row['table_id']] = $row;
		}
		
		$sql = "SELECT DISTINCT t1.ctrl_db_table as table_id, t3.* FROM dlg_vars t1 
				LEFT JOIN dlg_keys t2 ON t1.ctrl_db_table = t2.key_table LEFT JOIN dlg_tables t3 ON t1.ctrl_db_table = t3.table_name WHERE t1.dlg_id='".$dlgId."' AND t2.key_table is NULL;";
		
		$result =& $this->webapp->dbHandler->Execute( $sql );
		
		while ( $row = $result->FetchRow() ) {
			$tables[$row['table_id']] = $row;
		}
			
		return $tables;
	}
	
	/**
	 * Returns Array with Temlate Information from dlg_process
	 *
	 * @return	object	EK_Template
	 *
	 * @access 	private
	 */
	function & getTemplate( )
	{
		$row = array();
		$_EK_TPL_EXTENSIONS = array( 'xsd','eks','xml' );
		
		$dlgId = $this->webapp->getDlgId();
		
		$sql = "SELECT * FROM dlg_templates WHERE tpl_id='" . $dlgId . "'";
		$result =& $this->webapp->dbHandler->Execute( $sql );
		
		
		if ( $result->RecordCount() == 0 ) {
			$row['tpl_file'] = $dlgId;
		} elseif ( $result->RecordCount() == 1 ) {
			$row = array_change_key_case( $result->FetchRow() );
		} else {
			trigger_error( 'Duplicate Entries for Template ID: ' . $dlgId . ' in dlg_templates template !', E_USER_ERROR );
		}
		
		$tplFile = $row['tpl_file'];
		$tplPath = ( !isset( $row['tpl_path'] ) ) ? $this->webapp->tplPath : $row['tpl_path'];
		
		if ( !file_exists( $tplPath . "/" . $tplFile ) ) {
			foreach ( $_EK_TPL_EXTENSIONS as $ext ) {
				if (file_exists( $tplPath . "/" . $tplFile . "." . $ext ) ) {
					$tplFile = $tplFile . "." .$ext;
					break;
				}
			}
		} 
		
		if ( ! ($template = file_get_contents( $tplPath . "/" . $tplFile ) ) ) {
			trigger_error( 'Template File ' . $tplFile . ' not found in ' . $tplPath , E_USER_ERROR );
		}
		
		$tplTransformer = $row['tpl_transformer'];
		
		$tplStream		= is_null( $row['tpl_stream'] ) ? 'ek' : $row['tpl_stream'];
		
		$path_parts = pathinfo( $tplFile );
		
		if ( is_null( $tplTransformer) && in_array( $path_parts['extension'], $_EK_TPL_EXTENSIONS ) ) {
			$tplTransformer = 'ek_tpltransformer';
		}
		
		$tpl =& new EK_Template( $tplTransformer, $tplEngine, $tplStream );
		
		$tpl->setTemplate( $template );
		$tpl->setTplFile( $tplFile );
		$tpl->setTplPath( $tplPath );
	
		return $tpl;
	}
	
	/**
	 * Returns the Target Dialog Id
	 *
	 * @return 	string
	 *
	 * @access 	private
	 */
	function getTargetDlg( )
	{
		$dlgId 	= $this->webapp->getDlgId();
		$dlgEvt = $this->webapp->getDlgEvt();
		
		$sql = "SELECT * FROM dlg_process WHERE dlg_id='".$dlgId."' AND event='".$dlgEvt."'";
		$result =& $this->webapp->dbHandler->Execute( $sql );
		
		$row = $result->FetchRow();
		$tgtId = $row['target_dlg_id'];
		
		if ( empty( $tgtId ) || $tgtId == '*') {
			$sql = "SELECT * FROM dlg_process WHERE dlg_id='*' AND event='".$dlgEvt."'";
			$result =& $this->webapp->dbHandler->Execute( $sql );
			
			$row = $result->FetchRow( );
				
			$tgtId = $row['target_dlg_id'];
				
			if ( empty( $tgtId ) ) {
				$tgtId = ( $dlgId != '*' ) ? $dlgId : EK_INDEX_DLG;
			}
		}
		
		return $tgtId;
	}
	
	/**
	 * Returns a row from the dlg_queries table which can then be used to get the
	 * sql statement and the dsn
	 *
	 * @return array
	 */
	function & getQuery( $id )
	{
		$query = null;
		$sql = "SELECT query FROM dlg_queries WHERE id='" . $id . "'";
		$result =& $this->webapp->dbHandler->Execute( $sql );
		
		if ( $result->RecordCount() == 0 ) {
			$sql = "SELECT ctrl_query FROM dlg_vars WHERE ctrl_id='" . $id . "'";
			$result =& $this->webapp->dbHandler->Execute( $sql );
		
			if ($result->RecordCount() == 0) {
				return false;
			}
		}
				 
		return $result->FetchRow();
	}
	
	/**
	 * Returns a control query from the dlg_vars table
	 *
	 * @param string $id
	 * @param string $dlgId
	 * @return mixed	An array containing ctrl_query, and ctrl_query_dsn, FALSE if it does not exist
	 */
	function & getCtrlQuery( $id, $dlgId = '*')
	{
		$sql = "SELECT ctrl_query, ctrl_query_dsn FROM dlg_vars WHERE dlg_id='".$dlgId."' AND ctrl_id='".$id."'";
		$result =& $this->webapp->dbHandler->Execute( $sql );
		
		if ( $result->RecordCount() == 0 ) {
			$sql = "SELECT ctrl_query, ctrl_query_dsn FROM dlg_vars WHERE dlg_id='*' AND ctrl_id='".$id."'";
			$result =& $this->webapp->dbHandler->Execute( $sql );
			
			if ( $result->RecordCount() == 0 ) {
				trigger_error( 'Cannot find query ' . $id . ' in dlg_vars table!', E_USER_NOTICE );
			}
		}
		
		return $result->FetchRow();
	}
	
	/**
	 * Returns an array containing the table description
	 *
	 * @param string	$table	Name of table to get description for
	 *
	 * @return mixed	An array with table description, FALSE otherwise	
	 *
	 * @access public
	 */
	function getTableDescription( $table )
	{		
		$sql = "SELECT * FROM dlg_tables WHERE table_name='".$table."'";
		$result =& $this->webapp->dbHandler->Execute( $sql );
		
		if ( $result ) {
			return $result->FetchRow();
		}
		
		return false;
	}
}
?>