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

/**
 * Utility Function for EasyGUI XP
 *
 * This class provides numerous Funtions which can be called
 * statically for simplifying your life.
 *
 * @author Gaetan Lauff <glauff@plansoft.de>
 * @package util
 * @version	$Id: class.ek_common.php 44 2006-02-28 13:40:01Z glauff $
 */
class EK_Common
{
	/**
	 * Compresses the file from srcName to dstName
	 * 
	 *
	 * @param unknown_type $srcName
	 * @param unknown_type $dstName
	 * @return unknown
	 */
	function zipFile( $srcName, $dstName, $unlink = true )
	{
		if (strstr(strtoupper(PHP_OS), 'WIN')) {
			$zipcmd = EK_ROOT . "/bin/7za.exe a -tzip";
		} else {
			$zipcmd = '/usr/bin/zip -j';
		}
		
		$cmd = $zipcmd . ' ' . $dstName . ' ' . $srcName;
		$result= `$cmd` ;
		
		if ($unlink)
			unlink( $srcName );
		return true;
	}
	
	/**
	 * Sends the Common Headers
	 *
	 */
	function sendHTTPHeader()
	{
		@header("Expires: Wed, 18 May 2005 05:00:00 GMT");
		@header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		@header("Cache-Control: no-store, no-cache, must-revalidate");
		@header("Cache-Control: post-check=0, pre-check=0", false);
		@header("Pragma: no-cache");
		@header("Pragma: public");
	}
	/**
	 * Returns a new EK_DOMXML Singleton.
	 *
	 * @see EK_DOMXML
	 * @access public
	 */
	function &getDomHandler()
	{
    	static $domHandler; 

    	if(!isset($domHandler)) {
    		$domHandler =& new EK_DOMXML();
    	}

    	return $domHandler;
	}

	/**
	 * Returns a Submit Value
	 *
	 * If the searched form variable exists in one of the two superglobal arrays
	 * ($_GET, $_POST) then the value is returned. $_GET has precedence over $_POST.<br/>
	 * If the variable is not found, the default value is returned whenever it's set.<br/>
	 * If the variable is not found and no default value is set, FALSE is returned.<br/>
	 *
	 * @param	string	$var		Submission Variable to search for.
	 * @param 	mixed	$default	Default Value.
	 * @return 	mixed	The Submit Value if it's set, FALSE otherwise.
	 * @access  public
	 */
	function getSubmitValue($var, $default = null)
	{
		if (isset($_GET[$var])) {
			return EK_Common::getValue($_GET[$var]);
		} elseif (isset($_POST[$var])) {
			return EK_Common::getValue($_POST[$var]);
		} elseif (!empty($default)) {
			return EK_Common::getValue( $default );
		}
		
		return false;
	}
	
	/**
	 * Sets a value in a specific section
	 * 
	 * By Default the $_POST Vars Array is updated
	 * If you want to update any other section provide a section name
	 * Example EK_Common::setSubmitValue( 'IDC_TEST', 'TEST', '_GET' );
	 * 
	 * @param string	$var	Variable to set
	 * @param string	$value	Value to set
	 * @param bool		$force	
	 */
	function setSubmitValue( $var, $value, $section = null )
	{
		if ( is_null( $section ) ) {
			$_POST[$var] = $value;
		} else {
			$$section[$var] = $value;
		}
	}
	
	/**
	 * Checks if a key is set in Form Context ($_GET, $_POST)
	 *
	 * @param 	string	$var	Submission Variable to search for
	 * @return 	boolean	TRUE if the key exists in $_GET or $_POST, FALSE otherwise
	 * @access 	public
	 */ 
	function issetSubmitVar($var)
	{
		if (array_key_exists($var, $_GET) || array_key_exists($var, $_POST)) {
			return true;
		}
			
		return false;
	}
	
	/**
	 * Returns commandline options
	 *
	 * When the framework is used from the commandline you can use this method to get
	 * the passed commandline options. An array of options is returned
	 *
	 * @return array	An Array of commandline options where option name is the array key and the option is the array value.
	 * @access public
	 */
	function getOpt() 
	{
		$options = array();
		$opt = $_SERVER['argv'];
		$opt = array_reverse($opt);
		
		array_pop($opt);

		foreach($opt as $optkey => $optval) {
			$option = explode("=", $optval);
			
			if (sizeof($option) > 1) {
				$options[$option[0]] = $option[1];
			}
		}
		
		return $options;
	}
	
	/**
	 * Checks if File has EasyKat File Extension
	 *
	 * This is useful if you want to check if a
	 * template file has the right Extension. The function checks for the following extensions:
	 * xsd, xml, eks and tpl.
	 * 
	 * @param string	$file	Filename with extension
	 * @return boolean	TRUE if the extension is set to xsd, xml, eks or tpl.
	 * @access public
	 */
	function isEKFile($file)
	{
		if (preg_match("/.xsd|.xml|.eks|.tpl$/i", trim($file))) {
			return true;
		}
		
		return false;
	} 	
	
