FailTrans();
		}
		//print_r($e);
		//adodb_pr($e);
		Debug::Text( 'Begin Exception... [ ' . @date( 'd-M-Y G:i:s O' ) . ' [' . microtime( true ) . '] (PID: ' . getmypid() . ') ]', __FILE__, __LINE__, __METHOD__, 10 );
		Debug::Arr( Debug::backTrace(), ' BackTrace: ', __FILE__, __LINE__, __METHOD__, 10 );
		//Log database error
		// This can be tested with the following code:  throw new DBError( new Exception('unique constraint', 99999 ), 99999 );
		if ( $e->getMessage() != '' ) {
			if ( stristr( $e->getMessage(), 'statement timeout' ) !== false ) {
				$code = 'DBTimeout';
			} else if ( stristr( $e->getMessage(), 'unique constraint' ) !== false ) {
				$code = 'DBUniqueConstraint';
			} else if ( stristr( $e->getMessage(), 'invalid byte sequence' ) !== false ) {
				$code = 'DBInvalidByteSequence';
			} else if ( stristr( $e->getMessage(), 'could not serialize' ) !== false ) {
				$code = 'DBSerialize';
			} else if ( stristr( $e->getMessage(), 'deadlock' ) !== false || stristr( $e->getMessage(), 'lock timeout' ) !== false || stristr( $e->getMessage(), 'concurrent' ) !== false ) {
				$code = 'DBDeadLock';
			} else if ( stristr( $e->getMessage(), 'server has gone away' ) !== false || stristr( $e->getMessage(), 'closed the connection unexpectedly' ) !== false || stristr( $e->getMessage(), 'execution was interrupted' ) !== false ) { //Connection was lost after it was initially made.
				$code = 'DBConnectionLost';
			} else if ( stristr( $e->getMessage(), 'No space left on device' ) !== false ) { //Unrecoverable error, set down_for_maintenance so server admin can investigate?
				$code = 'DBNoSpaceOnDevice';
			} else if ( stristr( $e->getMessage(), 'connection failed' ) !== false ) { //Connection could not be established to begin with.
				$code = 'DBConnectionFailed';
			}
			Debug::Text( 'Code: ' . $code . '(' . $e->getCode() . ') Message: ' . $e->getMessage(), __FILE__, __LINE__, __METHOD__, 10 );
		}
		if ( $e->getTrace() != '' ) {
			ob_start(); //ADDBO_BACKTRACE() always insists on printing its output and returning it, so capture the output and drop it, so we can use the $adodb_backtrace_arr variable instead.
			$adodb_backtrace_arr = adodb_backtrace( $e->getTrace(), 9999, false );
			ob_end_clean();
			Debug::Arr( $adodb_backtrace_arr, 'Exception...', __FILE__, __LINE__, __METHOD__, 10 );
			unset( $adodb_backtrace_arr );
		}
		//Make sure we populate the exception variables, so we can properly catch them again.
		parent::__construct( $e->getMessage(), $e->getCode() );
		Debug::Text( 'End Exception...', __FILE__, __LINE__, __METHOD__, 10 );
		if ( !defined( 'UNIT_TEST_MODE' ) || UNIT_TEST_MODE === false ) { //When in unit test mode don't exit/redirect
			if ( DEPLOYMENT_ON_DEMAND == true || ( DEPLOYMENT_ON_DEMAND == false && in_array( $code, [ 'DBConnectionFailed', 'DBNoSpaceOnDevice', 'DBConnectionLost' ] ) == false ) ) {
				Debug::emailLog();
			}
			//Dump debug buffer.
			//Debug::Display(); //Handled in TTShutdown now.
			//Debug::writeToLog(); //Handled in TTShutdown now.
			//Prevent PHP error by checking to make sure output buffer exists before clearing it.
			if ( ob_get_level() > 0 ) {
				ob_flush();
				ob_clean();
			}
			if ( defined( 'TIMETREX_JSON_API' ) ) {
				if ( DEPLOYMENT_ON_DEMAND == true ) {
					switch ( strtolower( $code ) ) {
						case 'dbtimeout':
							$description = TTi18n::getText( '%1 database query has timed-out, if you were trying to run a report it may be too large, please narrow your search criteria and try again.', [ APPLICATION_NAME ] );
							break;
						case 'dbuniqueconstraint':
						case 'dbdeadlock':
							$description = TTi18n::getText( '%1 has detected a duplicate request, this may be due to double-clicking a button or a poor internet connection.', [ APPLICATION_NAME ] );
							break;
						case 'dbinvalidbytesequence':
							$description = TTi18n::getText( '%1 has detected invalid UTF8 characters, if you are attempting to use non-english characters, they may be invalid.', [ APPLICATION_NAME ] );
							break;
						case 'dbserialize':
							$description = TTi18n::getText( '%1 has detected a duplicate request running at the exact same time, please try your request again.', [ APPLICATION_NAME ] );
							break;
						default:
							$description = TTi18n::getText( '%1 is currently undergoing maintenance. We\'re sorry for any inconvenience this may cause. Please try again in 15 minutes.', [ APPLICATION_NAME ] );
							break;
					}
				} else {
					switch ( strtolower( $code ) ) {
						case 'dbtimeout':
							$description = TTi18n::getText( '%1 database query has timed-out, if you were trying to run a report it may be too large, please narrow your search criteria and try again.', [ APPLICATION_NAME ] );
							break;
						case 'dbuniqueconstraint':
						case 'dbdeadlock':
							$description = TTi18n::getText( '%1 has detected a duplicate request, this may be due to double-clicking a button or a poor internet connection.', [ APPLICATION_NAME ] );
							break;
						case 'dbinvalidbytesequence':
							$description = TTi18n::getText( '%1 has detected invalid UTF8 characters, if you are attempting to use non-english characters, they may be invalid.', [ APPLICATION_NAME ] );
							break;
						case 'dbserialize':
							$description = TTi18n::getText( '%1 has detected a duplicate request running at the exact same time, please try your request again.', [ APPLICATION_NAME ] );
							break;
						case 'dbnospaceondevice':
							$description = TTi18n::getText( '%1 has detected a database error, please contact technical support immediately.', [ APPLICATION_NAME ] );
							break;
						case 'dberror':
						case 'dbconnectionfailed':
							$description = TTi18n::getText( '%1 is unable to connect to its database, please make sure that the database service on your own local %1 server has been started and is running. If you are unsure, try rebooting your server.', [ APPLICATION_NAME ] );
							break;
						case 'dbinitialize':
							$description = TTi18n::getText( '%1 database has not been initialized yet, please run the installer again and follow the on screen instructions. Click here to run the installer now.', [ APPLICATION_NAME, Environment::getBaseURL() . '/install/install.php?external_installer=1' ] );
							break;
						default:
							$description = TTi18n::getText( '%1 experienced a general error, please contact technical support.', [ APPLICATION_NAME ] );
							break;
					}
				}
				$obj = new APIAuthentication();
				echo json_encode( $obj->returnHandler( false, 'EXCEPTION', $description ) );
				exit;
			} else if ( PHP_SAPI == 'cli' ) {
				//Don't attempt to redirect
				echo "Fatal Exception: Code: " . $code . "... Exiting with error code 254!\n";
				exit( 254 );
			} else {
				global $config_vars;
				if ( DEPLOYMENT_ON_DEMAND == false
						&& isset( $config_vars['other']['installer_enabled'] ) && $config_vars['other']['installer_enabled'] == 1
						&& in_array( strtolower( $code ), [ 'dberror', 'dbinitialize' ] ) ) {
					Redirect::Page( URLBuilder::getURL( [], Environment::getBaseURL() . 'html5/index.php?installer=1&disable_db=1&external_installer=0#!m=Install&a=license&external_installer=0' ) );
				} else {
					Redirect::Page( URLBuilder::getURL( [ 'exception' => $code ], Environment::getBaseURL() . 'html5/DownForMaintenance.php' ) );
				}
				exit;
			}
		}
		return true;
	}
}
/**
 * Used by RetryTransaction() when a nested retry block fails, so we can detect it and trigger the outer most retry block to retry from the scratch.
 * Class NestedRetryTransaction
 */
