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

/**
 * EasyGUI XP Error Handling Class
 *
 * This class handles all errors that happen on the server side
 * When an Error occur the EK_ErrorHandler is invoked.
 * The Error handler informs the end user that an error occured.
 * If you have log errors switched to on then the error is logged
 * in the error log. If you have an error email set then you will be
 * informed by mail whenever a fatal error occurs.
 * You can set the error handling properties in the workspace file
 *
 * @author Gaetan Lauff <glauff@plansoft.de>
 * @version	XP $Id: class.ek_errorhandler.php 3 2006-01-31 17:44:30Z glauff $
 * @package error
 */
class EK_Error
{
	/**
	 * EasyGUI Application Object
	 *
	 * @var object
	 */
	var $handler;
	
	/**
	 * @var boolean
	 */
	var $hasErrorsm = false;
	
	/**
	 * @var boolean
	 */
	var $hasWarnings = false;
	
	/**
	 * @var boolean
	 */
	var $hasNotices = false;
	
	/**
	 * @var boolean
	 */
	var $hasPHPErrors = false;
	
	/**
	 * @var array;
	 */
	var $trace;
	
	/**
	 * @var array;
	 */
	var $warnings = array();
	
	/**
	 * @var array;
	 */
	var $notices = array();
	
	/**
	 * @var array;
	 */
	var $phperrors = array();
	
	/**
	 * Logfile
	 *
	 * @var string
	 */
	var $logfile;
	
	/**
	 * Constructor
	 *
	 * @return void
	 *
	 * @access public
	 */
	function EK_Error()
	{
		$this->hasErrors 	= false;
		$this->trace		= array();
	}
		
	/**
	 * Error Handler
	 *
	 * Method that handles the EasyGUI XP Errors
	 * This Handler is registered as the Default ErrorHandler
	 *
	 * @param 	string	$errorLevel		Error level
	 * @param 	string	$errorMessage 	Error Message from Browser
	 * @param 	string	$errorFile		Source in which the error happened
	 * @param 	string	$errorLine		Line in which the error has happened
	 * @param 	context	$errorContext	Context in which the error happened
	 *
	 * @return 	void
	 *
	 * @access 	private
	 */
	function EK_ErrorHandler($errorLevel, $errorMessage, $errorFile, $errorLine, $errorContext)
	{
		global $handler;
		$this->logfile = null;
		
		if ( EK_LOG_ERRORS ) {
			$this->logfile = str_replace('.', '['.date('Y-m-d').'].', EK_LOG_FILE);
			
			if (!file_exists( $this->logfile )) {
				$loginfo = pathinfo( $this->logfile );
				$logdir = $loginfo['dirname'];

				if (!file_exists( $logdir ) ) {
					mkdir( $logdir );
				}
					
				if (!$fp = fopen( $this->logfile, 'w+')) {
					print "Logfile " . $this->logfile . " cannot be created !";
					exit(0);
				}
				
				fputs ( $fp, 'Log file created on ' . date('Y-m-d H:i:s') ."\r\n" . str_repeat('=', 80) ."\r\n" );
				fclose( $fp );
			}
			
			switch($errorLevel) {
				case E_USER_ERROR:
					$error = str_repeat('-', 80) . "\r\n";
					$error .= "Level: $errorLevel\r\n";
					$error .= "File: $errorFile\r\n";
					$error .= "Line: $errorLine\r\n";
					$error .= "Time: " . date('d.m.Y H:i:s') . "\r\n\r\n";
					$error .= strip_tags($errorMessage) . "\r\n";
					$error .= str_repeat('-', 80) . "\r\n";
					
					error_log($error, 3, $this->logfile );
					
					if ( defined( 'EK_REPORT_ERRORS' ) && EK_REPORT_ERRORS ) {
						mail( EK_REPORT_ERRORS, 'EasyGUI@' . $_SERVER['SERVER_NAME'] . ' reported the following fatal error', $error, "From: EasyGUI XP <easygui@{$_SERVER['SERVER_NAME']}>");
					}
						
					break;
				default:
					break;
			}
		}
		
		array_push( $this->trace, $errorMessage );
		
		switch ($errorLevel) {
			case E_USER_ERROR:
				if ( is_a( $handler, 'ek_webapp' ) ) {
					foreach ( $handler->dbHandlers as $dsn => $dbHandler ) {
						$dbHandler->CompleteTrans();
					}
					
					if ( $handler->ajax ) {
						
						$errorMessage = $errorMessage . "\r\nin: " . $errorFile . "\r\nLine: " . $errorLine;
						die( "alert('".addslashes( $errorMessage )."');" );
					}
				}
				
				//$tpl =& new EK_Template();
				//$tpl->setTemplate( file_get_contents( EK_ROOT . "/tpl/error.tpl" ) );
				$errorMessage = $errorMessage . "\r\n<br/>in: " . $errorFile . "\r\nLine: " . $errorLine;
				
				$tpl = file_get_contents( EK_ROOT . "/tpl/error.tpl" );
				
				$tpl = str_replace( '%ERROR_MSG%', $errorMessage, $tpl );
				$tpl = str_replace( '%LOGFILE%', $this->logfile, $tpl );
				$tpl = str_replace( '%EK_PATH%', constant( 'EK_PATH'), $tpl );
				
				die ($tpl);
				//$tpl->setValue( 'ERROR_MSG', $errorMessage );
				//$tpl->setValue( 'LOGFILE', $this->logfile );
				//$tpl->setValue( 'EK_PATH', constant( 'EK_PATH' ) );
				
				//$engine = new EK_TemplateEngine( $handler, $tpl );
				//die( $engine->fetch() );
				
	    	case E_USER_WARNING:
	    		$this->hasWarnings = true;
	       		array_push( $this->warnings, $errorMessage );
	    		break;
	    
	    	case E_USER_NOTICE:
	    		$this->hasNotices = true;
	        	array_push( $this->notices, $errorMessage );
	    		break;
	    		
	    	default:
	    		if ($errorLevel < E_WARNING ) {
	    			$this->hasPHPErrors = true;
	    			$errorMessage = $errorMessage . " in<br/>\r\n" . $errorFile . "<br/>\r\nLine: " . $errorLine . "<br/>\r\nContext: " . $errorContext . "<br/>\r\n";
	    			array_push( $this->phperrors, $errorMessage );
	    		}
	    		break;
		}
    }
    
