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

/**
 * Value Handler for EasyGUI XP System
 * Handles all Values
 *
 * @author Gaetan Lauff <glauff@plansoft.de>
 * @version	XP $Id: class.ek_valuehandler.php 50 2006-03-10 10:04:54Z glauff $
 * @package dataspace
 */
class EK_ValueHandler extends EK_Handler
{
	/**
	 * Returns a string where all Session Variables are replaced
	 *
	 * You have the possibility to refer to session Values in your queries.
	 * Just enclose the values in $ Signs and they are replace by the current session values
	 * Please refer to the EasyGUI XP Users Guide to get more information on how to design
	 * queries.
	 *
	 * @param string	$query
	 * @param string	$context	Session Context in which you want to search for the replacements
	 *
	 * @return string
	 *
	 * @access public
	 */
	function getReplacedSQL( $query, $context = null )
	{
		preg_match_all('/\$([^\$]+)\$/', $query, $values, PREG_PATTERN_ORDER );
		
		if ( is_null($context) ) {
			$context = $this->webapp->getDlgId();
		}
		
		foreach ( $values[1] as $id ) {
			//$value = EK_Common::getSubmitValue( $id, $this->getSessionValue( $id, $context ) );
			$value = $this->webapp->getSessionValue( $id, $context );
			
			if ( !is_null( $value ) ) {
				$query = str_replace( '$' . $id . '$', $value, $query );
			} else {
				trigger_error( $id . " is NULL !\r\n<br/>Check Default Value or set right value manually !", E_USER_NOTICE ); 
			}
		}
		//print $query;
		return $query;		
	}
	
	function getProgValue( $id )
	{
		$dldId = $this->webapp->getDlgId();
		return $dlgId;
	}
	
	/**
	 * Returns a value from Database or Session
	 *
	 * @param 	string	$id	Id of value to search for
	 *
	 * @return 	mixed	The value if it's found, FALSE otherwise
	 *
	 * @access 	public
	 */
	function getValue( $id )
	{
		$dlgId 		= $this->webapp->getDlgId();
		$dlgKeys 	= $this->webapp->getDlgKeys( $dlgId );
		
		if (!$dlgKeys) {
			return $this->webapp->getSessionValue( $id );
		}
		
		$res = $this->webapp->getDlgVar( $dlgId, $id );
		
		if (!$res || empty( $res['ctrl_db_table'] ) || empty( $res['ctrl_db_field'] ) ) {
			return $this->webapp->getSessionValue( $id );
		}
	
		$pk = array();
		
		$table 	= $res['ctrl_db_table'];
		$field 	= $res['ctrl_db_field'];
		$format = $res['ctrl_format'];
		
		$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'] );
		}
		
		foreach ( $dlgKeys as $keytable => $row ) {
			if ( $keytable == $table ) {
				$key = explode( '.', $row['key_ctrl'] );
				$sessionKey	= $dlgId;
			
				if (empty($key[1])) {
					$dlgKey 	= $key[0];
				} else {
					$sessionKey	= $key[0];
					$dlgKey 	= $key[1];
				}

				$pkVal = $this->webapp->getSessionValue( $dlgKey, $sessionKey );
			
				if ( $pkVal === false ) {
					if ( $res['session'] || !is_null( $res['ctrl_default_value'] ) ) {
						return $this->webapp->getSessionValue( $id );
					}
					
					return false;
				} else {
					$pkVar = $this->webapp->getPrimaryKeyField( $table, $dbHandler );
					$sql = "SELECT " . $field . " FROM " . $table . " WHERE " . $pkVar . "='".$pkVal."'";
					
					$result =& $dbHandler->Execute( $sql );
					
					if ($result->RecordCount() == 1) {
						$field = $result->FetchField(0);
						$value = $result->FetchRow();
						
						/*
						if ( is_null( $value[0] ) ) {
							// No Database Value is set
							// Search for Default Value
							// @experimental
							// return $this->webapp->getSessionValue( $res['ctrl_id'] );
							return null;
						}
						*/
						
						return $this->webapp->getScreenValue( $value[0], $format, $field, $result->MetaType($field), $dbHandler );
					}
			
					return false;
				}
			}
		}
		
