<?php
/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*/

//Error reporting
$debug_enabled = true;

error_reporting(E_ALL & ~E_NOTICE);

if($debug_enabled)
{
	ini_set('display_startup_errors', 1);
	ini_set('display_errors', 1);
}
else
{
	ini_set('display_startup_errors', 0);
	ini_set('display_errors', 0);
}

// Lets give the script some ram!
ini_set('memory_limit', -1);

// remove php time limit
set_time_limit(0);


//added encoding setting cos CLI Unit teses were coming up with different output encoding
mb_internal_encoding('UTF-8');
iconv_set_encoding("internal_encoding", "UTF-8");//setting gave grief at some point, i suspect it was surrounding Lucene, but needed for ZF mime header decoding. this doesnt work, possible because conflicts with php.ini setting
iconv_set_encoding("input_encoding", "BASE-64");
iconv_set_encoding("output_encoding", "UTF-8");


define('APP_ROOT', realpath(dirname(dirname(dirname(__FILE__)))) . '/');

set_include_path(APP_ROOT . ":" . APP_ROOT . "library/:" . APP_ROOT . "library/Pear/:" . APP_ROOT . "application/models/");

require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
//$loader->registerNamespace('App_'); //for model namespacing
$loader->setFallbackAutoloader(true);
$loader->suppressNotFoundWarnings(false);
Zend_Loader::loadFile('Atmail/General.php', null, true);
Zend_Loader::loadFile('Atmail/RenderHelpers.php', null, true);

//HTMLPURIFIER prefix needed for HTMLfilter plugin
define('HTMLPURIFIER_PREFIX', APP_ROOT . 'library');

// try and start a new session
try
{
	Zend_Session::start();
}
catch (Exception $e)
{
	print_r($e);
	exit;	
}

// Set locale to browser locale and register in registry for global use
$locale = new Zend_Locale();
date_default_timezone_set('Australia/Brisbane');

Zend_Registry::set('Zend_Locale', $locale);

$frontController = Zend_Controller_Front::getInstance();
Zend_Controller_Action_HelperBroker::addPrefix('Atmail_Controller_Action_Helper');
$frontController->registerPlugin(new Atmail_Controller_Plugin_Authenticate);
//$frontController->throwExceptions(true); //disabled to push through to ErrorController
$frontController->addModuleDirectory(APP_ROOT . "application/modules");
$frontController->registerPlugin(new Zend_Controller_Plugin_ErrorHandler());
Zend_Controller_Action_HelperBroker::addPrefix('Atmail_Controller_Action_Helper');

// Get database configuration
try
{
	$dbConfig = new Zend_Config_Ini(APP_ROOT . "config/dbconfig.ini", 'production');
}
catch (Exception $e)
{
	print_r($e);
	exit;
}

$dbAdapter = dbAdapterFactory($dbConfig);
Zend_Db_Table::setDefaultAdapter($dbAdapter);
Zend_Registry::set('dbAdapter', $dbAdapter);

//Get main configuration from server
try
{
	$config = new Atmail_Config_Mysql($dbConfig, true);
}
catch(Exception $e)
{
	print_r($e);
	exit;
}

Zend_Registry::set('config', $config);
unset($config);
//set siteBaseUrl as script filename without /index.php or die if not running throuh index.php
define('ATMAIL_IMAP_ERR', '/tmp/atmail-imap-err');

$siteBaseUrl = substr($_SERVER["SCRIPT_NAME"],0,strpos($_SERVER["SCRIPT_NAME"],'index.php'));
Zend_Registry::set('siteBaseUrl', $siteBaseUrl);

/* Set up logs */
//set up logging and only enable logging depending on config settings
//N.B.: define('ATMAIL_IMAP_ERR', '/tmp/atmail-imap-err') - has been removed, now using global['imapLogging'] - on by default
//N.B.: file_exists('advancedDebugEnabled') - has been removed, now using global['debug'] - off by default


$log = new Atmail_Log();
$log->addPriority('atmail', 10); 
$log->addPriority('sysadmin', 20); 
$log->addPriority('imap', 30); 
$log->addPriority('firebug', 40); 

$logBasePath = APP_ROOT . 'log' . DIRECTORY_SEPARATOR;

