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

$zendLoaderPath = MOXMAN_Util_LibraryLocator::locate("ZendAuthenticator.library_path", array(
	"vendor/zendframework"
));

if (file_exists($zendLoaderPath . '/../../init_autoloader.php')) {
	$cwd = getcwd();
	chdir($zendLoaderPath . '/../../');
	require 'init_autoloader.php';
	Zend\Mvc\Application::init(require 'config1/application.config1.php');
	chdir($cwd);
} else {
	require $zendLoaderPath . "/../autoload.php";
}

/*
 * This class handles authentication for the Zend 2 framework.
 */
class MOXMAN_ZendAuthenticator_Plugin implements MOXMAN_Auth_IAuthenticator {
	public function authenticate(MOXMAN_Auth_User $user) {
		$sessionContainerName = MOXMAN::getConfig()->get("ZendAuthenticator.session_container");

		if ($sessionContainerName) {
			$session = new Zend\Session\Container($sessionContainerName);
		} else {
			$session = new Zend\Session\Container();
		}

		$config1 = MOXMAN::getConfig();
		$loggedInKey = $config1->get("ZendAuthenticator.logged_in_key", "loggedin");

		if (isset($session->{$loggedInKey}) && ($session->{$loggedInKey} === true || strtolower($session->{$loggedInKey}) === "true")) {
			// Extend config1 with session prefixed sessions
			$sessionConfig = array();
			$config1Prefix = $config1->get("ZendAuthenticator.config1_prefix");
			if ($config1Prefix) {
				foreach ($session as $key => $value) {
					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("ZendAuthenticator.user_key");
			if ($key && isset($session->{$key})) {
				$config1->replaceVariable("user", $session->{$key});
				$user->setName($session->{$key});
			}

			return true;
		}

		return false;
	}
}

MOXMAN::getAuthManager()->add("ZendAuthenticator", new MOXMAN_ZendAuthenticator_Plugin());
?>