		$sql = "SELECT * FROM dlg_table_refs WHERE table_name='".$table."' AND foreign_key is not NULL";
		$result =& $this->webapp->dbHandler->Execute( $sql );
		
		$where = "";
		
		if ( $result->RecordCount() > 0) {
			while( $row = $result->FetchRow() ) {
				if (isset( $_SESSION[$dlgId]['DLG_TABLES']['FOREIGN_KEYS'][$row['table_name']][$row['foreign_key']] ) && !empty( $_SESSION[$dlgId]['DLG_TABLES']['FOREIGN_KEYS'][$row['table_name']][$row['foreign_key']] ) ) {
					$where .= " WHERE " . $row['foreign_key'] . "='" . $_SESSION[$dlgId]['DLG_TABLES']['FOREIGN_KEYS'][$row['table_name']][$row['foreign_key']] . "'";
				}
			}
		} 
		
		$sql = "SELECT " . $field . " FROM " . $table . $where;
		$result =& $dbHandler->Execute( $sql );
		
		if ($result->RecordCount() == 1) {
			$field = $result->FetchField(0);
			$value = $result->FetchRow();
			return $this->webapp->getScreenValue( $value[0], $format, $field->type, $result->MetaType($field), $dbHandler );
		}
			
		return false;
	}
	
	/**
	 * Returns a Value from a query
	 *
	 * Please refer to EasyGUI XP Users Guide for more Informations
	 * about the power of prepared Queries.
	 *
	 * @param 	string	$id
	 *
	 * @return 	mixed	The Value from the Query, FALSE otherwise
	 *
	 * @access 	private
	 */
	function getValueFromQuery( $id )
	{
		if ( empty($id) )
		{
			return;
		}
		
		$value = 'false';
		$handled = false;
		
		/*
		 * Default Queries that can be used by the programmer
		 */
		switch ( $id ) {
			case 'IDQ_CONFIRM_AUTH':
				if ( $this->webapp->confirmAuth() ) {
					$value = 'true';
				}
					
				$handled = true;
								
				break;
				
			case '!IDQ_CONFIRM_AUTH':
				if ( !$this->webapp->confirmAuth() ) {
					$value = 'true';
				}

				$handled = true;
								
				break;
				
			default:
				break;
		}
		
		if ( !$handled ) {
			$query = $this->webapp->getQuery( $id );
			
			if ( !$query ) {
				return false;
			}
			
			$sql = $this->webapp->getReplacedSQL( $query[0] );
			
			if (isset( $query[1] ) && !empty( $query[1] ) ) {
				$dsn = $query[1]; 
			}
			
			if ( !empty( $dsn ) ) {
				$dbHandler = $this->webapp->getDatabaseHandler( $dsn );
			} else {
				$dbHandler = $this->webapp->getDatabaseHandler( 'default' );
			}
				
			$result =& $dbHandler->Execute( $sql );

			$res = $result->FetchRow();
			$value = $res[0];
			
			$handled = true;
		}
		
		if ( !$handled ) {
			$value = $this->webapp->getSessionValue( $id );
		}
		
		return $value;
	}
	
	/**
	 * Returns replaced Values
	 *
	 * @param string	Statement
	 * @return string
	 * @access public
	 */
	function getReplacedValues( $statement ) 
	{
		preg_match_all("/\\$(\w+)\\$/", $statement, $matches, PREG_PATTERN_ORDER);
		
		if (!sizeof($matches[1])) {
			return 0;
		}
		
		while(list(,$id) = each($matches[1])) {
			$replaceVal = $this->getValue($id);
			$statement = str_replace("$".$id."$", $replaceVal, $statement);
		}
		
		return $statement;
	}
	
}