//log errors by default even if not set in config 
//INTENTION: log all priority <= INFO
$errorLogging = ( isset( Zend_Registry::get('config')->global['errorLogging'] )? Zend_Registry::get('config')->global['errorLogging']:true);
if( $errorLogging == true || $errorLogging == 'true' || $errorLogging == 1 ) 
{

	$logPath = $logBasePath . 'error.log';
	if( !file_exists($logPath))
		touch($logPath);
	$writer = new Zend_Log_Writer_Stream($logPath);
	$filter = new Zend_Log_Filter_Priority(Zend_Log::INFO, '<'); //will only log entries to this log that are < INFO 
    $writer->addFilter($filter);
	$log->addWriter($writer);
}

// main debug log (no filters set so will log everything) - other logs also for more specific logging
//Only enabled if config debug == true
//INTENTION: only log priority == DEBUG
//INTENTION: only log priority == FIREBUG - i.e. use this to send errors to browser if they are ajax or XML (as in the RPC calls) so that it doesnt mess up the normal responce

$debugLogging = ( isset(Zend_Registry::get('config')->global['debug'])? Zend_Registry::get('config')->global['debug']:false);
if( $debugLogging == true || $debugLogging == 'true' || $debugLogging == 1 ) 
{

	//no filters set so will log everything
	$logPath = $logBasePath . 'debug.log';
	if( !file_exists($logPath))
		touch($logPath);
	$writer = new Zend_Log_Writer_Stream($logPath);
	$filter = new Zend_Log_Filter_Priority(Zend_Log::INFO, '>='); //will only log entries to this log where priority >= INFO 
	$filter = new Zend_Log_Filter_Priority(Zend_Log::DEBUG, '<='); //will only log entries to this log where priority <= DEBUG 
	$writer->addFilter($filter); 
	
	$log->addWriter($writer);
	$log->debug('');
	$log->debug('------------------------------');
	$log->debug('Hit starting up: ' . time());
	
	//we also set up a logger to log things to firebug console for debugging ajax, RPC, XML responces so that debug content doesnt mess with the body
	//set up a logger to log things to firebug console for debugging ajax, RPC, XML responces so that debug content doesnt mess with the body 
	$writer = new Zend_Log_Writer_Firebug();
	$filter = new Zend_Log_Filter_Priority(40, '=='); //will only log entries to this log where priority == DEBUG
	$writer->addFilter($filter);
	$log->addWriter($writer);
	
}

//log IMAP communication only if enabled in config
//INTENTION: log only where priority == IMAP 
$imapLogging = (isset(Zend_Registry::get('config')->global['imapLogging'])? Zend_Registry::get('config')->global['imapLogging']:false);
if( $imapLogging == true || $imapLogging == 'true' || $imapLogging == 1 ) 
{

	$logPath = $logBasePath . 'imap.log';
	define('IMAP_LOG_PATH', $logPath); //needed by imap debug shutdown logging, because registry gets shut down before imap connection being logged
	if( !file_exists($logPath))
		touch($logPath);
	$writer = new Zend_Log_Writer_Stream($logPath);
	$filter = new Zend_Log_Filter_Priority(30, '=='); //will only log entries to this log that are == IMAP 
    $writer->addFilter($filter);
	$log->addWriter($writer);
}

//log sysAdmin communication on by default unless diasbled in Config
//INTENTION: log only where priority == SYSADMIN e.g. quota warnings, login failures (with reasons) 
$sysAdminLogging = (isset(Zend_Registry::get('config')->global['sysAdminLogging'])? Zend_Registry::get('config')->global['sysAdminLogging']:true);
if( $sysAdminLogging == true || $sysAdminLogging == 'true' || $sysAdminLogging == 1 ) 
{

	$logPath = $logBasePath . 'sysadmin.log';
	if( !file_exists($logPath))
		touch($logPath);
	$writer = new Zend_Log_Writer_Stream($logPath);
	$filter = new Zend_Log_Filter_Priority(20, '=='); //will only log entries to this log that are == SYSADMIN 
    $writer->addFilter($filter);
	$log->addWriter($writer);
}



Zend_Registry::set('log', $log);
/* log setup complete */ 

/* validate license */
license::validate();
