<?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.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("Refresh: 0; url=index.php");
		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");
			if(isset($_POST) && isset($_POST["action_url"]) && !empty($_POST["action_url"])) {
				// if action attributes are passed in POST variable then append it to URL for
				// further processing
				$url = "index.php" . $_POST["action_url"];
				header("Refresh: 0; url=$url");
				exit;
			} else {
				header("Refresh: 0; url=index.php");
				exit;
			}
		}

		// add extra header
		header("X-Zarafa: ".phpversion("mapi").(defined("SVN") ? "-".SVN:""));

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

			// Get Attachment data from state and put it into the $_SESSION
			$attachment_state = new State('attachments');
			$attachment_state->open();
			$_SESSION['files'] = $attachment_state->read("files");
			$_SESSION['deleteattachment'] = $attachment_state->read("deleteattachment");
			$attachment_state->close();
			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 "dialog":
					// If the dialog is called with attachid in URL we want to call the upload attachment file 
					// first to upload the files to the server, and add them to session files.
					if($_GET && array_key_exists("attachment_id", $_GET)){
						$GLOBALS['PluginManager']->triggerHook("server.index.load.upload_attachment.before");
						include("server/upload_attachment.php");
						$GLOBALS['PluginManager']->triggerHook("server.index.load.upload_attachment.after");
						// Get Attachment data from $_SESSION and put it into the state
						// Do it now before outputting the webclient.php data, so that zarafa.php cannot be called
						// before we have written the data
						$attachment_state = new State('attachments');
						$attachment_state->open();
						$attachment_state->write("files", $_SESSION['files']);
						$attachment_state->write("deleteattachment", $_SESSION['deleteattachment']);
						$attachment_state->close();
					}
					$GLOBALS['PluginManager']->triggerHook("server.index.load.dialog.before");
					include("client/webclient.php");
					$GLOBALS['PluginManager']->triggerHook("server.index.load.dialog.after");
					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;
			}

			// Get Attachment data from $_SESSION and put it into the state
			$attachment_state = new State('attachments');
			$attachment_state->open();
			$attachment_state->write("files", $_SESSION['files']);
			$attachment_state->write("deleteattachment", $_SESSION['deleteattachment']);
			$attachment_state->close();
			// Prevent the SESSION data to be stored elsewhere
			unset($_SESSION['files'], $_SESSION['deleteattachment']);
		} 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
			cleanTemp(TMP_PATH, UPLOADED_ATTACHMENT_MAX_LIFETIME);
					
			// 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");
		}
	} else { // Not authenticated, goto login page
		// Create global language object
		$GLOBALS["language"] = new Language();
		$GLOBALS["language"]->setLanguage(LANG);

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