class NestedRetryTransaction extends Exception {
}
/**
 * @package Core
 */
class GeneralError extends Exception {
	/**
	 * GeneralError constructor.
	 * @param string $message
	 */
	function __construct( $message ) {
		global $db;
		//debug_print_backtrace();
		//If we couldn't connect to the database, this method may not exist.
		if ( isset( $db ) && is_object( $db ) && method_exists( $db, 'FailTrans' ) ) {
			$db->FailTrans();
		}
		/*
		echo "======================================================================
\n";
		echo "EXCEPTION!
\n";
		echo "======================================================================
\n";
		echo "Error message: ".$message ."
\n";
		echo "Error code: ".$this->getCode()."
\n";
		echo "Script Name: ".$this->getFile()."
\n";
		echo "Line Number: ".$this->getLine()."
\n";
		echo "======================================================================
\n";
		echo "EXCEPTION!
\n";
		echo "======================================================================
\n";
		*/
		Debug::Text( 'EXCEPTION: Code: ' . $this->getCode() . ' Message: ' . $message . ' File: ' . $this->getFile() . ' Line: ' . $this->getLine(), __FILE__, __LINE__, __METHOD__, 10 );
		Debug::Arr( Debug::backTrace(), ' BackTrace: ', __FILE__, __LINE__, __METHOD__, 10 );
		if ( !defined( 'UNIT_TEST_MODE' ) || UNIT_TEST_MODE === false ) { //When in unit test mode don't exit/redirect
			//Dump debug buffer.
			//Debug::Display(); //Handled in TTShutdown now.
			//Debug::writeToLog(); //Handled in TTShutdown now.
			Debug::emailLog();
			ob_flush();
			ob_clean();
			if ( defined( 'TIMETREX_JSON_API' ) ) {
				$obj = new APIAuthentication();
				echo json_encode( $obj->returnHandler( false, 'EXCEPTION', TTi18n::getText( '%1 experienced a general error, please contact technical support.', [ APPLICATION_NAME ] ) ) );
				exit;
			} else {
				Redirect::Page( URLBuilder::getURL( [ 'exception' => 'GeneralError' ], Environment::getBaseURL() . 'html5/DownForMaintenance.php' ) );
				exit;
			}
		}
	}
}
?>