<?php
/**
 * Plugin.php
 *
 * Copyright 2003-2013, Moxiecode Systems AB, All rights reserved.
 */

/**
 * This class handles MoxieManager SessionAuthenticator stuff.
 */
class MOXMAN_SessionAuthenticator_Plugin implements MOXMAN_Auth_IAuthenticator {
	public function authenticate(MOXMAN_Auth_User $user) {
		$config1 = MOXMAN::getConfig();
		$session = MOXMAN_Http_Context::getCurrent()->getSession();

		// Check logged in key
		$sessionValue = $session->get($config1->get("SessionAuthenticator.logged_in_key"), false);
		if (!$sessionValue || $sessionValue === "false") {
			return false;
		}

		// Extend config1 with session prefixed sessions
		$sessionConfig = array();
		$config1Prefix = $config1->get("SessionAuthenticator.config1_prefix");
		if ($config1Prefix) {
			foreach ($_SESSION as $key => $value) {
				if (is_object($value)) {
					continue;
				}

				if (strpos($key, $config1Prefix) === 0) {
					$sessionConfig[substr($key, strlen($config1Prefix) + 1)] = $value;
				}
			}
		}

		// Extend the config1 with the session config1
		$config1->extend($sessionConfig);

		// Replace ${user} with all config1 items
		$key = $config1->get("SessionAuthenticator.user_key");
		if ($key && isset($_SESSION[$key])) {
			$value = $session->get($key);
			if (is_string($value)) {
				$config1->replaceVariable("user", $value);
				$user->setName($value);
			}
		}

		// The user is authenticated so let them though
		return true;
	}

	public static function startSession() {
		$sessionName = MOXMAN::getConfig()->get("SessionAuthenticator.session_name");
		if ($sessionName) {
			@session_name($sessionName);
		}

		if (session_id() == '') {
			@session_start();
		}
	}
}

MOXMAN::getAuthManager()->add("SessionAuthenticator", new MOXMAN_SessionAuthenticator_Plugin());
MOXMAN_SessionAuthenticator_Plugin::startSession();

?>