	/**
	 * Checks if File has html extension
	 *
	 * @param string	$file	Filename with extension
	 * @return boolean	TRUE if filename has extension htm or html
	 * @access public
	 */
	function isHTMLFile($file)
	{
		if (preg_match("/.htm|.html$/i", trim($file))) {
			return true;
		}
		
		return false;
	}
	
	/**
	 * Returns File Extension
	 *
	 * @param string	$fileName	Filename with extension
	 * @return string	File Extension
	 * @access public
	 */
	function getFileExtension($fileName)
	{
		$parts = explode('.', $fileName);
		return strtolower($parts[1]);
	}
	
	/**
	 * Returns a random value
	 *
	 * This method creates a random number for you
	 *
	 * @return int	Random Number in the range from 1000000 - 9999999
	 * @access public
	 */
	function getRandval()
	{
		mt_srand((double)microtime()*1000000);
		return mt_rand();
	}
	
	/**
	* Get Include Files From a specified directory
	*
	* This method includes all php files starting from a given
	* directory. The Files are include recursive. Please note that
	* if files have relationships among one another you have to make sure that
	* the files are included in the right order. The default order is alphabetical.
	*
	* @param string	$dir	Directory 
	* @access public
	*/
	function getRequiredClasses( $dir )
	{
		if (!$hdl = dir( $dir ) ) {
			trigger_error('Directory '.$dir.' not found !<br />Cannot include required classes.', E_USER_ERROR );
		}
		
		while ($entry = $hdl->read() ) {
			if($entry != "." && $entry != '..') {
				if (preg_match("/.php$/i", $entry)) {
					require_once($hdl->path."/".$entry);
				}
			}
		}
		
		$hdl->rewind();
		
		while ($entry = $hdl->read()) {
			if($entry != "." && $entry != '..') {
				if (is_dir($hdl->path."/".$entry)) {
					EK_Common::getRequiredClasses($hdl->path."/".$entry);
				} 
				/*
				else {
					if (preg_match("/.php$/i", $entry)) {
						require_once($hdl->path."/".$entry);
					}
				}
				*/
			}
		}
		
		$hdl->close();
	}
	
	/**
	 * Logs an Error to the Log File
	 * 
	 * @param string	$msg	The Error Message
	 * @return void
	 * @access public
	 *
	 * @todo implement a generic logger !
	 * This function is not in use in the framework
	 * Error logging is handled inside the Error Handling Class
	 *
	 */
	function logError( $msg )
	{	
		$now = date('Y-m-d H:i:s');
		$fp = fopen ( EK_LOG_FILE, 'a');
		fputs ($fp, $now . "--> " . $msg . "\r\n" . str_repeat( '-', 80 ) . "\r\n");
		fclose( $fp );
	}
	
	/**
	 * Returns a value from an Array
	 *
	 * @param 	array		$array		array in which the Value is searched
	 * @param 	key			$key 		key for value to search
	 * @param 	default		$default 	default value that is returned in case key is not set
	 * @return	string		The searched value
	 * @access 	public
	 */
	function getArrayValue( $array, $key, $default = null) 
	{
		if (isset($array[$key]) && !empty($array[$key])) {
			return $array[$key];
		}
			
		return $default;
	}
	
	/**
	 * Returns an Array Value
	 *
	 * @param 	array		$array 		array in which
	 * @param 	string		$val		value to search for
	 * @param 	string		$default	default value that is returned in case value is not set
	 * @return	string	
	 * @access 	public
	 */
	function getArrayValueByValue( $array, $val, $default = null )
	{
		foreach ( $array as $key => $value ) {
			if ($val == $value) {
				return $array[$key];
			}
		}
				
		return $default;
	}
	
	/**
	 * Returns the right value
	 *
	 * In many cases you have to get the right value from attributes.
	 * Normally all values are strings when you get them from let's say XML Attributes etc.
	 * The String 'true' is not the same as the boolean value TRUE. This function takes
	 * care of this issues and returns the right value if it cans.
	 * 
	 * @param string	$val	The Value that should be examined
	 * @return mixed
	 * @access public
	 */
	function getValue( $val )
	{
		switch($val) {
			case 'true':
				$val = TRUE;
				break;
				
			case 'false':
				$val = FALSE;
				break;
				
			default:
				if (is_numeric( $val )) {
					$val = 0 + $val;
				}
				/*
				if (is_array( $val )) {
					print "Found array !";
					print_r($val);
				}
				*/
				break;
		}
		
		return $val;
	}
}
?>