<?php
/*
**	$Id$
**
**	ITools - the Internet Tools Library
**
**	support.pinc - Various Support Functions for ITools.
**	This is the first file in itools.lib
*/

/**
 * Print an error message and end page
 * @see internal_error
 */
function fail($text)
{
	global $IT_CUSTOM_FAIL;

	if ($IT_CUSTOM_FAIL)
	{
		$IT_CUSTOM_FAIL($text);
		/* NOT REACHED */
	}

	trigger_error($text, E_USER_ERROR);
	it::fatal($text);
}


/**
 * Global shortcut for $it_debug::debug()
 * @see it_debug
 */
function debug($text, $level=0)
{
	if (isset($GLOBALS['it_debug']))
		$GLOBALS['it_debug']->debug($text, $level);
}


/**
 * Global shortcut for $it_debug::intermal_error()
 * @see it_debug
 */
function internal_error($text)
{
	if (isset($GLOBALS['it_debug']))
		$GLOBALS['it_debug']->internal_error($text);
	else
		exit;
	/* NOT REACHED */
}


/**
 * Convert a htmlentities-encoded string back to normal
 */
function it_htmlentities_decode($string)
{
	return strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
}


/**
 * Clone an object and return copy, works for all PHP versions
 */
function &it_clone(&$object)
{
	$result = (is_object($object) && version_compare(zend_version(), 2, '>=')) ? clone($object) : $object;

	return $result;	# PHP internals need a tmp var to return by ref
}


/**
 * Defines a new error_handler which gives a Stacktrace
 * To activate, use: set_error_handler('it_error_handler');
 */
function it_error_handler($errno, $errstr, $errfile, $errline)
{
	$errors = array(
		1 => 'ERROR',
		2 => 'WARNING',
		4 => 'PARSE',
		8 => 'NOTICE',
		16 => 'CORE_ERROR',
		32 => 'CORE_WARNING',
		64 => 'COMPILE_ERROR',
		128 => 'COMPILE_WARNING',
		256 => 'USER_ERROR',
		512 => 'USER_WARNING',
		1024 => 'USER_NOTICE',
		2048 => 'STRICT',
	);

	$error = isset($errors[$errno]) ? $errors[$errno] : $errno;

	if (ini_get('display_errors') && ($errno & ini_get('error_reporting')))
	{
		$stack = debug_backtrace();
		array_shift($stack);

		$url  = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
		$ref  = $_SERVER['HTTP_REFERER'];
		$errfile = preg_replace('#^/data./www/#', '/www/', $errfile);

		foreach ($stack as $level)
		{
			if (isset($level['class']))
				$level['function'] = "{$level['class']}->{$level['function']}";

			$file = preg_replace('#^/data./www/#', '/www/', $level['file']);
			$args = array();

			foreach ((array)$level['args'] as $arg)
			{
				switch (gettype($arg))
				{
				case 'array':
					$args[] = 'Array[' . count($arg) . ']';
					break;
				case 'object':
					$args[] = 'Object:' . get_class($arg);
					break;
				case 'boolean':
					$args[] = $arg ? 'true' : 'false';
					break;
				default:
					$args[] = '"' . (string)$arg . '"';
					break;
				}

				
			}

			if ($levelnum++ == 0)
				$message .= "Line {$level['line']} $file # <b>$error:</b> $errstr\n";
			else
				$message .= "Line {$level['line']} $file # {$level['function']}(" . join(', ', $args) . ")\n";
		}

		if ($_SERVER['HTTP_HOST'])
		{
			foreach((array)$_COOKIE as $key => $val)
				$cookies .= "$key=$val ";

			error_log("$error: $errstr at Line $errline $errfile url=$url ref=$ref $cookies");
			echo "\n\n<pre>\n$message</pre><br />\n\n";
		}
		else
			error_log(strip_tags($message));
	}

	if (!preg_match('/(WARNING|NOTICE|STRICT)$/', $error))
		exit(1);
}

/**
 * Return string containing names and values of all arguments
 */
function D()
{
	$args = func_get_args();
	return call_user_func_array(array('it_debug', 'dump'), $args);
}

/**
 * Echo string containing names and values of all arguments
 */
function ED()
{
	$args = func_get_args();
	echo call_user_func_array(array('it_debug', 'dump'), $args);
	return $args[0];
}

/**
 * Same as ED(), but first argument is string that must be in $_REQUEST['debug']
 */
function EDC()
{
	$args = func_get_args();
	$GLOBALS['ULTRADEBUGVARS'][$args[0]] = 1;
	if (strstr($_REQUEST['debug'], $args[0]) || $GLOBALS["debug_" . $args[0]]) {
		$active = $GLOBALS['debug_'.$args[0]];
		if( !$active )
			$active = 1;
		$args[0] = '_ignoreme';
		if (count($args) > 1)
			echo call_user_func_array(array('it_debug', 'dump'), $args);
	} else
		$active = 0;
	return $active;
}

/**
 * Echo string containing names and values of all arguments, then exit
 */
function EDX()
{
	$args = func_get_args();
	exit(call_user_func_array(array('it_debug', 'dump'), $args));
}

/**
 * Return "db4" or "db2" depending on availability
 */
function db_version()
{
	return in_array("db4", dba_handlers()) ? "db4" : "db2";
}

/**
 * Append a line to a logfile in log/. Date will be added to filename and line
 * @param $name Name of logfile
 * @param $line Line to append
 */
function log_append($name, $line)
{
	if ($fh = fopen($GLOBALS['ULTRAHOME'] . "/log/$name-" . date('Ymd'), "a")) {
		fputs($fh, date("Y-m-d H:i:s") . "\t$line\n");
		fclose($fh);
	}	
}

?>