<?php

openlog ('hedera-web', LOG_ODELAY, LOG_LOCAL0);

require_once ('vn/hedera/web.php');
require_once ('vn/rest/rest.php');

use Vn\Lib\Locale;
use Vn\Rest;
use Vn\Hedera\Web;

function myExitHandler ()
{
	Web::deinit ();
	Rest\Service::sendReply ();
	closelog ();
}

function myGlobalErrorHandler ()
{
	Rest\Service::setError ('PHP', 'internalError', 'An internal error has occurred');
	myExitHandler ();
	exit (0);
}

function myErrorHandler ($errno, $message, $file, $line, $context)
{
	error_log ("Error: $file($line): $message");

	switch ($errno)
	{
		case E_USER_ERROR:
			myGlobalErrorHandler ();
		default:
			Rest\Service::addWarning ('PHP', 'internalMessage', 'Something has gone wrong');
	}
	
	return TRUE;
}

function myExceptionHandler ($e)
{
	error_log (sprintf ('Exception: %s(%d): %s. Trace: %s'
		,$e->getFile ()
		,$e->getLine ()
		,$e->getMessage ()
		,$e->getTraceAsString ()
	));
	myGlobalErrorHandler ();
}

set_error_handler ('myErrorHandler', E_ALL);
set_exception_handler ('myExceptionHandler');

Rest\Service::init ();

try {
	Web::init ();
	Web::login ();

	// Checking the client version

	if (isset ($_COOKIE['hedera_version']))
	{
		$clientVersion = (float) $_COOKIE['hedera_version'];

		if ($clientVersion < Web::getVersion ())
		{
			Web::sysInit ();

			$row = Web::$sysConn->getRow (
				'SELECT critical, changelog FROM version LIMIT 1');

			if (!$row || $row['critical'])
				throw new Rest\Exception ('Version', 'criticalVersion', $row['changelog']);
			else
				Rest\Service::addWarning ('Version', 'newVersion', $row['changelog']);
		}
	}

	// Getting the action

	$action = NULL;

	if (isset ($_REQUEST['action']))
		$action = $_REQUEST['action'];

	if ($action && Vn\Hedera\checkToken ($action))
	{
		$actionFile = 'rest/'. $action .'.php';

		if (file_exists ($actionFile))
		{
			Locale::addPath ('rest/'. $action);
			require_once ($actionFile);
			
			$module = new RestMod (Web::$conn);
			Rest\Service::setData ($module->run ());
		}
		else
			throw new Rest\Exception ('Rest', 'invalidAction', s('Invalid action'));
	}
}
catch (Vn\Web\SessionExpiredException $e)
{
	Rest\Service::setError ('Auth', 'sessionExpired', s('The session has expired'));
}
catch (Vn\Web\BadLoginException $e)
{
	Rest\Service::setError ('Auth', 'badLogin', s('Invalid login'));
}
catch (Rest\Exception $e)
{
	Rest\Service::setError ($e->getDomain (), $e->getCode (), $e->getMessage ());
}

myExitHandler ();

?>