<?php
	/**
	 * This is the entry point for every request that should return HTML
	 * 
	 * (one exception is that it also returns translated text for javascript)
	 */
	// load config file
	if (!file_exists("config.php")){
		die("<strong>config.php is missing!</strong>");
	}

	include("init.php");
	include("config.php");
	include("defaults.php");

	ob_start();
	setlocale(LC_CTYPE, "en_US.UTF-8");

	// Start the session
	session_name(COOKIE_NAME);

	if($_POST && array_key_exists(COOKIE_NAME, $_POST))
		session_id($_POST[COOKIE_NAME]);

	session_start();
	
	// check if config is correct
	if (defined("CONFIG_CHECK")){
		include("server/class.configcheck.php");
		new ConfigCheck(CONFIG_CHECK);
	}

	// Include the files
	require("mapi/mapi.util.php");
	require("mapi/mapicode.php");
	require("mapi/mapidefs.php");
	require("mapi/mapitags.php");
	require("mapi/mapiguid.php");
	require("mapi/class.baseexception.php");
	require("mapi/class.mapiexception.php");

	require("server/exceptions/class.ZarafaException.php");
	require("server/exceptions/class.ZarafaErrorException.php");
	require("server/util.php");
	include("server/gettext.php");

	require("server/core/class.json.php");
	require("server/core/constants.php");
	require("server/core/class.conversion.php");
	require("server/core/class.mapisession.php");
	require("server/core/class.entryid.php");
	
	require("server/core/class.settings.php");
	require("server/core/class.language.php");
	include("server/core/class.properties.php");

	require("server/core/class.state.php");
	require("server/core/class.attachmentstate.php");

	require("server/core/class.pluginmanager.php");
	require("server/core/class.plugin.php");

	// Destroy session if an user loggs out
	if($_GET && array_key_exists("logout", $_GET)) {
		$_SESSION = array();
		
		if (isset($_COOKIE[session_name()])) {
			setcookie(session_name(), '', time()-42000, '/');
		}
		session_destroy();

		header("Location: index.php", true, 303);
		exit;
	}

	// Set the session variables if it is posted
	if($_POST && array_key_exists("username", $_POST) && array_key_exists("password", $_POST)) {
		$_SESSION["username"] = $_POST["username"];
		$_SESSION["password"] = $_POST["password"];
	}
	if(!DISABLE_REMOTE_USER_LOGIN){
		// REMOTE_USER is set when apache has authenticated the user
		if( ! $_POST && $_SERVER && array_key_exists("REMOTE_USER", $_SERVER)) {
			$_SESSION["username"] = $_SERVER['REMOTE_USER'];
			if (LOGINNAME_STRIP_DOMAIN) {
				$_SESSION["username"] = ereg_replace('@.*', '', $_SESSION["username"]);
			}
			$_SESSION["password"] = "";
		}
	}


	// Create global mapi object. This object is used in many other files
	$GLOBALS["mapisession"] = new MAPISession();
	if (isset($_SESSION["username"]) && isset($_SESSION["password"])) {
		$sslcert_file = defined('SSLCERT_FILE') ? SSLCERT_FILE : null;
		$sslcert_pass = defined('SSLCERT_PASS') ? SSLCERT_PASS : null;
		$hresult = $GLOBALS["mapisession"]->logon($_SESSION["username"], $_SESSION["password"], DEFAULT_SERVER, $sslcert_file, $sslcert_pass);
		if ($hresult != NOERROR){
			// login failed, remove session
			$_SESSION = array();
			$_SESSION["hresult"] = $hresult;
		}
	}

	// Check if user is authenticated
	if ($GLOBALS["mapisession"]->isLoggedOn()) {
		// Authenticated

		// Instantiate Plugin Manager
		$GLOBALS['PluginManager'] = new PluginManager(ENABLE_PLUGINS);
		$GLOBALS['PluginManager']->detectPlugins(DISABLED_PLUGINS_LIST);
		$GLOBALS['PluginManager']->initPlugins(DEBUG_LOADER);

		// Create global properties object
		$GLOBALS["properties"] = new Properties();
		
		// Create globals settings object
		$GLOBALS["settings"] = new Settings();
		
		// Create global language object
		$GLOBALS["language"] = new Language();

		// Create global entryId object
		$GLOBALS["entryid"] = new EntryId();

		// Set session settings (language & style)
		foreach($GLOBALS["settings"]->getSessionSettings() as $key=>$value){
			$_SESSION[$key] = $value;
		}
		
		// Get settings from post or session or settings
		if (isset($_REQUEST["language"]) && $GLOBALS["language"]->is_language($_REQUEST["language"])) {
			$lang = $_REQUEST["language"];
			$GLOBALS["settings"]->set("zarafa/v1/main/language", $lang);
		} else if(isset($_SESSION["lang"])) {
			$lang = $_SESSION["lang"];
			$GLOBALS["settings"]->set("zarafa/v1/main/language", $lang);
		} else {
			$lang = $GLOBALS["settings"]->get("zarafa/v1/main/language");
			if (empty($lang)) {
				$lang = LANG;
				$GLOBALS["settings"]->set("zarafa/v1/main/language", $lang);
			}
		}

		$GLOBALS["language"]->setLanguage($lang);
		if($_GET && array_key_exists("logon", $_GET)) {
			$GLOBALS['PluginManager']->triggerHook("server.index.login.success");
			header("Location: index.php", true, 303);
			exit;
		}

		// add extra header
		header("X-Zarafa: " . trim(file_get_contents('version')));

		// external files who need our login
		if ($_GET && array_key_exists("load", $_GET)) {

			switch ($_GET["load"]) {
				case "translations.js":
					$GLOBALS['PluginManager']->triggerHook("server.index.load.jstranslations.before");
					include("client/translations.js.php");
					$GLOBALS['PluginManager']->triggerHook("server.index.load.jstranslations.after");
					break;
				case "custom":
					$GLOBALS['PluginManager']->triggerHook("server.index.load.custom", array('name' => $_GET['name']));
					break;
				case "upload_attachment":
					$GLOBALS['PluginManager']->triggerHook("server.index.load.upload_attachment.before");
					include("server/upload_attachment.php");
					$GLOBALS['PluginManager']->triggerHook("server.index.load.upload_attachment.after");
					break;
				case "download_attachment":
					$GLOBALS['PluginManager']->triggerHook("server.index.load.download_attachment.before");
					include("client/download_attachment.php");
					$GLOBALS['PluginManager']->triggerHook("server.index.load.download_attachment.after");
					break;
				case "download_message":
					$GLOBALS['PluginManager']->triggerHook("server.index.load.download_message.before");
					include("client/download_message.php");
					$GLOBALS['PluginManager']->triggerHook("server.index.load.download_message.after");
					break;
				default:
					// These hooks are defined twice (also when no "load" argument is supplied)
					$GLOBALS['PluginManager']->triggerHook("server.index.load.main.before");
					include("client/webclient.php");
					$GLOBALS['PluginManager']->triggerHook("server.index.load.main.after");
					break;
			}
		} else if ($_GET && array_key_exists("authenticate", $_GET)) {
			$version = trim(file_get_contents('version'));
			$data = array(
				"settings" => $GLOBALS["settings"]->getJSON(),
				"properties" => $GLOBALS["properties"]->getJSON(),
				"languages" => $GLOBALS["language"]->getJSON(),
				"user" => array(
					"username" 	=> addslashes($GLOBALS["mapisession"]->getUserName()),
					"fullname" 	=> addslashes($GLOBALS["mapisession"]->getFullName()),
					"entryid" 	=> bin2hex($GLOBALS["mapisession"]->getUserEntryid()),
					"email_address" => addslashes($GLOBALS["mapisession"]->getEmailAddress()),
					"smtp_address" 	=> addslashes($GLOBALS["mapisession"]->getSMTPAddress()),
					"search_key" 	=> bin2hex($GLOBALS["mapisession"]->getSearchKey()),
					"sessionid" 	=> session_id()
				),
				"version" => array(
					"webapp"	=> $version,
					"zcp"		=> phpversion('mapi'),
					"server"	=> DEBUG_SHOW_SERVER ? DEBUG_SERVER_ADDRESS : '',
					"svn"		=> DEBUG_LOADER === LOAD_SOURCE ? svnversion() : ''
				)
			);
			echo JSON::Encode(array("zarafa" => $data));
		} else if ($_GET && array_key_exists("verify", $_GET)) {
			
			$user = $_GET["verify"];
			
			if($user == $_SESSION['username'])
				print "1";
			else
				print "0";
			
		} else {
			// Clean up old state files in tmp/session/
			$state = new State("index");
			$state->clean();

			// Clean up old attachments in tmp/attachments/
			$state = new AttachmentState();
			$state->clean();

			// clean search folders
			cleanSearchFolders();

			// These hooks are defined twice (also when there is a "load" argument supplied)
			$GLOBALS['PluginManager']->triggerHook("server.index.load.main.before");
			// Include webclient
			include("client/webclient.php");
			$GLOBALS['PluginManager']->triggerHook("server.index.load.main.after");
		}

		// Save the settings to the MAPI store
		$GLOBALS['settings']->saveSettings();

	} else { // Not authenticated, goto login page
		// Create global language object
		$GLOBALS["language"] = new Language();
		$GLOBALS["language"]->setLanguage(LANG);

		include("client/login.php");
	}
?>