    /**
	 * Returns a Trace of the Errors that occured
	 *
	 * @return unknown
	 */
	function getTrace()
	{
		if ( $this->hasErrors() ) {
			foreach ( $this->trace as $msg ) {
				print $msg . "\r\n";
			}
		}
	}
    
    /**
	 * Returns TRUE if the Application has caused any Errors
	 *
	 * @return boolean
	 */
	function hasErrors()
	{
		return $this->hasErrors;
	}
	
	/**
	 * Returns TRUE if the Application has encounteres any Warnings
	 *
	 * @return boolean
	 */
	function hasWarnings()
	{
		return $this->hasWarnings;
	}
	
	/**
	 * Returns TRUE if the Application has encountereds
	 *
	 * @return unknown
	 */
	function hasNotices()
	{
		return $this->hasNotices;
	}
	
	/**
	 * Returns a String of the Warnings that the application throwed
	 *
	 * @return string
	 */
	function getWarnings()
	{
		$warnings = '';
		
		foreach ( $this->warnings as $msg ) {
			$warnings .= "EasyGUI Warning: " . $msg . "<br/>\r\n";
		}
		
		return $warnings;
	}
	
	/**
	 * Returns a String of the Notices that the application throwed
	 *
	 * @return string
	 */
	function getNotices()
	{
		$notices = '';
		
		foreach ( $this->notices as $msg ) {
			$notices .= $msg . "<br/>\r\n";
		}
		
		return $notices;
	}
	
	/**
	 * Returns a String of the PHP Errors that occured
	 *
	 * @return String
	 */
	function getPHPErrors()
	{
		$errors = '';
		
		foreach ( $this->phperrors as $msg ) {
			$errors .= $msg . "<br/>\r\n";
		}
		
		return $errors;
	}	
}
?>